Programs & Examples On #Forms

A form is essentially a container that can be used to hold any amount of any subset of several types of data. HTML forms are used to pass data to a server. VB and C# forms are the windows used to interact with the user.

Access Form - Syntax error (missing operator) in query expression

Put [] around any field names that had spaces (as Dreden says) and save your query, close it and reopen it.

Using Access 2016, I still had the error message on new queries after I added [] around any field names... until the Query was saved.

Once the Query is saved (and visible in the Objects' List), closed and reopened, the error message disappears. This seems to be a bug from Access.

Check if input value is empty and display an alert

You could create a function that checks every input in an input class like below

 function validateForm() {
    var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
        return $.trim(this.value).length === 0;
    }).length > 0

    if (anyFieldIsEmpty) {
        alert("Fill all the necessary fields");
        var empty = $(".myclass").filter(function () {
            return $.trim(this.value).length === 0;
        empty.css("border", "1px solid red");
        return false;
    } else {
        return true;

What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.

Auto submit form on page load

This is the way it worked for me, because with other methods the form was sent empty:

<form name="yourform" id="yourform" method="POST" action="yourpage.html">
    <input type=hidden name="data" value="yourdata">
    <input type="submit" id="send" name="send" value="Send">
    document.addEventListener("DOMContentLoaded", function(event) {

How to disable input conditionally in vue.js

To toggle the input's disabled attribute was surprisingly complex. The issue for me was twofold:

(1) Remember: the input's "disabled" attribute is NOT a Boolean attribute.
The mere presence of the attribute means that the input is disabled.

However, the Vue.js creators have prepared this...

(Thanks to @connexo for this... How to add disabled attribute in input text in vuejs?)

(2) In addition, there was a DOM timing re-rendering issue that I was having. The DOM was not updating when I tried to toggle back.

Upon certain situations, "the component will not re-render immediately. It will update in the next 'tick.'"

From Vue.js docs:

The solution was to use:

    this.disableInputBool = true

Fuller example workflow:

<div @click="allowInputOverwrite">

<button @click="disallowInputOverwrite">
    press me (do stuff in method, then disable input bool again)


export default {
  data() {
    return {
      disableInputBool: true
  methods: {
      this.disableInputBool = false
      // accomplish other stuff here.
        this.disableInputBool = true


When should I use GET or POST method? What's the difference between them?

Get and Post methods have nothing to do with the server technology you are using, it works the same in php, or ruby. GET and POST are part of HTTP protocol. As mark noted, POST is more secure. POST forms are also not cached by the browser. POST is also used to transfer large quantities of data.

How to reset a form using jQuery with .reset() method

you may try using trigger() Reference Link


Is there a W3C valid way to disable autocomplete in a HTML form?

I would be very surprised if W3C would have proposed a way that would work with (X)HTML4. The autocomplete feature is entirely browser-based, and was introduced during the last years (well after the HTML4 standard was written).

Wouldn't be surprised if HTML5 would have one, though.

Edit: As I thought, HTML5 does have that feature. To define your page as HTML5, use the following doctype (i.e: put this as the very first text in your source code). Note that not all browsers support this standard, as it's still in draft-form.

<!DOCTYPE html>

How to change an element's title attribute using jQuery

If you are creating a div and trying to add a title to it.


var myDiv= document.createElement("div");

href around input type submit

You can do do it. The input type submit should be inside of a form. Then all you have to do is write the link you want to redirect to inside the action attribute that is inside the form tag.

spacing between form fields

In your CSS file:

input { margin-bottom: 10px; }

Can I use an HTML input type "date" to collect only a year?

No you can not but you may want to use input type number as a workaround. Look at the following example:

<input type="number" min="1900" max="2099" step="1" value="2016" />

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw


Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.

Please consult the appendix for information about security issues for forms.

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.

A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.

As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.


This is the default content type. Forms submitted with this content type must be encoded as follows:

Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by=' and name/value pairs are separated from each other by `&'.

application/x-www-form-urlencoded the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:


The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

Two submit buttons in one form

There’s a new HTML5 approach to this, the formaction attribute:

<button type="submit" formaction="/action_one">First action</button>
<button type="submit" formaction="/action_two">Second action</button>

Apparently this does not work in IE9 and earlier, but for other browsers you should be fine (see: HTML <button> formaction Attribute).

Personally, I generally use Javascript to submit forms remotely (for faster perceived feedback) with this approach as backup. Between the two, the only people not covered are IE<9 with Javascript disabled.

Of course, this may be inappropriate if you’re basically taking the same action server-side regardless of which button was pushed, but often if there are two user-side actions available then they will map to two server-side actions as well.

Edit: As noted by Pascal_dher in the comments, this attribute is also available on the <input> tag as well.

Disabled form fields not submitting data

add CSS or class to the input element which works in select and text tags like

style="pointer-events: none;background-color:#E9ECEF"

how to POST/Submit an Input Checkbox that is disabled?

You could handle it this way... For each checkbox, create a hidden field with the same name attribute. But set the value of that hidden field with some default value that you could test against. For example..

<input type="checkbox" name="myCheckbox" value="agree" />
<input type="hidden" name="myCheckbox" value="false" />

If the checkbox is "checked" when the form is submitted, then the value of that form parameter will be


If the checkbox is not checked, then the value would be


You could use any value instead of "false", but you get the idea.

How can I set the form action through JavaScript?

Very easy solution with jQuery:

$('#myFormId').attr('action', 'myNewActionTarget.html');

Your form:

<form action=get_action() id="myFormId">

What's the proper value for a checked attribute of an HTML checkbox?

  1. checked
  2. checked=""
  3. checked="checked"

    are equivalent;

according to spec checkbox '----? checked = "checked" or "" (empty string) or empty Specifies that the element represents a selected control.---'

c# open a new form then close the current form?

I think this is much easier :)

    private void btnLogin_Click(object sender, EventArgs e)
        //var mm = new MainMenu();
        //mm.FormClosed += (s, args) => this.Close();

        MainMenu mm = new MainMenu();


Styling Password Fields in CSS

The best I can find is to set input[type="password"] {font:small-caption;font-size:16px}


input {_x000D_
  font: small-caption;_x000D_
  font-size: 16px;_x000D_
<input type="password">

Using PUT method in HTML form

XHTML 1.x forms only support GET and POST. GET and POST are the only allowed values for the "method" attribute.

angular2 submit form by pressing enter without submit button

Just simply add (keyup.enter)="yourFunction()"

Can you style html form buttons with css?

You might want to add:

-webkit-appearance: none; 

if you need it looking consistent on Mobile Safari...

jQuery: Clearing Form Inputs

I'd recomment using good old javascript:


Resetting Select2 value in dropdown with reset button

You can also reset select2 value using

$(function() {
  $('#d').select2('data', null)

alternately you can pass 'allowClear': true when calling select2 and it will have an X button to reset its value.

How to access html form input from code behind

If you are accessing a plain HTML form, it has to be submitted to the server via a submit button (or via javascript post). This usually means that your form definition will look like this (I'm going off of memory, make sure you check the html elements are correct):

<form method="POST" action="page.aspx">

<input id="customerName" name="customerName" type="Text" />
<input id="customerPhone" name="customerPhone" type="Text" />
<input value="Save" type="Submit" />


You should be able to access the customerName and customerPhone data like this:

string n = String.Format("{0}", Request.Form["customerName"]);

If you have method="GET" in the form (not recommended, it messes up your URL space), you will have to access the form data like this:

string n = String.Format("{0}", Request.QueryString["customerName"]);

This of course will only work if the form was 'Posted', 'Submitted', or done via a 'Postback'. (i.e. somebody clicked the 'Save' button, or this was done programatically via javascript.)

Also, keep in mind that accessing these elements in this manner can only be done when you are not using server controls (i.e. runat="server"), with server controls the id and name are different.

How do I make a "div" button submit the form its sitting in?

Are you aware of <button> elements? <button> elements can be styled just like <div> elements and can have type="submit" so they submit the form without javascript:

<form action="whatever.html" method="post">  
    <button name="mysubmitbutton" id="mysubmitbutton" type="submit" class="customButton">  
    Button Text

Using a <button> is also more semantic, whereas <div> is very generic. You get the following benefits for free:

  • JavaScript is not necessary to submit the form
  • Accessibility tools, e.g. screen readers, will (correctly) treat it as a button and not part of the normal text flow
  • <button type="submit"> becomes a "default" button, which means the return key will automatically submit the form. You can't do this with a <div>, you'd have to add a separate keydown handler to the <form> element.

There's one (non-) caveat: a <button> can only have phrasing content, though it's unlikely anyone would need any other type of content when using the element to submit a form.

disable all form elements inside div

If your form inside div simply contains form inputting elements, then this simple query will disable every element inside form tag:

<div id="myForm">
    <form action="">

However, it will also disable other than inputting elements in form, as it's effects will only be seen on input type elements, therefore suitable majorly for every type of forms!

$('#myForm *').attr('disabled','disabled');

Clear text field value in JQuery

If you are using jQuery, then you can use this:

// var doc_val_check = $('#doc_title').val(); - No need of this!
if ($('#doc_title').val().length > 0) {

How to convert Base64 String to javascript file object like as from file input form?

I had a very similar requirement (importing a base64 encoded image from an external xml import file. After using xml2json-light library to convert to a json object, I was able to leverage insight from cuixiping's answer above to convert the incoming b64 encoded image to a file object.

const imgName = incomingImage['FileName'];
const imgExt = imgName.split('.').pop();
let mimeType = 'image/png';
if (imgExt.toLowerCase() !== 'png') {
    mimeType = 'image/jpeg';
const imgB64 = incomingImage['_@ttribute'];
const bstr = atob(imgB64);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
  u8arr[n] = bstr.charCodeAt(n);
const file = new File([u8arr], imgName, {type: mimeType});

My incoming json object had two properties after conversion by xml2json-light: FileName and _@ttribute (which was b64 image data contained in the body of the incoming element.) I needed to generate the mime-type based on the incoming FileName extension. Once I had all the pieces extracted/referenced from the json object, it was a simple task (using cuixiping's supplied code reference) to generate the new File object which was completely compatible with my existing classes that expected a file object generated from the browser element.

Hope this helps connects the dots for others.

Prevent form submission on Enter key press

Cross Browser Solution

Some older browsers implemented keydown events in a non-standard way.

KeyBoardEvent.key is the way it is supposed to be implemented in modern browsers.

which and keyCode are deprecated nowadays, but it doesn't hurt to check for these events nonetheless so that the code works for users that still use older browsers like IE.

The isKeyPressed function checks if the pressed key was enter and event.preventDefault() hinders the form from submitting.

  if (isKeyPressed(event, 'Enter', 13)) {
    console.log('enter was pressed and is prevented');

Minimal working example


function isKeyPressed(event, expectedKey, expectedCode) {
  const code = event.which || event.keyCode;

  if (expectedKey === event.key || code === expectedCode) {
    return true;
  return false;

document.getElementById('myInput').addEventListener('keydown', function(event) {
  if (isKeyPressed(event, 'Enter', 13)) {
    console.log('enter was pressed and is prevented');


  <input id="myInput">

How to place two forms on the same page?

Hope this will help you. Assumed that login form has: username and password inputs.

if(isset($_POST['username']) && trim($_POST['username']) != "" && isset($_POST['password']) && trim($_POST['password']) != ""){
} else {

Getting an option text/value with JavaScript

You can use:

var option_user_selection = element.options[ element.selectedIndex ].text

PHP form send email to multiple recipients

Use comma separated values as below.

$email_to = 'Mary <[email protected]>, Kelly <[email protected]>';
@mail($email_to, $email_subject, $email_message, $headers);

or run a foreach for email address

//list of emails in array format and each one will see their own to email address
$arrEmail = array('Mary <[email protected]>', 'Kelly <[email protected]>');

foreach($arrEmail as $key => $email_to)
    @mail($email_to, $email_subject, $email_message, $headers);

Disable validation of HTML5 form elements

I just wanted to add that using the novalidate attribute in your form will only prevent the browser from sending the form. The browser still evaluates the data and adds the :valid and :invalid pseudo classes.

I found this out because the valid and invalid pseudo classes are part of the HTML5 boilerplate stylesheet which I have been using. I just removed the entries in the CSS file that related to the pseudo classes. If anyone finds another solution please let me know.

If input field is empty, disable submit button

You are disabling only on document.ready and this happens only once when DOM is ready but you need to disable in keyup event too when textbox gets empty. Also change $(this).val.length to $(this).val().length

        if($(this).val().length !=0)
            $('.sendButton').attr('disabled', false);            

Or you can use conditional operator instead of if statement. also use prop instead of attr as attribute is not recommended by jQuery 1.6 and above for disabled, checked etc.

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method, jQuery docs

        $('.sendButton').prop('disabled', this.value == "" ? true : false);     

Calling a PHP function from an HTML form in the same file

Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:

    function test() {
        echo $_POST["user"];

    if (isset($_POST[])) { // If it is the first time, it does nothing

<form action="test.php" method="post">
    <input type="text" name="user" placeholder="enter a text" />
    <input type="submit" value="submit" onclick="test()" />

No value accessor for form control

enter image description here

enter image description here

You can see formControlName in label , removing this solved my problem

How do I select the parent form based on which submit button is clicked?

You can select the form like this:

    var form = $(this).parents('form:first');

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission

To select fields inside the form, use the form context. For example:


Check if option is selected with jQuery, if not select a default

While I'm not sure about exactly what you want to accomplish, this bit of code worked for me.

<select id="mySelect" multiple="multiple">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>

<script type="text/javascript"> 
$(document).ready(function() {
  if (!$("#mySelect option:selected").length) {
    $("#mySelect option[value='3']").attr('selected', 'selected');

Clear input fields on form submit

Still using empty strings you can use:

document.getElementById("name").value = '';
document.getElementById("review").value = '';

Javascript to Select Multiple options

<script language="JavaScript" type="text/javascript">
function loopSelected()
  var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
  var selectedArray = new Array();
  var selObj = document.getElementById('selSeaShells');
  var i;
  var count = 0;
  for (i=0; i<selObj.options.length; i++) {
    if (selObj.options[i].selected) {
      selectedArray[count] = selObj.options[i].value;
  txtSelectedValuesObj.value = selectedArray;
function openInNewWindow(frm)
  // open a blank window
  var aWindow ='', 'Tutorial004NewWindow',

  // set the target to the blank window = 'Tutorial004NewWindow';

  // submit
<form action="tutorial004_nw.html" method="get">
  <table border="1" cellpadding="10" cellspacing="0">
    <td valign="top">
      <input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
      <input type="button" value="Loop Selected" onclick="loopSelected();" />
      <br />
      <select name="selSea" id="selSeaShells" size="5" multiple="multiple">
        <option value="val0" selected>sea zero</option>
        <option value="val1">sea one</option>
        <option value="val2">sea two</option>
        <option value="val3">sea three</option>
        <option value="val4">sea four</option>
    <td valign="top">
      <input type="text" id="txtSelectedValues" />
      selected array

HTML5 textarea placeholder not appearing

I know this post has been (very well) answered by Aquarelle but just in case somebody is having this issue with other tag forms with no text such as inputs i'll leave this here:

If you have an input in your form and placeholder is not showing because a white space at the beginning, this may be caused for you "value" attribute. In case you are using variables to fill the value of an input check that there are no white spaces between the commas and the variables.

example using twig for php framework symfony :

<input type="text" name="subject" value="{{ subject }}" placeholder="hello" />       <-- this is ok
<input type="text" name="subject" value" {{ subject }} " placeholder="hello" />      <-- this will not show placeholder 

In this case the tag between {{ }} is the variable, just make sure you are not leaving spaces between the commas because white space is also a valid character.

How to submit a form on enter when the textarea has focus?

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea>

Keycode 13 is the enter key.

Here's how you could do it with jQuery like as Stackoverflow does:

<textarea class="commentarea"></textarea>


$(document).ready(function() {
    $('.commentarea').keydown(function(event) {
        if (event.which == 13) {

Reading file input from a multipart/form-data POST

I've had some issues with parser that are based on string parsing particularly with large files I found it would run out of memory and fail to parse binary data.

To cope with these issues I've open sourced my own attempt at a C# multipart/form-data parser here


  • Handles very large files well. (Data is streamed in and streamed out while reading)
  • Can handle multiple file uploads and automatically detects if a section is a file or not.
  • Returns files as a stream not as a byte[] (good for large files).
  • Full documentation for the library including a MSDN-style generated website.
  • Full unit tests.


  • Doesn't handle non-multipart data.
  • Code is more complicated then Lorenzo's

Just use the MultipartFormDataParser class like so:

Stream data = GetTheStream();

// Boundary is auto-detected but can also be specified.
var parser = new MultipartFormDataParser(data, Encoding.UTF8);

// The stream is parsed, if it failed it will throw an exception. Now we can use
// your data!

// The key of these maps corresponds to the name field in your
// form
string username = parser.Parameters["username"].Data;
string password = parser.Parameters["password"].Data

// Single file access:
var file = parser.Files.First();
string filename = file.FileName;
Stream data = file.Data;

// Multi-file access
foreach(var f in parser.Files)
    // Do stuff with each file.

In the context of a WCF service you could use it like this:

public ResponseClass MyMethod(Stream multipartData)
    // First we need to get the boundary from the header, this is sent
    // with the HTTP request. We can do that in WCF using the WebOperationConext:
    var type = WebOperationContext.Current.IncomingRequest.Headers["Content-Type"];

    // Now we want to strip the boundary out of the Content-Type, currently the string
    // looks like: "multipart/form-data; boundary=---------------------124123qase124"
    var boundary = type.Substring(type.IndexOf('=')+1);

    // Now that we've got the boundary we can parse our multipart and use it as normal
    var parser = new MultipartFormDataParser(data, boundary, Encoding.UTF8);


Or like this (slightly slower but more code friendly):

public ResponseClass MyMethod(Stream multipartData)
    var parser = new MultipartFormDataParser(data, Encoding.UTF8);

Documentation is also available, when you clone the repository simply navigate to HttpMultipartParserDocumentation/Help/index.html

How to transfer data from JSP to servlet when submitting HTML form

first up on create your jsp file : and write the text field which you want
for ex:

after that create your servlet class:

public class test{

protected void doGet(paramter , paramter){

String name  = request.getparameter("name");


Using the HTML5 "required" attribute for a group of checkboxes?

I had the same problem and I my solution was this:


<form id="processForm.php" action="post">
  <div class="input check_boxes required wish_payment_type">
    <div class="wish_payment_type">
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_1">
        <input class="check_boxes required" id="wish_payment_type_1" name="wish[payment_type][]" type="checkbox" value="1">Foo
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_2">
        <input class="check_boxes required" id="wish_payment_type_2" name="wish[payment_type][]" type="checkbox" value="2">Bar
    <span class="checkbox payment-radio">
      <label for="wish_payment_type_3">
        <input class="check_boxes required" id="wish_payment_type_3" name="wish[payment_type][]" type="checkbox" value="3">Buzz

      <input id='submit' type="submit" value="Submit">


var verifyPaymentType = function () {
  var checkboxes = $('.wish_payment_type .checkbox');
  var inputs = checkboxes.find('input');
  var first = inputs.first()[0];

  inputs.on('change', function () {

  first.setCustomValidity(checkboxes.find('input:checked').length === 0 ? 'Choose one' : '');


submitting a GET form with query string params and hidden params disappear

What you can do is using a simple foreach on the table containing the GET information. For example in php :

foreach ($_GET as $key => $value) {
    echo("<input type='hidden' name='$key' value='$value'/>");

AJAX Mailchimp signup form integration

You don't need an API key, all you have to do is plop the standard mailchimp generated form into your code ( customize the look as needed ) and in the forms "action" attribute change post?u= to post-json?u= and then at the end of the forms action append &c=? to get around any cross domain issue. Also it's important to note that when you submit the form you must use GET rather than POST.

Your form tag will look something like this by default:

<form action="" method="post" ... >

change it to look something like this

<form action="" method="get" ... >

Mail Chimp will return a json object containing 2 values: 'result' - this will indicate if the request was successful or not ( I've only ever seen 2 values, "error" and "success" ) and 'msg' - a message describing the result.

I submit my forms with this bit of jQuery:

$(document).ready( function () {
    // I only have one form on the page but you can be more specific if need be.
    var $form = $('form');

    if ( $form.length > 0 ) {
        $('form input[type="submit"]').bind('click', function ( event ) {
            if ( event ) event.preventDefault();
            // validate_input() is a validation function I wrote, you'll have to substitute this with your own.
            if ( validate_input($form) ) { register($form); }

function register($form) {
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        cache       : false,
        dataType    : 'json',
        contentType: "application/json; charset=utf-8",
        error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
        success     : function(data) {
            if (data.result != "success") {
                // Something went wrong, do something to notify the user. maybe alert(data.msg);
            } else {
                // It worked, carry on...

Form content type for a json HTTP POST?

It looks like people answered the first part of your question (use application/json).

For the second part: It is perfectly legal to send query parameters in a HTTP POST Request.


POST /members?id=1234 HTTP/1.1
Content-Type: application/json

{"email":"[email protected]"}

Query parameters are commonly used in a POST request to refer to an existing resource. The above example would update the email address of an existing member with the id of 1234.

jQuery's .on() method combined with the submit event

The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:



// re-attach to all forms

Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:

function bindItems(){

So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.


I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.

Angular is automatically adding 'ng-invalid' class on 'required' fields

Try to add the class for validation dynamically, when the form has been submitted or the field is invalid. Use the form name and add the 'name' attribute to the input. Example with Bootstrap:

<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
    <label class="col-sm-2 control-label" for="username">Username*</label>
    <div class="col-sm-10 col-md-9">
        <input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>

It is also important, that your form has the ng-submit="" attribute:

<form name="myForm" ng-submit="checkSubmit()" novalidate>
 <!-- input fields here -->

  <button type="submit">Submit</button>

You can also add an optional function for validation to the form:

//within your controller (some extras...)

$scope.checkSubmit = function () {

   if ($scope.myForm.$valid) {
        alert('All good...'); //next step!

   else {
        alert('Not all fields valid! Do something...');


Now, when you load your app the class 'has-error' will only be added when the form is submitted or the field has been touched. Instead of:

You could also use:

Auto-Submit Form using JavaScript

This solution worked for me:

<body onload="setTimeout(function() { document.myform.submit() }, 5000)">
   <form action=TripRecorder name="myform">
      <textarea id="result1"  name="res1" value="str1" cols="20" rows="1" ></textarea> <br> <br/>
      <textarea id="result2" name="res2" value="str2" cols="20" rows="1" ></textarea>

What is &amp used for

That's a great example. When &current is parsed into a text node it is converted to ¤t. When parsed into an attribute value, it is parsed as &current.

If you want &current in a text node, you should write &amp;current in your markup.

The gory details are in the HTML5 parsing spec - Named Character Reference State

HTML form action and onsubmit issues

You should stop the submit procedure by returning false on the onsubmit callback.

    function checkRegistration(){
            alert('Given data is not correct');
            return false;
        return true;

<form onsubmit="return checkRegistration()"...

Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:

    function checkRegistration(){
        var form_valid = (document.getElementById('some_input').value == 'google');
            alert('Given data is incorrect');
            return false;
        return true;

<form onsubmit="return checkRegistration()" method="get" action="">
    Write google to go to google...<br/>
    <input type="text" id="some_input" value=""/>
    <input type="submit" value="google it"/>

Submit form after calling e.preventDefault()

Why not bind the submit button event than the form itself? it would really much easier and safer if you bind the buttons than the form itself as the form will mostly submit unless you will use preventDefault()

$("#btn-submit").on("click", function (e) {_x000D_
    var submitAllow = true;_x000D_
    $('[name="atendeename[]"]', this).each(function(index, el){_x000D_
        // If there is a value_x000D_
        if ($(el).val()) {_x000D_
            // Find adjacent entree input_x000D_
            var entree = $(el).next('input');_x000D_
            // If entree is empty, don't submit form_x000D_
            if ( ! entree.val()) {_x000D_
                alert('Please select an entree');_x000D_
                submitAllow = false;_x000D_
                return false;_x000D_
    if (submitAllow) {_x000D_
<script src=""></script>_x000D_
<form id="form-attendee">_x000D_
    Name: <input name="atendeename[]">_x000D_
    Entree: <input name="entree[]"><br>_x000D_
    Name: <input name="atendeename[]">_x000D_
    Entree: <input name="entree[]"><br>_x000D_
    Name: <input name="atendeename[]">_x000D_
    Entree: <input name="entree[]"><br>_x000D_
    Name: <input name="atendeename[]">_x000D_
    Entree: <input name="entree[]"><br>_x000D_
    Name: <input name="atendeename[]">_x000D_
    Entree: <input name="entree[]"><br>_x000D_
    <button type="button" id="btn-submit">Submit<button>_x000D_

HTML select form with option to enter custom value

Using one of the above solutions ( @mickmackusa ), I made a working prototype in React 16.8+ using Hooks.

I hope it helps someone.

Prevent double submission of forms in jQuery

Nathan's code but for jQuery Validate plugin

If you happen to use jQuery Validate plugin, they already have submit handler implemented, and in that case there is no reason to implement more than one. The code:

  submitHandler: function(form){
    // Prevent double submit
      // Previously submitted - don't submit again
      return false;
    } else {
      // Mark form as 'submitted' so that the next submit can be ignored
      $(form).data('submitted', true);
      return true;

You can easily expand it within the } else {-block to disable inputs and/or submit button.


How do I post button value to PHP?

Change the type to submit and give it a name (and remove the useless onclick and flat out the 90's style uppercased tags/attributes).

<input type="submit" name="foo" value="A" />
<input type="submit" name="foo" value="B" />

The value will be available by $_POST['foo'] (if the parent <form> has a method="post").

Why use $_SERVER['PHP_SELF'] instead of ""

When you insert ANY variable into HTML, unless you want the browser to interpret the variable itself as HTML, it's best to use htmlspecialchars() on it. Among other things, it prevents hackers from inserting arbitrary HTML in your page.

The value of $_SERVER['PHP_SELF'] is taken directly from the URL entered in the browser. Therefore if you use it without htmlspecialchars(), you're allowing hackers to directly manipulate the output of your code.

For example, if I e-mail you a link to"><script>malicious_code_here()</script><span class=" and you have <form action="<?php echo $_SERVER['PHP_SELF'] ?>">, the output will be:

<form action=""><script>malicious_code_here()</script><span class="">

My script will run, and you will be none the wiser. If you were logged in, I may have stolen your cookies, or scraped confidential info from your page.

However, if you used <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>">, the output would be:

<form action=";&gt;&lt;script&gt;cookie_stealing_code()&lt;/script&gt;&lt;span class=&quot;">

When you submitted the form, you'd have a weird URL, but at least my evil script did not run.

On the other hand, if you used <form action="">, then the output would be the same no matter what I added to my link. This is the option I would recommend.

Keep values selected after form submission

To avoid many if-else structures, let JavaScript do the trick automatically:

<select name="name" id="name">
   <option value="a">a</option>
   <option value="b">b</option>

<script type="text/javascript">
  document.getElementById('name').value = "<?php echo $_GET['name'];?>";

<select name="location" id="location">
  <option value="x">x</option>
  <option value="y">y</option>

<script type="text/javascript">
  document.getElementById('location').value = "<?php echo $_GET['location'];?>";

Pass a PHP variable value through an HTML form

Try that

First place

global $var;
$var = 'value';

Second place

global $var;
if (isset($_POST['save_exit']))
    echo $var; 

Or if you want to be more explicit you can use the globals array:

$GLOBALS['var'] = 'test';

// after that
echo $GLOBALS['var'];

And here is third options which has nothing to do with PHP global that is due to the lack of clarity and information in the question. So if you have form in HTML and you want to pass "variable"/value to another PHP script you have to do the following:

HTML form

<form action="script.php" method="post">
    <input type="text" value="<?php echo $var?>" name="var" />
    <input type="submit" value="Send" />

PHP script ("script.php")


$var = $_POST['var'];
echo $var;


AngularJS does not send hidden field value

I use a classical javascript to set value to hidden input

$scope.SetPersonValue = function (PersonValue)
    document.getElementById('TypeOfPerson').value = PersonValue;
    if (PersonValue != 'person')
        document.getElementById('Discount').checked = false;
        $scope.isCollapsed = true;
        $scope.isCollapsed = false;

How to edit HTML input value colour?

Maybe something like this (just add your style):

<input type="text" 
       value="Job Title e.g. Assistant Manager" 
              border: solid 1px #6E6E6E;
              height: 30px; 
        onfocus="if(this.value == 'Job Title e.g. Assistant Manager') {
                    this.value = '';
                 }" />

<input type="text" 
       name="searchterm" size="35" 
              border: solid 1px #6E6E6E;
              height: 30px; 
              vertical-align:9px" />

UPDATE: Since placeholder attribute is very well supported on all major browsers, there is no need to do anything manually. Its possible to achieve the same thing with this:

<input type="text" 
       placeholder="Job Title e.g. Assistant Manager" />

Angularjs - simple form submit

WARNING This is for Angular 1.x

If you are looking for Angular (v2+, currently version 8), try this answer or the official guide.


I have rewritten your JS fiddle here:

<div ng-app="myApp">

    <form name="saveTemplateData" action="#" ng-controller="FormCtrl" ng-submit="submitForm()">

        First name:    <br/><input type="text" name="form.firstname">    

        Email Address: <br/><input type="text" ng-model="form.emailaddress"> 

        <textarea rows="3" cols="25">
          Describe your reason for submitting this form ... 

        <input type="radio" ng-model="form.gender" value="female" />Female
        <input type="radio" ng-model="form.gender" value="male" />Male 

        <input type="checkbox" ng-model="form.member" value="true"/> Already a member
        <input type="checkbox" ng-model="form.member" value="false"/> Not a member

        <input type="file" ng-model="form.file_profile" id="file_profile">

        <input type="file" ng-model="form.file_avatar" id="file_avatar">

        <input type="submit">

Here I'm using lots of angular directives(ng-controller, ng-model, ng-submit) where you were using basic html form submission. Normally all alternatives to "The angular way" work, but form submission is intercepted and cancelled by Angular to allow you to manipulate the data before submission

BUT the JSFiddle won't work properly as it doesn't allow any type of ajax/http post/get so you will have to run it locally.

For general advice on angular form submission see the cookbook examples

UPDATE The cookbook is gone. Instead have a look at the 1.x guide for for form submission

The cookbook for angular has lots of sample code which will help as the docs aren't very user friendly.

Angularjs changes your entire web development process, don't try doing things the way you are used to with JQuery or regular html/js, but for everything you do take a look around for some sample code, as there is almost always an angular alternative.

Disabled form inputs do not appear in the request

I find this works easier. readonly the input field, then style it so the end user knows it's read only. inputs placed here (from AJAX for example) can still submit, without extra code.

<input readonly style="color: Grey; opacity: 1; ">

form serialize javascript (no framework)

For modern browsers only

If you target browsers that support the URLSearchParams API (most recent browsers) and FormData(formElement) constructor (most recent browsers), use this:

new URLSearchParams(new FormData(formElement)).toString()

Everywhere except IE

For browsers that support URLSearchParams but not the FormData(formElement) constructor, use this FormData polyfill and this code (works everywhere except IE):

new URLSearchParams(Array.from(new FormData(formElement))).toString()


var form = document.querySelector('form');
var out = document.querySelector('output');

function updateResult() {
  try {
    out.textContent = new URLSearchParams(Array.from(new FormData(form)));
    out.className = '';
  } catch (e) {
    out.textContent = e;
    out.className = 'error';

form.addEventListener('input', updateResult);
body { font-family: Arial, sans-serif; display: flex; flex-wrap: wrap; }
input[type="text"] { margin-left: 6px; max-width: 30px; }
label + label { margin-left: 10px; }
output { font-family: monospace; }
.error { color: #c00; }
div { margin-right: 30px; }
<!-- FormData polyfill for older browsers -->
<script src="[email protected]/formdata.min.js"></script>
  <form id="form">
    <label>x:<input type="text" name="x" value="1"></label>
    <label>y:<input type="text" name="y" value="2"></label>
    <select name="z">
      <option value="a" selected>a</option>
      <option value="b" selected>b</option>
  <h3>Query string</h3>
  <output for="form"></output>

Compatible with IE 10

For even older browsers (e.g. IE 10), use the FormData polyfill, an Array.from polyfill if necessary and this code:

  new FormData(formElement),
  e =>'=')

PHP: Possible to automatically get all POSTed data?

Sure. Just walk through the $_POST array:

foreach ($_POST as $key => $value) {
    echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";

How to pass value from <option><select> to form action

instead of trying to catch both POST and GET responses - you can have everything you want in the POST.

Your code:

<form method="POST" action="index.php?action=contact_agent&agent_id=">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>

can easily become:

<form method="POST" action="index.php">
  <input type="hidden" name="action" value="contact_agent">
  <select name="agent_id">
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  <button type="submit">Submit POST Data</button>

then in index.php - these values will be populated

$_POST['action'] // "contact_agent"
$_POST['agent_id'] // 1, 2 or 3 based on selection in form... 

How to submit a form with JavaScript by clicking a link?

this works well without any special function needed. Much easier to write with php as well. <input onclick="this.form.submit()"/>

How do I make a PHP form that submits to self?

Try this

<form method="post" id="reg" name="reg" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>"

Works well :)

Making Enter key on an HTML form submit instead of activating button

$("form#submit input").on('keypress',function(event) {
  if (event.which === 13) {

How can I get form data with JavaScript/jQuery?

showing form input element fields and input file to submit your form without page refresh and grab all values with file include in it here it is

<form id="imageUploadForm"   action="" method="post" enctype="multipart/form-data">_x000D_
<input type="text" class="form-control" id="fname" name='fname' placeholder="First Name" >_x000D_
<input type="text" class="form-control" name='lname' id="lname" placeholder="Last Name">_x000D_
<input type="number" name='phoneno'  class="form-control" id="phoneno" placeholder="Phone Number">_x000D_
<textarea class="form-control" name='address' id="address" rows="5" cols="5" placeholder="Your Address"></textarea>_x000D_
<input type="file" name="file" id="file" >_x000D_
<input type="submit" id="sub" value="Registration">        _x000D_
_x000D_ on Submit button page will send ajax request to your php file.
$('#imageUploadForm').on('submit',(function(e) _x000D_
     fname = $('#fname').val();_x000D_
     lname =  $('#lname').val();_x000D_
     address =  $('#address').val();_x000D_
     phoneno =  $('#phoneno').val();_x000D_
     file =  $('#file').val();_x000D_
     var formData = new FormData(this);_x000D_
     formData.append('file', $('#file')[0]);_x000D_
                url: "test.php",_x000D_
                //url: '<?php echo base_url().'edit_profile/edit_profile2';?>',_x000D_
                contentType: false,_x000D_
                processData: false,_x000D_
                     alert('Data with file are submitted !');_x000D_

PHP form - on submit stay on same page

Friend. Use this way, There will be no "Undefined variable message" and it will work fine.

        $price = $_POST["price"];
        $qty = $_POST["qty"];
        $message = $price*$qty;


    <!DOCTYPE html>
        <form action="#" method="post">
            <input type="number" name="price"> <br>
            <input type="number" name="qty"><br>
            <input type="submit" name="SubmitButton">
        <?php echo "The Answer is" .$message; ?>


HTML5: Slider with two inputs possible?

Sure you can simply use two sliders overlaying each other and add a bit of javascript (actually not more than 5 lines) that the selectors are not exceeding the min/max values (like in @Garys) solution.

Attached you'll find a short snippet adapted from a current project including some CSS3 styling to show what you can do (webkit only). I also added some labels to display the selected values.

It uses JQuery but a vanillajs version is no magic though.

@Update: The code below was just a proof of concept. Due to many requests I've added a possible solution for Mozilla Firefox (without changing the original code). You may want to refractor the code below before using it.

    (function() {

        function addSeparator(nStr) {
            nStr += '';
            var x = nStr.split('.');
            var x1 = x[0];
            var x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + '.' + '$2');
            return x1 + x2;

        function rangeInputChangeEventHandler(e){
            var rangeGroup = $(this).attr('name'),
                minBtn = $(this).parent().children('.min'),
                maxBtn = $(this).parent().children('.max'),
                range_min = $(this).parent().children('.range_min'),
                range_max = $(this).parent().children('.range_max'),
                minVal = parseInt($(minBtn).val()),
                maxVal = parseInt($(maxBtn).val()),
                origin = $(this).context.className;

            if(origin === 'min' && minVal > maxVal-5){
            var minVal = parseInt($(minBtn).val());
            $(range_min).html(addSeparator(minVal*1000) + ' €');

            if(origin === 'max' && maxVal-5 < minVal){
                $(maxBtn).val(5+ minVal);
            var maxVal = parseInt($(maxBtn).val());
            $(range_max).html(addSeparator(maxVal*1000) + ' €');

     $('input[type="range"]').on( 'input', rangeInputChangeEventHandler);
font-family: sans-serif;
input[type='range'] {
  width: 210px;
  height: 30px;
  overflow: hidden;
  cursor: pointer;
    outline: none;
input[type='range']::-webkit-slider-thumb {
  -webkit-appearance: none;
    background: none;
input[type='range']::-webkit-slider-runnable-track {
  width: 200px;
  height: 1px;
  background: #003D7C;

  background: none;

input[type='range']::-webkit-slider-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;

  z-index: 2;

    position: relative;
    height: 60px;
    width: 210px;
    display: inline-block;
    margin-top: -5px;
    margin-left: 20px;
.rangeslider input{
    position: absolute;
    position: absolute;

.rangeslider span{
    position: absolute;
    margin-top: 30px;
    left: 0;

.rangeslider .right{
   position: relative;
   float: right;
   margin-right: -5px;

/* Proof of concept for Firefox */
@-moz-document url-prefix() {
    background: #003D7C;
    position: relative;

    top:35px !important;
    overflow:visible !important;

    top:35px !important;
    overflow:visible !important;
input[type='range']::-moz-range-thumb {
  position: relative;
  height: 15px;
  width: 15px;
  margin-top: -7px;
  background: #fff;
  border: 1px solid #003D7C;
  border-radius: 25px;
  z-index: 1;

  input[type='range']:nth-child(1)::-moz-range-thumb {
      transform: translateY(-20px);    
  input[type='range']:nth-child(2)::-moz-range-thumb {
      transform: translateY(-20px);    
<script src=""></script>
<div class="rangeslider">
                                <input class="min" name="range_1" type="range" min="1" max="100" value="10" />
                                <input class="max" name="range_1" type="range" min="1" max="100" value="90" />
                                <span class="range_min light left">10.000 €</span>
                                <span class="range_max light right">90.000 €</span>

passing form data to another HTML page

*first html page*

<form action="display.jsp" >
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />

*Second html page*
<p>The serial number is:<%=request.getParameter("serialNumber") %></p>

you will get the value of the textbox on another page.

Form inside a table

If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table, display:table-row, and display:table-cell.

There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.

Try this instead:

<div class="table">
    <form class="tr" method="post" action="blah.html">
        <span class="td"><input type="text"/></span>
        <span class="td"><input type="text"/></span>
    <div class="tr">
        <span class="td">(cell data)</span>
        <span class="td">(cell data)</span>

The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.

The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.

Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.

Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group, table-row-group and table-footer-group respectively.

NOTE: The only thing you cannot do with this method is colspan.

Check out this illustration:

storing user input in array

You have at least these 3 issues:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
  3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

You can save all three values at once by doing:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;

And then change the show function to:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup

Here's a jsfiddle for you to play around.

How do I cancel form submission in submit button onclick event?

you should change the type from submit to button:

<input type='button' value='submit request'>

instead of

<input type='submit' value='submit request'>

you then get the name of your button in javascript and associate whatever action you want to it

var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};

worked for me hope it helps.

How do I send an HTML Form in an Email .. not just MAILTO

I actually use ASP C# to send my emails now, with something that looks like :

protected void Page_Load(object sender, EventArgs e)
    if (Request.Form.Count > 0)
        string formEmail = "";
        string fromEmail = "[email protected]";
        string defaultEmail = "[email protected]";

        string sendTo1 = "";

        int x = 0;

        for (int i = 0; i < Request.Form.Keys.Count; i++)
            formEmail += "<strong>" + Request.Form.Keys[i] + "</strong>";
            formEmail += ": " + Request.Form[i] + "<br/>";
            if (Request.Form.Keys[i] == "Email")
                if (Request.Form[i].ToString() != string.Empty)
                    fromEmail = Request.Form[i].ToString();
                formEmail += "<br/>";

        System.Net.Mail.MailMessage myMsg = new System.Net.Mail.MailMessage();
        SmtpClient smtpClient = new SmtpClient();

            myMsg.To.Add(new System.Net.Mail.MailAddress(defaultEmail));
            myMsg.IsBodyHtml = true;
            myMsg.Body = formEmail;
            myMsg.From = new System.Net.Mail.MailAddress(fromEmail);
            myMsg.Subject = "Sent using Gmail Smtp";
            smtpClient.Host = "";
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("[email protected]", "pward");

            smtpClient.Send(defaultEmail, sendTo1, "Sent using gmail smpt", formEmail);

        catch (Exception ee)
            debug.Text += ee.Message;

This is an example using gmail as the smtp mail sender. Some of what is in here isn't needed, but it is how I use it, as I am sure there are more effective ways in the same fashion.

PHP $_POST not working?

Have you check your php.ini ?
I broken my post method once that I set post_max_size the same with upload_max_filesize.

I think that post_max_size must less than upload_max_filesize.
Tested with PHP 5.3.3 in RHEL 6.0

$_POST in php 5.3.5 does not work
PHP POST not working

Checking Value of Radio Button Group via JavaScript?

Use document.querySelector() if you want to avoid frameworks (which I almost always want to do).


Jquery submit form

Try this lets say your form id is formID

$(".nextbutton").click(function() { $("form#formID").submit(); });

Clear form fields with jQuery

By using a combination of JQuery's .trigger() and native Javascripts's .reset() all form elements can be reset to blank state.


Replace <form_id> with id of form to reset.

Prevent redirect after form is submitted

Using Ajax

Using the jQuery Ajax request method you can post the email data to a script (submit.php). Using the success callback option to animate elements after the script is executed.

note - I would suggest utilizing the ajax Response Object to make sure the script executed successfully.

$(function() {
    $('.submit').click(function() {
            type: 'POST',
            url: 'submit.php',
            data: 'password=p4ssw0rt',
            error: function()
               alert("Request Failed");
            success: function(response)
            } // this was missing
        return false;

Manually Set Value for FormBuilder Control

Tip: If you're using setValue but not providing every property on the form you'll get an error:

Must supply a value for form control with name: 'stateOrProvince'.

So you may be tempted to use patchValue, but this can be dangerous if you're trying to update a whole form. I have an address that may not have stateOrProvince or stateCd depending upon whether it is US or worldwide.

Instead you can update like this - which will use the nulls as defaults:

this.form.setValue( { stateOrProvince: null, stateCd: null, ...address } );

Why is textarea filled with mysterious white spaces?

I'm against HTML code mixed with PHP code.

However try this:

<textarea style="width:350px; height:80px;" cols="42" rows="5" name="sitelink">
        echo trim($siteLink_val);

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

Not with plain HTML I'm afraid.

You could use some jQuery to do this though:

    var $select = $(".1-100");
    for (i=1;i<=100;i++){

-- SEE DEMO --

You can download jQuery here

PHP send mail to multiple email addresses

I think the following code will works.

$tos = array('[email protected]', '[email protected]');
foreach ($tos as $to){
    $ok = mail ($to, $subject, $body, $from);
if ($ok) {
    echo "Message Send";
} else { 
    echo "Error";

How to fix 'Notice: Undefined index:' in PHP form action

Use empty() to check if it is available. Try with -

will generate the error if host is not present here


jQuery Change event on an <input> element - any way to retain previous value?

$('#element').on('change', function() {

Show red border for all invalid fields after submitting form angularjs

I have created a working CodePen example to demonstrate how you might accomplish your goals.

I added ng-click to the <form> and removed the logic from your button:

<form name="addRelation" data-ng-click="save(model)">
<input class="btn" type="submit" value="SAVE" />

Here's the updated template:

<section ng-app="app" ng-controller="MainCtrl">
  <form class="well" name="addRelation" data-ng-click="save(model)">
    <label>First Name</label>
    <input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
    <label>Last Name</label>
    <input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
    <input type="email" placeholder="Email" data-ng-model="" id="Email" name="Email" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$">Email address is not valid</span><br/>
    <input class="btn" type="submit" value="SAVE" />  

and controller code:

app.controller('MainCtrl', function($scope) {  
  $ = function(model) {
    $scope.addRelation.submitted = true;

    if($scope.addRelation.$valid) {
      // submit to db
    } else {
      console.log('Errors in form data');

I hope this helps.

How to handle checkboxes in ASP.NET MVC forms?

In case you're wondering WHY they put a hidden field in with the same name as the checkbox the reason is as follows :

Comment from the sourcecode MVCBetaSource\MVC\src\MvcFutures\Mvc\ButtonsAndLinkExtensions.cs

Render an additional <input type="hidden".../> for checkboxes. This addresses scenarios where unchecked checkboxes are not sent in the request. Sending a hidden input makes it possible to know that the checkbox was present on the page when the request was submitted.

I guess behind the scenes they need to know this for binding to parameters on the controller action methods. You could then have a tri-state boolean I suppose (bound to a nullable bool parameter). I've not tried it but I'm hoping thats what they did.

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
    $.post('', function() {
      window.location = '';
    return false;

Use CSS to automatically add 'required field' asterisk to form inputs

Here is a simple "CSS only" trick I created and am using to dynamically add a red asterisk on the labels of required form elements without losing browsers' default form validation.

The following code works perfectly on all the browsers and for all the main form elements.

.form-group {
  display: flex;
  flex-direction: column;

label {
  order: 1;
  text-transform: capitalize;
  margin-bottom: 0.3em;

textarea {
  padding: 0.5em;
  order: 2;

textarea:required+label::after {
  content: " *";
  color: #e32;
<div class="form-group">
  <input class="form-control" name="first_name" id="first_name" type="text" placeholder="First Name" required>
  <label class="small mb-1" for="first_name">First Name</label>


<div class="form-group">
  <input class="form-control" name="last_name" id="last_name" type="text" placeholder="Last Name">
  <label class="small mb-1" for="last_name">Last Name</label>

Important: You must preserve the order of elements that is the input element first and label element second. CSS is gonna handle it and transform it in the traditional way, that is the label first and input second.

Requery a subform from another form?

All your controls are belong to us!

Fionnuala answered this correctly but skimmers like me would find it easy to miss the point.

You don't refresh the subFORM you refresh the subform CONTROL. In fact, if you check with allforms() the subForm isn't even loaded as far as access is concerned.

On the main form look at the label the subform wizard provided or select the subform by clicking once or on the border around it and look at the "caption" in the "Other" tab in properties. That's the name you use for requerying, not the name of the form that appears in the navigation panel.

In my case I had a subform called frmInvProdSub and I tried for many hours to figure out why Access didn't think it existed. I gave up, deleted the form and re-created it. The very last step is telling it what you want to call the control so I called it frmInvProdSub and finished the wizard. Then I tried and voila, it worked!

When I looked at the form name in the navigation window I realized I'd forgotten to put "Sub" in the name! That's when it clicked. The CONTROL is called frmInvProdSub, not the form and using the control name works.

Of course if both names are identical then you didn't have this problem lol.

How to disable/enable select field using jQuery?

Just simply use:

var update_pizza = function () {
     $("#pizza_kind").prop("disabled", !$('#pizza').prop('checked'));



jQuery - select the associated label element of a input field

You shouldn't rely on the order of elements by using prev or next. Just use the for attribute of the label, as it should correspond to the ID of the element you're currently manipulating:

var label = $("label[for='" + $(this).attr('id') + "']");

However, there are some cases where the label will not have for set, in which case the label will be the parent of its associated control. To find it in both cases, you can use a variation of the following:

var label = $('label[for="' + $(this).attr('id') + '"]');

if(label.length <= 0) {
    var parentElem = $(this).parent(),
        parentTagName = parentElem.get(0).tagName.toLowerCase();

    if(parentTagName == "label") {
        label = parentElem;

I hope this helps!

javascript if number greater than number

You can "cast" to number using the Number constructor..

var number = new Number("8"); // 8 number

You can also call parseInt builtin function:

var number = parseInt("153"); // 153 number

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

I use this javascript line to block the pop up asking for form resubmission on refresh once the form is submitted.

if ( window.history.replaceState ) {
  window.history.replaceState( null, null, window.location.href );

Just place this line at the footer of your file and see the magic

Use a normal link to submit a form


<input type="image" src=".."/>


<button type="send"><img src=".."/> + any html code</button>

plus some CSS

How to add text inside the doughnut chart using Chart.js?

Base on @rap-2-h answer,Here the code for using text on doughnut chart on Chart.js for using in dashboard like. It has dynamic font-size for responsive option.


<canvas id="chart-area" width="300" height="300" style="border:1px solid"/><div>


var doughnutData = [
                value: 100,
                highlight: "#FF5A5E",
                label: "Red"
                value: 50,
                color: "#CCCCCC",
                highlight: "#5AD3D1",
                label: "Green"

  var ctx = $('#chart-area').get(0).getContext("2d");

  var myDoughnut = new Chart(ctx).Doughnut(doughnutData,{
     responsive: true,
     showTooltips: false,
     percentageInnerCutout : 70,
     segmentShowStroke : false,
     onAnimationComplete: function() {

     var canvasWidthvar = $('#chart-area').width();
     var canvasHeight = $('#chart-area').height();
     //this constant base on canvasHeight / 2.8em
     var constant = 114;
     var fontsize = (canvasHeight/constant).toFixed(2);
     ctx.font=fontsize +"em Verdana";
     var total = 0;
     $.each(doughnutData,function() {
       total += parseInt(this.value,10);
  var tpercentage = ((doughnutData[0].value/total)*100).toFixed(2)+"%";
  var textWidth = ctx.measureText(tpercentage).width;

   var txtPosx = Math.round((canvasWidthvar - textWidth)/2);
    ctx.fillText(tpercentage, txtPosx, canvasHeight/2);

Here the sample code.try to resize the window.

What is the reason for a red exclamation mark next to my project in Eclipse?

Isn´t it a strange behavior? In my case, the mistake was that I added a jar-lib. But this lib was faulty, so I removed the lib. But, no matter what I´ve done, the error still exists. I removed the jar-file, even with the eclipse option "remove from build-path", deleted it on my project-folders and cleaned my project, but nothing worked. Only after I´ve done the way Qwert has described, it worked. But sould an IDE not independent from error messages? The error was fixed, only the messages caused the problem. Thanks to Qwert (if I got enough reputations, I will vote your answer. But now I am not able to, sorry).

How to print_r $_POST array?

Because you have nested arrays, then I actually recommend a recursive approach:

function recurse_into_array( $in, $tabs = "" )
    foreach( $in as $key => $item )
        echo $tabs . $key . ' => ';
        if( is_array( $item ) )
            recurse_into_array( $item, $tabs . "\t" );
            echo $tabs . "\t" . $key;

recurse_into_array( $_POST );

How do I create a file and write to it?

    public static void writefromFile(ArrayList<String> lines, String destPath) {
        FileWriter fw;
        try {
            fw = new FileWriter(destPath);
            for (String str : lines) {
         } catch (IOException ex) {
            JOptionPane.showMessageDialog("ERROR: exception was: " + ex.toString());
        File f = new File(destPath);

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

I used this and it worked out well for me. If your directory is

"repo" and your project is "hello" copy the project there

cd /path/to/my/repo

Initialize your directory

git init

Stage the project

git add hello

commit the project

git commit

Add configurations using the email and username you are using in Bitbucket

git config --global
git config --global

Add comment to the project

git commit -m 'comment'

push the project now

git push origin master

Check out of the master

git checkout master

How to specify the JDK version in android studio?

You can use cmd + ; for Mac or Ctrl + Alt + Shift + S for Windows/Linux to pull up the Project Structure dialog. In there, you can set the JDK location as well as the Android SDK location.

Project Structure Dialog

To get your JDK location, run /usr/libexec/java_home -v 1.7 in terminal. Send 1.7 for Java 7 or 1.8 for Java 8.

Escape string Python for MySQL

install sqlescapy package:

pip install sqlescapy

then you can escape variables in you raw query

from sqlescapy import sqlescape

query = """
    SELECT * FROM "bar_table" WHERE id='%s'
""" % sqlescape(user_input)

What is the difference/usage of homebrew, macports or other package installation tools?

MacPorts is the way to go.

  1. Like @user475443 pointed, MacPorts has many many more packages. With brew you'll find yourself trapped soon because the formula you need doesn't exist.

  2. MacPorts is a native application: C + TCL. You don't need Ruby at all. To install Ruby on Mac OS X you might need MacPorts, so just go with MacPorts and you'll be happy.

  3. MacPorts is really stable, in 8 years I never had a problem with it, and my entire Unix ecosystem relay on it.

  4. If you are a PHP developer you can install the last version of Apache (Mac OS X uses 2.2), PHP and all the extensions you need, then upgrade all with one command. Forget to do the same with Homebrew.

  5. MacPorts support groups.

    foo@macpro:~/ port select --summary
    Name        Selected      Options
    ====        ========      =======
    db          none          db46 none
    gcc         none          gcc42 llvm-gcc42 mp-gcc48 none
    llvm        none          mp-llvm-3.3 none
    mysql       mysql56       mysql56 none
    php         php55         php55 php56 none
    postgresql  postgresql94  postgresql93 postgresql94 none
    python      none          python24 python25-apple python26-apple python27 python27-apple none

    If you have both PHP55 and PHP56 installed (with many different extensions), you can swap between them with just one command. All the relative extensions are part of the group and they will be activated within the chosen group: php55 or php56. I'm not sure Homebrew has this feature.

  6. Rubists like to rewrite everything in Ruby, because the only thing they are at ease is Ruby itself.

Visual Studio breakpoints not being hit

If any of your components are Strong Named (signed), then all need to be. If you, as I did, add a project and reference it from a Strong Named project/component, neglecting to sign your new component, debugging will be as if your new component is an external one and you will not be able to step into it. So make sure all your components are signed, or none.

enter image description here

How to change ProgressBar's progress indicator color in Android

You guys are really giving me a headache. What you can do is make your layer-list drawable via xml first (meaning a background as the first layer, a drawable that represents secondary progress as the second layer, and another drawable that represents the primary progress as the last layer), then change the color on the code by doing the following:

public void setPrimaryProgressColor(int colorInstance) {
      if (progressBar.getProgressDrawable() instanceof LayerDrawable) {
        Log.d(mLogTag, "Drawable is a layer drawable");
        LayerDrawable layered = (LayerDrawable) progressBar.getProgressDrawable();
        Drawable circleDrawableExample = layered.getDrawable(<whichever is your index of>);
        circleDrawableExample.setColorFilter(colorInstance, PorterDuff.Mode.SRC_IN);
    } else {
        Log.d(mLogTag, "Fallback in case it's not a LayerDrawable");
        progressBar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_IN);

This method will give you the best flexibility of having the measurement of your original drawable declared on the xml, WITH NO MODIFICATION ON ITS STRUCTURE AFTERWARDS, especially if you need to have the xml file screen folder specific, then just modifying ONLY THE COLOR via the code. No re-instantiating a new ShapeDrawable from scratch whatsoever.

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

Calculate correlation for more than two variables?

You can also calculate correlations for all variables but exclude selected ones, for example:

mtcars <- data.frame(mtcars)
# here we exclude gear and carb variables
cors <- cor(subset(mtcars, select = c(-gear,-carb)))

Also, to calculate correlation between each variable and one column you can use sapply()

# sapply effectively calls the corelation function for each column of mtcars and mtcars$mpg
cors2 <- sapply(mtcars, cor, y=mtcars$mpg)

How to increment variable under DOS?

I realize you've found another answer - but the fact is that your original code was nearly correct but for a syntax error.

Your code contained the line


and the syntax that would work is simply...


See for all the details on the SET command. I just thought I'd add this clarification for anyone else who doesn't have the option of using FreeDOS.

How to access host port from docker container

You can access the local webserver which is running in your host machine in two ways.

  1. Approach 1 with public IP

    Use host machine public IP address to access webserver in Jenkins docker container.

  2. Approach 2 with the host network

    Use "--net host" to add the Jenkins docker container on the host's network stack. Containers which are deployed on host's stack have entire access to the host interface. You can access local webserver in docker container with a private IP address of the host machine.

NETWORK ID          NAME                      DRIVER              SCOPE
b3554ea51ca3        bridge                    bridge              local
2f0d6d6fdd88        host                      host                local
b9c2a4bc23b2        none                      null                local

Start a container with the host network Eg: docker run --net host -it ubuntu and run ifconfig to list all available network IP addresses which are reachable from docker container.

Eg: I started a nginx server in my local host machine and I am able to access the nginx website URLs from Ubuntu docker container.

docker run --net host -it ubuntu

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
a604f7af5e36        ubuntu              "/bin/bash"         22 seconds ago      Up 20 seconds                           ubuntu_server

Accessing the Nginx web server (running in local host machine) from Ubuntu docker container with private network IP address.

root@linuxkit-025000000001:/# curl 192.168.x.x -I
HTTP/1.1 200 OK
Server: nginx/1.15.10
Date: Tue, 09 Apr 2019 05:12:12 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 26 Mar 2019 14:04:38 GMT
Connection: keep-alive
ETag: "5c9a3176-264"
Accept-Ranges: bytes

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Normally when an optimization algorithm does not converge, it is usually because the problem is not well-conditioned, perhaps due to a poor scaling of the decision variables. There are a few things you can try.

  1. Normalize your training data so that the problem hopefully becomes more well conditioned, which in turn can speed up convergence. One possibility is to scale your data to 0 mean, unit standard deviation using Scikit-Learn's StandardScaler for an example. Note that you have to apply the StandardScaler fitted on the training data to the test data.
  2. Related to 1), make sure the other arguments such as regularization weight, C, is set appropriately.
  3. Set max_iter to a larger value. The default is 1000.
  4. Set dual = True if number of features > number of examples and vice versa. This solves the SVM optimization problem using the dual formulation. Thanks @Nino van Hooff for pointing this out, and @JamesKo for spotting my mistake.
  5. Use a different solver, for e.g., the L-BFGS solver if you are using Logistic Regression. See @5ervant's answer.

Note: One should not ignore this warning.

This warning came about because

  1. Solving the linear SVM is just solving a quadratic optimization problem. The solver is typically an iterative algorithm that keeps a running estimate of the solution (i.e., the weight and bias for the SVM). It stops running when the solution corresponds to an objective value that is optimal for this convex optimization problem, or when it hits the maximum number of iterations set.

  2. If the algorithm does not converge, then the current estimate of the SVM's parameters are not guaranteed to be any good, hence the predictions can also be complete garbage.


In addition, consider the comment by @Nino van Hooff and @5ervant to use the dual formulation of the SVM. This is especially important if the number of features you have, D, is more than the number of training examples N. This is what the dual formulation of the SVM is particular designed for and helps with the conditioning of the optimization problem. Credit to @5ervant for noticing and pointing this out.

Furthermore, @5ervant also pointed out the possibility of changing the solver, in particular the use of the L-BFGS solver. Credit to him (i.e., upvote his answer, not mine).

I would like to provide a quick rough explanation for those who are interested (I am :)) why this matters in this case. Second-order methods, and in particular approximate second-order method like the L-BFGS solver, will help with ill-conditioned problems because it is approximating the Hessian at each iteration and using it to scale the gradient direction. This allows it to get better convergence rate but possibly at a higher compute cost per iteration. That is, it takes fewer iterations to finish but each iteration will be slower than a typical first-order method like gradient-descent or its variants.

For e.g., a typical first-order method might update the solution at each iteration like

x(k + 1) = x(k) - alpha(k) * gradient(f(x(k)))

where alpha(k), the step size at iteration k, depends on the particular choice of algorithm or learning rate schedule.

A second order method, for e.g., Newton, will have an update equation

x(k + 1) = x(k) - alpha(k) * Hessian(x(k))^(-1) * gradient(f(x(k)))

That is, it uses the information of the local curvature encoded in the Hessian to scale the gradient accordingly. If the problem is ill-conditioned, the gradient will be pointing in less than ideal directions and the inverse Hessian scaling will help correct this.

In particular, L-BFGS mentioned in @5ervant's answer is a way to approximate the inverse of the Hessian as computing it can be an expensive operation.

However, second-order methods might converge much faster (i.e., requires fewer iterations) than first-order methods like the usual gradient-descent based solvers, which as you guys know by now sometimes fail to even converge. This can compensate for the time spent at each iteration.

In summary, if you have a well-conditioned problem, or if you can make it well-conditioned through other means such as using regularization and/or feature scaling and/or making sure you have more examples than features, you probably don't have to use a second-order method. But these days with many models optimizing non-convex problems (e.g., those in DL models), second order methods such as L-BFGS methods plays a different role there and there are evidence to suggest they can sometimes find better solutions compared to first-order methods. But that is another story.

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.


function test(){
    "use strict";
    let a = 1;

MySQL Multiple Joins in one query?

Just add another join:

SELECT dashboard_data.headline,
FROM dashboard_data 
    INNER JOIN dashboard_messages
            ON dashboard_message_id = 
    INNER JOIN images
            ON dashboard_messages.image_id = images.image_id

Simple CSS: Text won't center in a button

padding: 0px solves the horizontal centering


setting line-height equal to or less than the height of the button solves the vertical alignment.

How to remove a virtualenv created by "pipenv run"

I know that question is a bit old but

In root of project where Pipfile is located you could run

pipenv --venv

which returns


and then remove this env by typing

rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

How to redirect the output of print to a TXT file

Usinge the file argument in the print function, you can have different files per print:

print('Redirect output to file', file=open('/tmp/example.log', 'w'))

How to generate the JPA entity Metamodel?

It would be awesome if someone also knows the steps for setting this up in Eclipse (I assume it's as simple as setting up an annotation processor, but you never know)

Yes it is. Here are the implementations and instructions for the various JPA 2.0 implementations:





The latest Hibernate implementation is available at:

An older Hibernate implementation is at:

What should be the sizeof(int) on a 64-bit machine?

Not really. for backward compatibility it is 32 bits.
If you want 64 bits you have long, size_t or int64_t

Counting unique / distinct values by group in a data frame

This is a simple solution with the function aggregate:

aggregate(order_no ~ name, myvec, function(x) length(unique(x)))

Fit website background image to screen size

You can try with

.appBackground {
    position: relative;
    background-image: url(".../img/background.jpg");
    background-size:100% 100vh;

works for me :)

What is the use of ObservableCollection in .net?

From Pro C# 5.0 and the .NET 4.5 Framework

The ObservableCollection<T> class is very useful in that it has the ability to inform external objects when its contents have changed in some way (as you might guess, working with ReadOnlyObservableCollection<T> is very similar, but read-only in nature). In many ways, working with the ObservableCollection<T> is identical to working with List<T>, given that both of these classes implement the same core interfaces. What makes the ObservableCollection<T> class unique is that this class supports an event named CollectionChanged. This event will fire whenever a new item is inserted, a current item is removed (or relocated), or if the entire collection is modified. Like any event, CollectionChanged is defined in terms of a delegate, which in this case is NotifyCollectionChangedEventHandler. This delegate can call any method that takes an object as the first parameter, and a NotifyCollectionChangedEventArgs as the second. Consider the following Main() method, which populates an observable collection containing Person objects and wires up the CollectionChanged event:

class Program
   static void Main(string[] args)
     // Make a collection to observe and add a few Person objects.
     ObservableCollection<Person> people = new ObservableCollection<Person>()
        new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
        new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
     // Wire up the CollectionChanged event.
     people.CollectionChanged += people_CollectionChanged;
     // Now add a new item.
     people.Add(new Person("Fred", "Smith", 32));

     // Remove an item.

   static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
       // What was the action that caused the event?
        Console.WriteLine("Action for this event: {0}", e.Action);

        // They removed something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            Console.WriteLine("Here are the OLD items:");
            foreach (Person p in e.OldItems)

        // They added something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            // Now show the NEW items that were inserted.
            Console.WriteLine("Here are the NEW items:");
            foreach (Person p in e.NewItems)

The incoming NotifyCollectionChangedEventArgs parameter defines two important properties, OldItems and NewItems, which will give you a list of items that were currently in the collection before the event fired, and the new items that were involved in the change. However, you will want to examine these lists only under the correct circumstances. Recall that the CollectionChanged event can fire when items are added, removed, relocated, or reset. To discover which of these actions triggered the event, you can use the Action property of NotifyCollectionChangedEventArgs. The Action property can be tested against any of the following members of the NotifyCollectionChangedAction enumeration:

public enum NotifyCollectionChangedAction
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,

Members of System.Collections.ObjectModel

No newline at end of file

If you add a new line of text at the end of the existing file which does not already have a newline character at the end, the diff will show the old last line as having been modified, even though conceptually it wasn’t.

This is at least one good reason to add a newline character at the end.


A file contains:

A() {
    // do something


00000000: 4128 2920 7b0a 2020 2020 2f2f 2064 6f20  A() {.    // do 
00000010: 736f 6d65 7468 696e 670a 7d              something.}

You now edit it to

A() {
    // do something
// Useful comment


00000000: 4128 2920 7b0a 2020 2020 2f2f 2064 6f20  A() {.    // do 
00000010: 736f 6d65 7468 696e 670a 7d0a 2f2f 2055  something.}.// U
00000020: 7365 6675 6c20 636f 6d6d 656e 742e 0a    seful comment..

The git diff will show:

\ No newline at end of file
+// Useful comment.

In other words, it shows a larger diff than conceptually occurred. It shows that you deleted the line } and added the line }\n. This is, in fact, what happened, but it’s not what conceptually happened, so it can be confusing.

How to debug ORA-01775: looping chain of synonyms?

ORA-01775: looping chain of synonyms I faced the above error while I was trying to compile a Package which was using an object for which synonym was created however underlying object was not available.

How to convert int to Integer

I had a similar problem . For this you can use a Hashmap which takes "string" and "object" as shown in code below:

/** stores the image database icons */
public static int[] imageIconDatabase = { R.drawable.ball,
        R.drawable.catmouse, R.drawable.cube, R.drawable.fresh,
        R.drawable.guitar,, R.drawable.teapot,
        R.drawable.india, R.drawable.thailand, R.drawable.netherlands,
        R.drawable.srilanka, R.drawable.pakistan,

private void initializeImageList() {
    // TODO Auto-generated method stub
    for (int i = 0; i < imageIconDatabase.length; i++) {
        map = new HashMap<String, Object>();

        map.put("Name", imageNameDatabase[i]);
        map.put("Icon", imageIconDatabase[i]);


How to access the elements of a 2D array?

If you want do many calculation with 2d array, you should use NumPy array instead of nest list.

for your question, you can use:zip(*a) to transpose it:

In [55]: a=[[1,1],[2,1],[3,1]]
In [56]: zip(*a)
Out[56]: [(1, 2, 3), (1, 1, 1)]
In [57]: zip(*a)[0]
Out[57]: (1, 2, 3)

How to set web.config file to show full error message

If you're using ASP.NET MVC you might also need to remove the HandleErrorAttribute from the Global.asax.cs file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    filters.Add(new HandleErrorAttribute());

How to pass prepareForSegue: an object

For Swift use this,

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var segueID = segue.identifier

    if(segueID! == "yourSegueName"){

        var yourVC:YourViewController = segue.destinationViewController as YourViewController

        yourVC.objectOnYourVC = setObjectValueHere!


How to replace specific values in a oracle database column?

In Oracle, there is the concept of schema name, so try using this

update schemname.tablename t
set t.columnname = replace(t.columnname, t.oldvalue, t.newvalue);

Find all files with name containing string

Use find:

find . -maxdepth 1 -name "*string*" -print

It will find all files in the current directory (delete maxdepth 1 if you want it recursive) containing "string" and will print it on the screen.

If you want to avoid file containing ':', you can type:

find . -maxdepth 1 -name "*string*" ! -name "*:*" -print

If you want to use grep (but I think it's not necessary as far as you don't want to check file content) you can use:

ls | grep touch

But, I repeat, find is a better and cleaner solution for your task.

Export html table data to Excel using JavaScript / JQuery is not working properly in chrome browser

Instead of using you can use a link with the onclick event.
And you can put the html table into the uri and set the file name to be downloaded.

Live demo :

function exportF(elem) {_x000D_
  var table = document.getElementById("table");_x000D_
  var html = table.outerHTML;_x000D_
  var url = 'data:application/,' + escape(html); // Set your html table into url _x000D_
  elem.setAttribute("href", url);_x000D_
  elem.setAttribute("download", "export.xls"); // Choose the file name_x000D_
  return false;_x000D_
<table id="table" border="1">_x000D_
<a id="downloadLink" onclick="exportF(this)">Export to excel</a>

phpMyAdmin says no privilege to create database, despite logged in as root user

It appears to be a transient issue and fixed itself afterwards. Thanks for everyone's attention.

file_put_contents - failed to open stream: Permission denied

Gathering info from this link stackoverflow-image save doesn't work with chmod 777 and from user azerafati and Loek Bergman

if you were to look under /etc/apache/envvars file you will see something like:

export APACHE_RUN_USER=www-data
export APACHE_RUN_GROUP=www-data

Apache is run under the username 'www-data'

'0755' means the file owner can read/write/execute but group and other users cannot write. so in ur terminal, cd to the folder containing your 'images' folder. then type:

find images -type d -exec chmod 0755 {} \;
find images -type f -exec chmod 0755 {} \;
sudo chown -R www-data:www-data images

you must change persmissions first before changing owner. enter your password when prompted. this will make 'www-data' owner of the images folder.

your upload should now work.

how to get javaScript event source element?

Try something like this:


    <script type="text/javascript">
        function doSomething(event) {
          var source = || event.srcElement;
          if(window.event) {
            // IE8 and earlier
            // doSomething
           } else if(e.which) {
            // IE9/Firefox/Chrome/Opera/Safari
            // doSomething

    <button onclick="doSomething('param')" id="id_button">


How to change the order of DataFrame columns?

Here is a very simple answer to this(only one line).

You can do that after you added the 'n' column into your df as follows.

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))
df['mean'] = df.mean(1)
           0           1           2           3           4        mean
0   0.929616    0.316376    0.183919    0.204560    0.567725    0.440439
1   0.595545    0.964515    0.653177    0.748907    0.653570    0.723143
2   0.747715    0.961307    0.008388    0.106444    0.298704    0.424512
3   0.656411    0.809813    0.872176    0.964648    0.723685    0.805347
4   0.642475    0.717454    0.467599    0.325585    0.439645    0.518551
5   0.729689    0.994015    0.676874    0.790823    0.170914    0.672463
6   0.026849    0.800370    0.903723    0.024676    0.491747    0.449473
7   0.526255    0.596366    0.051958    0.895090    0.728266    0.559587
8   0.818350    0.500223    0.810189    0.095969    0.218950    0.488736
9   0.258719    0.468106    0.459373    0.709510    0.178053    0.414752

### here you can add below line and it should work 
# Don't forget the two (()) 'brackets' around columns names.Otherwise, it'll give you an error.

df = df[list(('mean',0, 1, 2,3,4))]

        mean           0           1           2           3           4
0   0.440439    0.929616    0.316376    0.183919    0.204560    0.567725
1   0.723143    0.595545    0.964515    0.653177    0.748907    0.653570
2   0.424512    0.747715    0.961307    0.008388    0.106444    0.298704
3   0.805347    0.656411    0.809813    0.872176    0.964648    0.723685
4   0.518551    0.642475    0.717454    0.467599    0.325585    0.439645
5   0.672463    0.729689    0.994015    0.676874    0.790823    0.170914
6   0.449473    0.026849    0.800370    0.903723    0.024676    0.491747
7   0.559587    0.526255    0.596366    0.051958    0.895090    0.728266
8   0.488736    0.818350    0.500223    0.810189    0.095969    0.218950
9   0.414752    0.258719    0.468106    0.459373    0.709510    0.178053

How to set margin with jquery?



Detect when an image fails to load in Javascript

You could try the following code. I can't vouch for browser compatibility though, so you'll have to test that.

function testImage(URL) {
    var tester=new Image();

function imageFound() {
    alert('That image is found and loaded');

function imageNotFound() {
    alert('That image was not found.');


And my sympathies for the jQuery-resistant boss!

Entity Framework : How do you refresh the model when the db changes?

Double click on the .edmx file then right_click anywhere on the screen and choose "Update Modle From DB". In the new window go to the "Refresh" tab and choose the changed table/view and click Finish.

Babel command not found

Worked for me e.g.

./node_modules/.bin/babel --version
./node_modules/.bin/babel src/main.js

C-like structures in Python

Here is a solution which uses a class (never instantiated) to hold data. I like that this way involves very little typing and does not require any additional packages etc.

class myStruct:
    field1 = "one"
    field2 = "2"

You can add more fields later, as needed:

myStruct.field3 = 3

To get the values, the fields are accessed as usual:

>>> myStruct.field1

What is the use of a private static variable in Java?

When in a static method you use a variable, the variable have to be static too as an example:

private static int a=0;  
public static void testMethod() {  

How can I pass parameters to a partial view in mvc 4

Here is an extension method that will convert an object to a ViewDataDictionary.

public static ViewDataDictionary ToViewDataDictionary(this object values)
    var dictionary = new ViewDataDictionary();
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(values))
        dictionary.Add(property.Name, property.GetValue(values));
    return dictionary;

You can then use it in your view like so:

@Html.Partial("_MyPartial", new
    Property1 = "Value1",
    Property2 = "Value2"

Which is much nicer than the new ViewDataDictionary { { "Property1", "Value1" } , { "Property2", "Value2" }} syntax.

Then in your partial view, you can use ViewBag to access the properties from a dynamic object rather than indexed properties, e.g.


Android Studio doesn't start, fails saying components not installed

A possible solution would be to check your proxy settings; under Windows 7 you can find those settings in the other.xml file present under the path C:\Users\YourUsername\\.AndroidStudio\config\options.

Note that if you turn both options "USE_HTTP_PROXY" and "USE_PROXY_PAC" to true the error keep coming but a pop-up should come out noticing the problem of a double configuration and prompting a resolution with a input window for those settings.

UPDATE - Possible solution

I've just managed to complete the wizard at home, maybe the proxy is not the real problem (as the last comment of @meanderingmoose pointed out). It seems there is a problem with the default installer of Android Studio 1.0.0, the one that contain both the IDE and di SDK Tools: the default installation path for the android sdk tools ends with myInstallPath../sdk/android-sdk but the first run setting for the Android Studio points at ..myInstallPath../sdk. So here is what i did.

  • Cut & Paste the content of the android-sdk folder outside the folder, so the files are under ..myInstallPath../sdk/
  • Use SDK Manager from the new location to update everything (Use this instead of the automatic wizard, you can select which package you want or need and you get also the speed and estimate time for the download)
  • Run Android Studio (it should load and check that the SDK is up to date and start the creation of an AVD, after that the IDE will load completely)

UPDATE - Workaround for the "download interrupted: read timed out" problem

The firewall and the proxy prevented my SDK Manager to download some updates, so i've recovered the .xml url for these updates, searched for the .zip files i needed and directly downloaded them with the help of a download manager, then i've manually installed them in their relative folder under the sdk folder ..a bit tricky but worked for me. For example in the Addon_xml_file i've searched for the m2repository, found the entry and downloaded the archive with the link m2repository_r14_zip_file. You always find the files you need in the same base as the .xml file (take a look at the url i've posted for the example).

Custom Listview Adapter with filter Android

If you want to achieve filtering with custom model class in kotlin then you can implement below code.

Step 1: Add SearchView in your xml file and then in your activity or fragment implement SearchView.OnQueryTextListener

class SearchActivity : AppCompatActivity(),SearchView.OnQueryTextListener {

    lateinit var sectionModelArrayList: ArrayList<CategorySectionModel>
    lateinit var filteredArrayList: ArrayList<CategorySectionModel>

    override fun onCreate(savedInstanceState: Bundle?) {

    //Called this method with you own data to populate the recycler view.
    private fun parseJson() {
        rv_category_list.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        adapter = CategoryLabelAdapter(sectionModelArrayList, this)
        rv_category_list.adapter = adapter

    override fun onQueryTextSubmit(query: String?): Boolean {
        return false

    override fun onQueryTextChange(newText: String?): Boolean {
        return false

My model class CategorySectionModel looks like

class CategorySectionModel(val categoryLabel: String, val categoryItemList: ArrayList<CategoryItem>)

Now we have to work on adapter class and there you need to implement Filterable interface and override getFilter() method like below

class CategoryLabelAdapter(internal var data: ArrayList<CategorySectionModel>?, internal var activity: Context) : RecyclerView.Adapter<CategoryLabelAdapter.ViewHolder>(), Filterable {
    val originalList = data
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.item_category_name, parent, false)
        return ViewHolder(v)

    override fun getItemCount(): Int {
        return data!!.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        data?.get(position)?.let { holder.bindItem(it) }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bindItem(data: CategorySectionModel) {
            itemView.tv_category_name.text = data.categoryLabel

    override fun getFilter(): Filter? {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence): FilterResults {
                val results = FilterResults()
                if (constraint.isEmpty()) {
                    //no filter implemented we return full list
                    results.values = data
                    results.count = data!!.size
                } else {
                    //Here we perform filtering operation
                    val list: ArrayList<CategorySectionModel> = ArrayList()
                    for (p in data!!) {
                        if (p.categoryLabel.toUpperCase().startsWith(constraint.toString().toUpperCase())) list.add(p)
                    results.values = list
                    results.count = list.size
                return results

            override fun publishResults(constraint: CharSequence, results: FilterResults) {
                // Now we have to inform the adapter about the new list filtered
                if (results.count == 0 || constraint == "") {
                    data = originalList
                } else {
                    data = results.values as ArrayList<CategorySectionModel>?

Throw keyword in function's signature

A no throw specification on an inlined function that only returns a member variable and could not possibly throw exceptions may be used by some compilers to do pessimizations (a made-up word for the opposite of optimizations) that can have a detrimental effect on performance. This is described in the Boost literature: Exception-specification

With some compilers a no-throw specification on non-inline functions may be beneficial if the correct optimizations are made and the use of that function impacts performance in a way that it justifies it.

To me it sounds like whether to use it or not is a call made by a very critical eye as part of a performance optimization effort, perhaps using profiling tools.

A quote from the above link for those in a hurry (contains an example of bad unintended effects of specifying throw on an inline function from a naive compiler):

Exception-specification rationale

Exception specifications [ISO 15.4] are sometimes coded to indicate what exceptions may be thrown, or because the programmer hopes they will improve performance. But consider the following member from a smart pointer:

T& operator*() const throw() { return *ptr; }

This function calls no other functions; it only manipulates fundamental data types like pointers Therefore, no runtime behavior of the exception-specification can ever be invoked. The function is completely exposed to the compiler; indeed it is declared inline Therefore, a smart compiler can easily deduce that the functions are incapable of throwing exceptions, and make the same optimizations it would have made based on the empty exception-specification. A "dumb" compiler, however, may make all kinds of pessimizations.

For example, some compilers turn off inlining if there is an exception-specification. Some compilers add try/catch blocks. Such pessimizations can be a performance disaster which makes the code unusable in practical applications.

Although initially appealing, an exception-specification tends to have consequences that require very careful thought to understand. The biggest problem with exception-specifications is that programmers use them as though they have the effect the programmer would like, instead of the effect they actually have.

A non-inline function is the one place a "throws nothing" exception-specification may have some benefit with some compilers.

Why fragments, and when to use fragments instead of activities?

Not sure what video(s) you are referring to, but I doubt they are saying you should use fragments instead of activities, because they are not directly interchangeable. There is actually a fairly detailed entry in the Dev Guide, consider reading it for details.

In short, fragments live inside activities, and each activity can host many fragments. Like activities, they have a specific lifecycle, unlike activities, they are not top-level application components. Advantages of fragments include code reuse and modularity (e.g., using the same list view in many activities), including the ability to build multi-pane interfaces (mostly useful on tablets). The main disadvantage is (some) added complexity. You can generally achieve the same thing with (custom) views in a non-standard and less robust way.

Swapping two variable value without using third variable

Maybe off topic, but if you know what you are swapping a single variable between two different values, you may be able to do array logic. Each time this line of code is run, it will swap the value between 1 and 2.

n = [2, 1][n - 1]

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

Php multiple delimiters in explode

How about using strtr() to substitute all of your other delimiters with the first one?

private function multiExplode($delimiters,$string) {
    return explode(
                array_slice(    $delimiters, 1  ),

It's sort of unreadable, I guess, but I tested it as working over here.

One-liners ftw!

SelectSingleNode returning null for known good xml node path using XPath

Well... I had the same issue and it was a headache. Since I didn't care much about the namespace or the xml schema, I just deleted this data from my xml and it solved all my issues. May not be the best answer? Probably, but if you don't want to deal with all of this and you ONLY care about the data (and won't be using the xml for some other task) deleting the namespace may solve your problems.

XmlDocument vinDoc = new XmlDocument();
string vinInfo = "your xml string";

vinDoc.InnerXml = vinDoc.InnerXml.Replace("xmlns=\"\/\", "");

Java: print contents of text file to screen

Why hasn't anyone thought it was worth mentioning Scanner?

Scanner input = new Scanner(new File("foo.txt"));

while (input.hasNextLine())

Select specific row from mysql table

You can use LIMIT 2,1 instead of WHERE row_number() = 3.

As the documentation explains, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return.

Keep in mind that it's an 0-based index. So, if you want the line number n, the first argument should be n-1. The second argument will always be 1, because you just want one row. For example, if you want the line number 56 of a table customer:

SELECT * FROM customer LIMIT 55,1

Log exception with traceback

maybe not as stylish, but easier:

/path/to/your/ 2>&1 | (while read; do echo "$REPLY" >> $log; done)

How to count the number of occurrences of an element in a List

What you want is a Bag - which is like a set but also counts the number of occurances. Unfortunately the java Collections framework - great as they are dont have a Bag impl. For that one must use the Apache Common Collection link text

Can't operator == be applied to generic types in C#?

I wrote the following function looking at the latest msdn. It can easily compare two objects x and y:

static bool IsLessThan(T x, T y) 
    return ((IComparable)(x)).CompareTo(y) <= 0;

Typescript empty object for a typed variable

Note that using const user = {} as UserType just provides intellisense but at runtime user is empty object {} and has no property inside. that means user.Email will give undefined instead of ""

type UserType = {
    Username: string;
    Email: string;

So, use class with constructor for actually creating objects with default properties.

type UserType = {
  Username: string;
  Email: string;

class User implements UserType {
  constructor() {
    this.Username = "";
    this.Email = "";

  Username: string;
  Email: string;

const myUser = new User();
console.log(myUser); // output: {Username: "", Email: ""}
console.log("val: "+myUser.Email); // output: ""

You can also use interface instead of type

interface UserType {
  Username: string;
  Email: string;

...and rest of code remains same.

Actually, you can even skip the constructor part and use it like this:

class User implements UserType {
      Username = ""; // will be added to new obj
      Email: string; // will not be added

const myUser = new User();
console.log(myUser); // output: {Username: ""}

Adding a column to a data.frame

You can add a column to your data using various techniques. The quotes below come from the "Details" section of the relevant help text, [[.data.frame.

Data frames can be indexed in several modes. When [ and [[ are used with a single vector index (x[i] or x[[i]]), they index the data frame as if it were a list.

my.dataframe["new.col"] <- a.vector
my.dataframe[["new.col"]] <- a.vector

The data.frame method for $, treats x as a list

my.dataframe$new.col <- a.vector

When [ and [[ are used with two indices (x[i, j] and x[[i, j]]) they act like indexing a matrix

my.dataframe[ , "new.col"] <- a.vector

Since the method for data.frame assumes that if you don't specify if you're working with columns or rows, it will assume you mean columns.

For your example, this should work:

# make some fake data
your.df <- data.frame(no = c(1:4, 1:7, 1:5), h_freq = runif(16), h_freqsq = runif(16))

# find where one appears and 
from <- which(your.df$no == 1)
to <- c((from-1)[-1], nrow(your.df)) # up to which point the sequence runs

# generate a sequence (len) and based on its length, repeat a consecutive number len times
get.seq <- mapply(from, to, 1:length(from), FUN = function(x, y, z) {
            len <- length(seq(from = x[1], to = y[1]))
            return(rep(z, times = len))

# when we unlist, we get a vector
your.df$group <- unlist(get.seq)
# and append it to your original data.frame. since this is
# designating a group, it makes sense to make it a factor
your.df$group <- as.factor(your.df$group)

   no     h_freq   h_freqsq group
1   1 0.40998238 0.06463876     1
2   2 0.98086928 0.33093795     1
3   3 0.28908651 0.74077119     1
4   4 0.10476768 0.56784786     1
5   1 0.75478995 0.60479945     2
6   2 0.26974011 0.95231761     2
7   3 0.53676266 0.74370154     2
8   4 0.99784066 0.37499294     2
9   5 0.89771767 0.83467805     2
10  6 0.05363139 0.32066178     2
11  7 0.71741529 0.84572717     2
12  1 0.10654430 0.32917711     3
13  2 0.41971959 0.87155514     3
14  3 0.32432646 0.65789294     3
15  4 0.77896780 0.27599187     3
16  5 0.06100008 0.55399326     3

Measuring the distance between two coordinates in PHP

For exact values do it like that:

public function DistAB()
      $delta_lat = $this->lat_b - $this->lat_a ;
      $delta_lon = $this->lon_b - $this->lon_a ;

      $a = pow(sin($delta_lat/2), 2);
      $a += cos(deg2rad($this->lat_a9)) * cos(deg2rad($this->lat_b9)) * pow(sin(deg2rad($delta_lon/29)), 2);
      $c = 2 * atan2(sqrt($a), sqrt(1-$a));

      $distance = 2 * $earth_radius * $c;
      $distance = round($distance, 4);

      $this->measure = $distance;

Hmm I think that should do it...


For formulars and at least JS-implementations try:

Dare me... I forgot to deg2rad all the values in the circle-functions...

Convert from lowercase to uppercase all values in all character variables in dataframe

If you need to deal with data.frames that include factors you can use:

df = data.frame(v1=letters[1:5],v2=1:5,v3=letters[10:14],v4=as.factor(letters[1:5]),v5=runif(5),stringsAsFactors=FALSE)

    v1 v2 v3 v4        v5
    1  a  1  j  a 0.1774909
    2  b  2  k  b 0.4405019
    3  c  3  l  c 0.7042878
    4  d  4  m  d 0.8829965
    5  e  5  n  e 0.9702505

         v1          v2          v3          v4          v5
"character"   "integer" "character"    "factor"   "numeric"

Use mutate_each_ to convert factors to character then convert all to uppercase

   upper_it = function(X){X %>% mutate_each_( funs(as.character(.)), names( .[sapply(., is.factor)] )) %>%
   mutate_each_( funs(toupper), names( .[sapply(., is.character)] ))}   # convert factor to character then uppercase


      v1 v2 v3 v4
    1  A  1  J  A
    2  B  2  K  B
    3  C  3  L  C
    4  D  4  M  D
    5  E  5  N  E


sapply( upper_it(df),class)
         v1          v2          v3          v4          v5
"character"   "integer" "character" "character"   "numeric"

How do I get the localhost name in PowerShell?

Long form:

get-content env:computername

Short form:

gc env:computername

Return value in a Bash function

The problem with other answers is they either use a global, which can be overwritten when several functions are in a call chain, or echo which means your function cannot output diagnostic info (you will forget your function does this and the "result", i.e. return value, will contain more info than your caller expects, leading to weird bug), or eval which is way too heavy and hacky.

The proper way to do this is to put the top level stuff in a function and use a local with bash's dynamic scoping rule. Example:



    local ret_val=nothing
    echo $ret_val
    echo $ret_val
    echo $ret_val


This outputs


Dynamic scoping means that ret_val points to a different object depending on the caller! This is different from lexical scoping, which is what most programming languages use. This is actually a documented feature, just easy to miss, and not very well explained, here is the documentation for it (emphasis is mine):

Variables local to the function may be declared with the local builtin. These variables are visible only to the function and the commands it invokes.

For someone with a C/C++/Python/Java/C#/javascript background, this is probably the biggest hurdle: functions in bash are not functions, they are commands, and behave as such: they can output to stdout/stderr, they can pipe in/out, they can return an exit code. Basically there is no difference between defining a command in a script and creating an executable that can be called from the command line.

So instead of writing your script like this:

top-level code 
bunch of functions
more top-level code

write it like this:

# define your main, containing all top-level code
bunch of functions
# call main

where main() declares ret_val as local and all other functions return values via ret_val.

See also the following Unix & Linux question: Scope of Local Variables in Shell Functions.

Another, perhaps even better solution depending on situation, is the one posted by ya.teck which uses local -n.

Best practice for instantiating a new Android Fragment

I believe I have a much simpeler solution for this.

public class MyFragment extends Fragment{

   private String mTitle;
   private List<MyObject> mObjects;

   public static MyFragment newInstance(String title, List<MyObject> objects)
   MyFragment myFrag = new MyFragment();
   myFrag.mTitle = title;
   myFrag.mObjects = objects;
   return myFrag;

Apply function to pandas groupby

apply takes a function to apply to each value, not the series, and accepts kwargs. So, the values do not have the .size() method.

Perhaps this would work:

from pandas import *

d = {"my_label": Series(['A','B','A','C','D','D','E'])}
df = DataFrame(d)

def as_perc(value, total):
    return value/float(total)

def get_count(values):
    return len(values)

grouped_count = df.groupby("my_label").my_label.agg(get_count)
data = grouped_count.apply(as_perc, total=df.my_label.count())

The .agg() method here takes a function that is applied to all values of the groupby object.

Checking if a string is empty or null in Java

You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.


System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true

Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).


System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

Python + Django page redirect

Since Django 1.1, you can also use the simpler redirect shortcut:

from django.shortcuts import redirect

def myview(request):
    return redirect('/path')

It also takes an optional permanent=True keyword argument.

Group By Multiple Columns

You can also use a Tuple<> for a strongly-typed grouping.

from grouping in list.GroupBy(x => new Tuple<string,string,string>(x.Person.LastName,x.Person.FirstName,x.Person.MiddleName))
select new SummaryItem
    LastName = grouping.Key.Item1,
    FirstName = grouping.Key.Item2,
    MiddleName = grouping.Key.Item3,
    DayCount = grouping.Count(), 
    AmountBilled = grouping.Sum(x => x.Rate),

Map implementation with duplicate keys

This problem can be solved with a list of map entry List<Map.Entry<K,V>>. We don't need to use neither external libraries nor new implementation of Map. A map entry can be created like this: Map.Entry<String, Integer> entry = new AbstractMap.SimpleEntry<String, Integer>("key", 1);

Is there any way I can define a variable in LaTeX?

add the following to you preamble:

\newcommand{\newCommandName}{text to insert}

Then you can just use \newCommandName{} in the text

For more info on \newcommand, see e.g. wikibooks





Angular 2 router.navigate

import { ActivatedRoute } from '@angular/router';_x000D_
export class ClassName {_x000D_
  private router = ActivatedRoute;_x000D_
    constructor(r: ActivatedRoute) {_x000D_
        this.router =r;_x000D_
onSuccess() {_x000D_
         {queryParams: {email: loginEmail, code: userCode}});_x000D_
Get this values:_x000D_
ngOnInit() {_x000D_
        .subscribe(params => {_x000D_
            let code = params['code'];_x000D_
            let userEmail = params['email'];_x000D_


Vue.js get selected option on @change

You can save your @change="onChange()" an use watchers. Vue computes and watches, it´s designed for that. In case you only need the value and not other complex Event atributes.

Something like:

  watch: {
    leaveType () {
  methods: {
     onChange() {
         console.log('The new value is: ', this.leaveType)

What port number does SOAP use?

SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.

One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.

so exclusively open SOAP Port in Firewalls

How to embed new Youtube's live video permanent URL?

The embed URL for a channel's live stream is:

You can find your CHANNEL_ID at

Using IF ELSE statement based on Count to execute different Insert statements

IF exists

IF exists (select * from table_1 where col1 = 'value')
    -- one or more
    insert into table_1 (col1) values ('valueB')
    -- zero
    insert into table_1 (col1) values ('value') 

Convert Data URI to File then append to FormData

The original answer by Stoive is easily fixable by changing the last line to accommodate Blob:

function dataURItoBlob (dataURI) {
    // convert base64 to raw binary data held in a string
    // doesn't handle URLEncoded DataURIs
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
        byteString = unescape(dataURI.split(',')[1]);
    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to an ArrayBuffer
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);

    // write the ArrayBuffer to a blob, and you're done
    return new Blob([ab],{type: mimeString});

import sun.misc.BASE64Encoder results in error compiled in Eclipse

Java 6 ships the javax.xml.bind.DatatypeConverter. This class provides two static methods that support the same decoding & encoding:

parseBase64Binary() / printBase64Binary()

Update: Since Java 8 we now have a much better Base64 Support.

Use this and you will not need an extra library, like Apache Commons Codec.

How to make responsive table


A responsive table is simply a 100% width table.

You can just set up your table with this CSS:

.table { width: 100%; }

Demo here

You can use media queries to show/hide/manipulate columns according to the screens dimensions by adding a class (or targeting using nth-child, etc):

@media screen and (max-width: 320px) {
    .hide { display: none; }


<td class="hide">Not important</td>

More advanced solutions

If you have a table with a lot of data and you would like to make it readable on small screen devices there are many other solutions:

Black transparent overlay on image hover with only CSS?

Here's a good way using :after on the image div, instead of the extra overlay div:

<div class="image">
    <img src="" alt="" />

.image {position:relative; border:1px solid black; width:200px; height:200px;}
.image img {max-width:100%; max-height:100%;}
.image:hover:after {content:""; position:absolute; top:0; left:0; bottom:0; right:0; background-color: rgba(0,0,0,0.3);}

Difference between Groovy Binary and Source release?

Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.

AndroidStudio: Failed to sync Install build tools

I had the same problem, in my cases this happened because I changed the time on my computer to load .apk on google play. I spent a few hours to fix "this" problem until I remembered and changed the time back.

How to start Spyder IDE on Windows

As stated in the documentation of Spyder, you need to install PyQt5 first.

Open a Command Prompt as Administrator, then run:

pip install pyqt5
pip install spyder

Then you can find the spyder3.exe in the Python3.6/Scripts folder. You can also make a shortcut to it. No need for Anaconda.

Is it better in C++ to pass by value or pass by constant reference?

It used to be generally recommended best practice1 to use pass by const ref for all types, except for builtin types (char, int, double, etc.), for iterators and for function objects (lambdas, classes deriving from std::*_function).

This was especially true before the existence of move semantics. The reason is simple: if you passed by value, a copy of the object had to be made and, except for very small objects, this is always more expensive than passing a reference.

With C++11, we have gained move semantics. In a nutshell, move semantics permit that, in some cases, an object can be passed “by value” without copying it. In particular, this is the case when the object that you are passing is an rvalue.

In itself, moving an object is still at least as expensive as passing by reference. However, in many cases a function will internally copy an object anyway — i.e. it will take ownership of the argument.2

In these situations we have the following (simplified) trade-off:

  1. We can pass the object by reference, then copy internally.
  2. We can pass the object by value.

“Pass by value” still causes the object to be copied, unless the object is an rvalue. In the case of an rvalue, the object can be moved instead, so that the second case is suddenly no longer “copy, then move” but “move, then (potentially) move again”.

For large objects that implement proper move constructors (such as vectors, strings …), the second case is then vastly more efficient than the first. Therefore, it is recommended to use pass by value if the function takes ownership of the argument, and if the object type supports efficient moving.

A historical note:

In fact, any modern compiler should be able to figure out when passing by value is expensive, and implicitly convert the call to use a const ref if possible.

In theory. In practice, compilers can’t always change this without breaking the function’s binary interface. In some special cases (when the function is inlined) the copy will actually be elided if the compiler can figure out that the original object won’t be changed through the actions in the function.

But in general the compiler can’t determine this, and the advent of move semantics in C++ has made this optimisation much less relevant.

1 E.g. in Scott Meyers, Effective C++.

2 This is especially often true for object constructors, which may take arguments and store them internally to be part of the constructed object’s state.

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

How do you completely remove the button border in wpf?

I don't know why others haven't pointed out that this question is duplicated with this one with accepted answer.

I quote here the solution: You need to override the ControlTemplate of the Button:

<Button Content="save" Name="btnSaveEditedText" 
                FontFamily="Tw Cen MT Condensed" 
        <ControlTemplate TargetType="Button">
             <ContentPresenter Content="{TemplateBinding Content}"/>

How to pass values across the pages in without using Session

There are multiple ways to achieve this. I can explain you in brief about the 4 types which we use in our daily programming life cycle.

Please go through the below points.

1 Query String.


Response.Redirect("SecondForm.aspx?Parameter=" + TextBox1.Text);


TextBox1.Text = Request.QueryString["Parameter"].ToString();

This is the most reliable way when you are passing integer kind of value or other short parameters. More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:


Response.Redirect("SecondForm.aspx?Parameter=" + Server.UrlEncode(TextBox1.Text));


TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());

URL Encoding

  1. Server.URLEncode
  2. HttpServerUtility.UrlDecode

2. Passing value through context object

Passing value through context object is another widely used method.


TextBox1.Text = this.Context.Items["Parameter"].ToString();


this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("SecondForm.aspx", true);

Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.

3. Posting form to another page instead of PostBack

Third method of passing value by posting page to another form. Here is the example of that:


private void Page_Load(object sender, System.EventArgs e)
   buttonSubmit.Attributes.Add("onclick", "return PostPage();");

And we create a javascript function to post the form.


function PostPage()
   document.Form1.action = "SecondForm.aspx";
   document.Form1.method = "POST";
TextBox1.Text = Request.Form["TextBox1"].ToString();

Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false

4. Another method is by adding PostBackURL property of control for cross page post back

In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.


<asp:Button id=buttonPassValue style=”Z-INDEX: 102" runat=”server” Text=”Button”         PostBackUrl=”~/SecondForm.aspx”></asp:Button>


TextBox1.Text = Request.Form["TextBox1"].ToString();

In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.

You can also use PreviousPage class to access controls of previous page instead of using classic Request object.


TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1");
TextBox1.Text = textBoxTemp.Text;

As you have noticed, this is also a simple and clean implementation of passing value between pages.



Unzipping files

Code example is given on the author site's. You can use babelfish to translate the texts (Japanese to English).

As far as I understand Japanese, this zip inflate code is meant to decode ZIP data (streams) not ZIP archive.

How to check if JavaScript object is JSON

I combine the typeof operator with a check of the constructor attribute (by Peter):

var typeOf = function(object) {
    var firstShot = typeof object;
    if (firstShot !== 'object') {
        return firstShot;
    else if (object.constructor === [].constructor) {
        return 'array';
    else if (object.constructor === {}.constructor) {
        return 'object';
    else if (object === null) {
        return 'null';
    else {
        return 'don\'t know';

// Test
var testSubjects = [true, false, 1, 2.3, 'string', [4,5,6], {foo: 'bar'}, null, undefined];

console.log(['typeOf()', 'input parameter'].join('\t'))
console.log(new Array(28).join('-'));{
    console.log([typeOf(testSubject), JSON.stringify(testSubject)].join('\t\t'));


typeOf()    input parameter
boolean     true
boolean     false
number      1
number      2.3
string      "string"
array       [4,5,6]
object      {"foo":"bar"}
null        null

"unadd" a file to svn before commit

Use svn revert --recursive folder_name


svn revert is inherently dangerous, since its entire purpose is to throw away data — namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes.

How to remove text before | character in notepad++

To replace anything that starts with "text" until the last character:



text             hsjh sdjh sd          jhsjhsdjhsdj hsd
                                                      last character

To replace anything that starts with "text" until "123"

text.+(\ 123)


text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e
^                                   ^
From here                     To here

how to add or embed CKEditor in php page

After reading the Quick Start Guide

In your HTML page add an element that CKEditor should replace:

<textarea name="content" id="editor"></textarea>

Load the classic editor build (here CDN location is used):

<script src=""></script>

Call the ClassicEditor.create() method.

        .create( document.querySelector( '#editor' ) )
        .catch( error => {
            console.error( error );
        } );


<!DOCTYPE html>
    <meta charset="utf-8">
    <title>CKEditor 5 - Classic editor</title>
    <script src=""></script>
    <h1>Classic editor</h1>
    <textarea name="content" id="editor">
        <p>This is some sample content.</p>
            .create( document.querySelector( '#editor' ) )
            .catch( error => {
                console.error( error );
            } );

This example is for the specific classic editor. FOr other variants, only CDN will change.

SimpleDateFormat and locale based format string

Localization of date string:

Based on redsonic's post:

private String localizeDate(String inputdate, Locale locale) { 

    Date date = new Date();
    SimpleDateFormat dateFormatCN = new SimpleDateFormat("dd-MMM-yyyy", locale);       
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");

    try {
        date = dateFormat.parse(inputdate);
    } catch (ParseException e) {
        log.warn("Input date was not correct. Can not localize it.");
        return inputdate;
    return dateFormatCN.format(date);

String localizedDate = localizeDate("05-Sep-2013", new Locale("zh","CN"));

will be like 05-??-2013

How to generate a number of most distinctive colors in R?

In my understanding searching distinctive colors is related to search efficiently from an unit cube, where 3 dimensions of the cube are three vectors along red, green and blue axes. This can be simplified to search in a cylinder (HSV analogy), where you fix Saturation (S) and Value (V) and find random Hue values. It works in many cases, and see this here :

In R,

get_distinct_hues <- function(ncolor,s=0.5,v=0.95,seed=40) {
  golden_ratio_conjugate <- 0.618033988749895
  h <- runif(1)
  H <- vector("numeric",ncolor)
  for(i in seq_len(ncolor)) {
    h <- (h + golden_ratio_conjugate) %% 1
    H[i] <- h

An alternative way, is to use R package "uniformly"

and this simple function can generate distinctive colors:

get_random_distinct_colors <- function(ncolor,seed = 100) {
  rgb_mat <- runif_in_cube(n=ncolor,d=3,O=rep(0.5,3),r=0.5)

One can think of a little bit more involved function by grid-search:

get_random_grid_colors <- function(ncolor,seed = 100) {
  ngrid <- ceiling(ncolor^(1/3))
  x <- seq(0,1,length=ngrid+1)[1:ngrid]
  dx <- (x[2] - x[1])/2
  x <- x + dx
  origins <- expand.grid(x,x,x)
  nbox <- nrow(origins) 
  RGB <- vector("numeric",nbox)
  for(i in seq_len(nbox)) {
    rgb <- runif_in_cube(n=1,d=3,O=as.numeric(origins[i,]),r=dx)
    RGB[i] <- rgb(rgb[1,1],rgb[1,2],rgb[1,3])
  index <- sample(seq(1,nbox),ncolor)

check this functions by:

ncolor <- 20
barplot(rep(1,ncolor),col=get_distinct_hues(ncolor))          # approach 1
barplot(rep(1,ncolor),col=get_random_distinct_colors(ncolor)) # approach 2
barplot(rep(1,ncolor),col=get_random_grid_colors(ncolor))     # approach 3

However, note that, defining a distinct palette with human perceptible colors is not simple. Which of the above approach generates diverse color set is yet to be tested.

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

If you're using Angular's ng-repeat to populate the table hackel's jquery snippet will not work by placing it in the document load event. You'll need to run the snippet after angular has finished rendering the table.

To trigger an event after ng-repeat has rendered try this directive:

var app = angular.module('myapp', [])
.directive('onFinishRender', function ($timeout) {
return {
    restrict: 'A',
    link: function (scope, element, attr) {
        if (scope.$last === true) {
            $timeout(function () {

Complete example in angular:

I got the directive from here: Use AngularJS just for routing purposes

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }

public class OtherClass {
    public void anotherMethod();

Web page and JavaScript code:

<applet id="app"
        code="MethodInvocation" ...>
<script language="javascript">
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();

Divide a number by 3 without using *, /, +, -, % operators

Where InputValue is the number to divide by 3

  FROM (SELECT InputValue NUM from sys.dual
         UNION ALL SELECT 0 from sys.dual
         UNION ALL SELECT 0 from sys.dual) divby3

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

`Follow below steps:

its working for me.To resolve this issue,

1.Right Click on appcompat_v7 library and select Properties

2.Now, Click on Android Option, Set Project Build Path as Android 5.0 (API level 21) Apply Changes.

3.Now go to file under appcompat_v7 library,

4.Set the project target as : target=android-21

5.Now Clean + Build appcompat_v7 library and your projects`

Mutex example / tutorial?

For those looking for the shortex mutex example:

#include <mutex>

int main() {
    std::mutex m;

    // do thread-safe stuff

Change Select List Option background colour on hover in html

Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

How to convert <select> dropdown into an unordered list using jquery?

Good ways to manage a changelog using git?

Since creating a tag per version is the best practice, you may want to partition your changelog per version. In that case, this command could help you:

git log YOUR_LAST_VERSION_TAG..HEAD --no-merges --format=%B

Fastest way to check if a file exist using standard C++/C++11/C?

Same as suggested by PherricOxide but in C

#include <sys/stat.h>
int exist(const char *name)
  struct stat   buffer;
  return (stat (name, &buffer) == 0);

How to split CSV files as per number of rows specified?

This should do it for you - all your files will end up called Part1-Part500.

HDR=$(head -1 $FILENAME)   # Pick up CSV header line to apply to each file
split -l 20 $FILENAME xyz  # Split the file into chunks of 20 lines each
for f in xyz*              # Go through all newly created chunks
   echo $HDR > Part${n}    # Write out header to new file called "Part(n)"
   cat $f >> Part${n}      # Add in the 20 lines from the "split" command
   rm $f                   # Remove temporary file
   ((n++))                 # Increment name of output part

Python != operation vs "is not"

>>> () is ()
>>> 1 is 1
>>> (1,) == (1,)
>>> (1,) is (1,)
>>> a = (1,)
>>> b = a
>>> a is b

Some objects are singletons, and thus is with them is equivalent to ==. Most are not.

How to Remove Array Element and Then Re-Index Array?

array_splice($array, array_search(array_value, $array), 1);

Runnable with a parameter?

You could put it in a function.

String paramStr = "a parameter";
Runnable myRunnable = createRunnable(paramStr);

private Runnable createRunnable(final String paramStr){

    Runnable aRunnable = new Runnable(){
        public void run(){

    return aRunnable;


(When I used this, my parameter was an integer ID, which I used to make a hashmap of ID --> myRunnables. That way, I can use the hashmap to post/remove different myRunnable objects in a handler.)

Get output parameter value in ADO.NET

You can get your result by below code::

using (SqlConnection conn = new SqlConnection(...))
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add other parameters parameters

    //Add the output parameter to the command object
    SqlParameter outPutParameter = new SqlParameter();
    outPutParameter.ParameterName = "@Id";
    outPutParameter.SqlDbType = System.Data.SqlDbType.Int;
    outPutParameter.Direction = System.Data.ParameterDirection.Output;


    //Retrieve the value of the output parameter
    string Id = outPutParameter.Value.ToString();

    // *** read output parameter here, how?

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:


It allows filters to be mapped on the particular servlet:


Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

public class Servlet1 extends HttpServlet {

See also:

Difference between single and double quotes in Bash

Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \ escapes, etc.


$ echo "$(echo "upg")"
$ echo '$(echo "upg")'
$(echo "upg")

The Bash manual has this to say: Single Quotes

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. Double Quotes

Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.

The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

How to disable auto-play for local video in iframe

Try This Code for disable auto play video.

Its Working . Please Vote if your are done with this

<div class="embed-responsive embed-responsive-16by9">
    <video controls="true" class="embed-responsive-item">
      <source src="example.mp4" type="video/mp4" />

How can I obfuscate (protect) JavaScript?

Try JScrambler. I gave it a spin recently and was impressed by it. It provides a set of templates for obfuscation with predefined settings for those who don't care much about the details and just want to get it done quickly. You can also create custom obfuscation by choosing whatever transformations/techniques you want.

How to set focus on an input field after rendering?

To move focus to a newly created element, you can store the element's ID in the state and use it to set autoFocus. e.g.

export default class DefaultRolesPage extends React.Component {

    addRole = ev => {
        const roleKey = this.roleKey++;
            focus: {$set: roleKey},
            formData: {
                roles: {
                    $push: [{
                        id: null,
                        name: '',
                        permissions: new Set(),
                        key: roleKey,

    render() {
        const {formData} = this.state;

        return (
            <GridForm onSubmit={this.submit}>
                {, idx) => (
                    <GridSection key={role.key}>
                                <TextBox value={} onChange={this.roleName(idx)} autoFocus={role.key === this.state.focus}/>

This way none of the textboxes get focus on page load (like I want), but when you press the "Add" button to create a new record, then that new record gets focus.

Since autoFocus doesn't "run" again unless the component gets remounted, I don't have to bother unsetting this.state.focus (i.e. it won't keep stealing focus back as I update other states).

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
End Sub

Python List vs. Array - when to use?

This answer will sum up almost all the queries about when to use List and Array:

  1. The main difference between these two data types is the operations you can perform on them. For example, you can divide an array by 3 and it will divide each element of array by 3. Same can not be done with the list.

  2. The list is the part of python's syntax so it doesn't need to be declared whereas you have to declare the array before using it.

  3. You can store values of different data-types in a list (heterogeneous), whereas in Array you can only store values of only the same data-type (homogeneous).

  4. Arrays being rich in functionalities and fast, it is widely used for arithmetic operations and for storing a large amount of data - compared to list.

  5. Arrays take less memory compared to lists.

Bootstrap dropdown sub menu missing

Shprink's code helped me the most, but to avoid the dropdown to go off-screen i updated it to:


$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
    // Avoid following the href location when clicking
    // Avoid having the menu to close when clicking
    // If a menu is already open we close it
    $('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open');
    // opening the one you clicked on

    var menu = $(this).parent().find("ul");
    var menupos = $(menu).offset();

    if (menupos.left + menu.width() > $(window).width()) {
        var newpos = -$(menu).width();
        menu.css({ left: newpos });    
    } else {
        var newpos = $(this).parent().width();
        menu.css({ left: newpos });


CSS: FROM background-color: #eeeeee TO background-color: #c5c5c5 - white font & light background wasn't looking good.

.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
  background-color: #c5c5c5;
  border-color: #428bca;

I hope this helps people as much as it did for me!

But i hope Bootstrap add the subs feature back ASAP.

JavaFX Location is not set error message

I think problem is either incorrect layout name or invalid layout file path.

for IntelliJ, you can create resource directory and place layout files there.

FXMLLoader loader = new FXMLLoader();
rootLayout = loader.load();

How can I add additional PHP versions to MAMP

First stop the Server if its running. Go to "/Applications/MAMP/bin/", rename the PHP Version you don't need (MAMP is only allowed to use 2 PHP Versions), e.g. "_php5.2.17". Now MAMP will use the php versions that are left. Go to the MAMP Manager and then settings, then switch to the php version you need.

One problem with this solution I encountered was the httpd process (took me a while to figure that out xD). If you have the httpd process running in the background, then the php switch won't work, until you stop those processes (sometimes MAMP has an awkward problem to stop the server, thats why this process can be still alive). Start your Activity Monitor on your Mac (Shortcut: Press Command+Space and type in activity...), go to the Search Function and type in "httpd", close all those processes. Now you should be able to switch your PHP Version with the MAMP Manager.

C++ Array of pointers: delete or delete []?

delete[] monsters;

Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.

Your other implementation is the correct one as the pointers in the array do point to dynamically allocated Monster objects.

Note that with your current memory allocation strategy you probably want to declare your own copy constructor and copy-assignment operator so that unintentional copying doesn't cause double deletes. (If you you want to prevent copying you could declare them as private and not actually implement them.)

How to change the Jupyter start-up folder

Use the jupyter notebook config file:

Open cmd (or Anaconda Prompt) and run jupyter notebook --generate-config.

This writes a file to C:\Users\username\.jupyter\

Browse to the file location and open it in an Editor

Search for the following line in the file: #c.NotebookApp.notebook_dir = ''

Replace by c.NotebookApp.notebook_dir = '/the/path/to/home/folder/'

Make sure you use forward slashes in your path and use /home/user/ instead of ~/ for your home directory, backslashes could be used if placed in double quotes even if folder name contains spaces as such : "D:\yourUserName\Any Folder\More Folders\"

Remove the # at the beginning of the line to allow the line to execute

How to dynamic new Anonymous Class?

You can create an ExpandoObject like this:

IDictionary<string,object> expando = new ExpandoObject();
expando["Name"] = value;

And after casting it to dynamic, those values will look like properties:

dynamic d = expando;

However, they are not actual properties and cannot be accessed using Reflection. So the following statement will return a null:


Bootstrap 3 Multi-column within a single ul not floating properly

You should try using the Grid Template.

Here's what I've used for a two Column Layout of a <ul>

<ul class="list-group row">
     <li class="list-group-item col-xs-6">Row1</li>
     <li class="list-group-item col-xs-6">Row2</li>
     <li class="list-group-item col-xs-6">Row3</li>
     <li class="list-group-item col-xs-6">Row4</li>
     <li class="list-group-item col-xs-6">Row5</li>

This worked for me.

How can I stop redis-server?

Redis has configuration parameter pidfile (e.g. /etc/redis.conf - check redis source code), for example:

# If a pid file is specified, Redis writes it where specified at startup
# and removes it at exit.
# When the server runs non daemonized, no pid file is created if none is
# specified in the configuration. When the server is daemonized, the pid file
# is used even if not specified, defaulting to "/var/run/".
pidfile /var/run/

If it is set or could be set, instead of searching for process id (pid) by using ps + grep something like this could be used:

kill $(cat /var/run/

If required one can make redis stop script like this (adapted default redis 5.0 init.d script in redis source code):

if [ ! -f $PIDFILE ]
    echo "$PIDFILE does not exist, process is not running"
    PID=$(cat $PIDFILE)
    echo "Stopping ..."
    kill $PID
    while [ -x /proc/${PID} ]
        echo "Waiting for Redis to shutdown ..."
        sleep 1
    echo "Redis stopped"

Insert NULL value into INT column

If column is not NOT NULL (nullable).

You just put NULL instead of value in INSERT statement.

C programming: Dereferencing pointer to incomplete type error

How did you actually define the structure? If

struct {
  char name[32];
  int  size;
  int  start;
  int  popularity;
} stasher_file;

is to be taken as type definition, it's missing a typedef. When written as above, you actually define a variable called stasher_file, whose type is some anonymous struct type.


typedef struct { ... } stasher_file;

(or, as already mentioned by others):

struct stasher_file { ... };

The latter actually matches your use of the type. The first form would require that you remove the struct before variable declarations.

Connect to sqlplus in a shell script and run SQL scripts

For example:

sqlplus -s admin/password << EOF
whenever sqlerror exit sql.sqlcode;
set echo off 
set heading off



How to insert close button in popover for Bootstrap

The trick is to get the current Popover with .data('bs.popover').tip():

$('#my_trigger').popover().on('', function() {
    // Define elements
    var current_trigger=$(this);

    // Activate close button
    current_popover.find('button.close').click(function() {

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

I just put an index.html file in /htdocs and type in - and up comes the html.

Add a folder "named Forum" and type in

Parsing json and searching through it

Functions to search through and print dicts, like JSON. *made in python 3


def pretty_search(dict_or_list, key_to_search, search_for_first_only=False):
    Give it a dict or a list of dicts and a dict key (to get values of),
    it will search through it and all containing dicts and arrays
    for all values of dict key you gave, and will return you set of them
    unless you wont specify search_for_first_only=True

    :param dict_or_list: 
    :param key_to_search: 
    :param search_for_first_only: 
    search_result = set()
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if key == key_to_search:
                if search_for_first_only:
                    return key_value
            if isinstance(key_value, dict) or isinstance(key_value, list) or isinstance(key_value, set):
                _search_result = pretty_search(key_value, key_to_search, search_for_first_only)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, list) or isinstance(element, set) or isinstance(element, dict):
                _search_result = pretty_search(element, key_to_search, search_result)
                if _search_result and search_for_first_only:
                    return _search_result
                elif _search_result:
                    for result in _search_result:
    return search_result if search_result else None


def pretty_print(dict_or_list, print_spaces=0):
    Give it a dict key (to get values of),
    it will return you a pretty for print version
    of a dict or a list of dicts you gave.

    :param dict_or_list: 
    :param print_spaces: 
    pretty_text = ""
    if isinstance(dict_or_list, dict):
        for key in dict_or_list:
            key_value = dict_or_list[key]
            if isinstance(key_value, dict):
                key_value = pretty_print(key_value, print_spaces + 1)
                pretty_text += "\t" * print_spaces + "{}:\n{}\n".format(key, key_value)
            elif isinstance(key_value, list) or isinstance(key_value, set):
                pretty_text += "\t" * print_spaces + "{}:\n".format(key)
                for element in key_value:
                    if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                        pretty_text += pretty_print(element, print_spaces + 1)
                        pretty_text += "\t" * (print_spaces + 1) + "{}\n".format(element)
                pretty_text += "\t" * print_spaces + "{}: {}\n".format(key, key_value)
    elif isinstance(dict_or_list, list) or isinstance(dict_or_list, set):
        for element in dict_or_list:
            if isinstance(element, dict) or isinstance(element, list) or isinstance(element, set):
                pretty_text += pretty_print(element, print_spaces + 1)
                pretty_text += "\t" * print_spaces + "{}\n".format(element)
        pretty_text += str(dict_or_list)
    if print_spaces == 0:
    return pretty_text

How to fluently build JSON in Java?

You can use one of Java template engines. I love this method because you are separating your logic from the view.

Java 8+:


Java 6/7:


Example template file:

Name: {{name}}
Price: {{price}}
  Feature: {{description}}

Might be powered by some backing code:

public class Context {
  List<Item> items() {
    return Arrays.asList(
      new Item("Item 1", "$19.99", Arrays.asList(new Feature("New!"), new Feature("Awesome!"))),
      new Item("Item 2", "$29.99", Arrays.asList(new Feature("Old."), new Feature("Ugly.")))

  static class Item {
    Item(String name, String price, List<Feature> features) { = name;
      this.price = price;
      this.features = features;
    String name, price;
    List<Feature> features;

  static class Feature {
    Feature(String description) {
       this.description = description;
    String description;

And would result in:

Name: Item 1
Price: $19.99
  Feature: New!
  Feature: Awesome!
Name: Item 2
Price: $29.99
  Feature: Old.
  Feature: Ugly.

Count occurrences of a char in a string using Bash

awk works well if you your server has it

num=$(echo "${var}" | awk -F, '{print NF-1}')
echo "${num}"

openssl s_client -cert: Proving a client certificate was sent to the server

I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:

Yourhostname here -vvvvvvvvvv s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state

When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.

The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.

You are clearly sending a certificate. The server is clearly rejecting it.

The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.

docker mounting volumes on host

VOLUME is used in Dockerfile to expose the volume to be used by other containers. Example, create Dockerfile as:

FROM ubuntu:14.04

RUN mkdir /myvol  
RUN echo "hello world" > /myvol/greeting  
VOLUME /myvol

build the image:

$ docker build -t testing_volume .

Run the container, say container1:

$ docker run -it <image-id of above image> bash

Now run another container with volumes-from option as (say-container2)

$ docker run -it --volumes-from <id-of-above-container> ubuntu:14.04 bash

You will get all data from container1 /myvol directory into container2 at same location.

-v option is given at run time of container which is used to mount container's directory on host. It is simple to use, just provide -v option with argument as <host-path>:<container-path>. The whole command may be as $ docker run -v <host-path>:<container-path> <image-id>

How do I add a foreign key to an existing SQLite table?

Basically you cannot but you can bypass the situation.

The correct way to add the foreign key constraint to an existing table is the following command.

db.execSQL("alter table child add column newCol integer REFERENCES parent(parent_Id)");

Then copy the parent_Id data to the newCol and then delete the Parent_Id column. Hence, no need for temporary table.

RadioGroup: How to check programmatically

In your layout you can add android:checked="true" to CheckBox you want to be selected.

Or programmatically, you can use the setChecked method defined in the checkable interface:

RadioButton b = (RadioButton) findViewById(; b.setChecked(true);

Access key value from Web.config in Razor View-MVC3 ASP.NET

The preferred method is actually:


It also doesn't need a reference to the ConfigurationManager assembly, it's already in System.Web.

How to hide command output in Bash

>/dev/null 2>&1 will mute both stdout and stderr

yum install nano >/dev/null 2>&1

Reminder - \r\n or \n\r?

The sequence is CR (Carriage Return) - LF (Line Feed). Remember dot matrix printers? Exactly. So - the correct order is \r \n

Typescript export vs. default export

I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default declaration for a class, and instead append the export tag to the class declaration. The imported class should be instead listed in the import command of the module.

That is: instead of

class Foo {
    // ...
export default Foo;

and the simple import Foo from './foo'; in the module that will import, one should use

export class Foo {
    // ...

and import {Foo} from './foo' in the importer.

The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in export default can lead to problems

Convert Python program to C/C++ code?

Yes. Look at Cython. It does just that: Converts Python to C for speedups.

Anaconda / Python: Change Anaconda Prompt User Path

Go to Start and search for "Anaconda Prompt" - right click this and choose "Open File Location", which will open a folder of shortcuts. Right click the "Anaconda Prompt" shortcut, choose "Properties" and you can adjust the starting dir in the "Start in" box.

how to get login option for phpmyadmin in xampp

If you wish to go to the login page of phpmyadmin, click the "exit" button (the second one from left to right under the main logo "phpmyadmin").

Android dependency has different version for the compile and runtime

Replace a hard coded version to + example:

implementation ''
implementation ''

What is the &#xA; character?

This is the ASCII format.

Please consider that:

Some data (like URLs) can be sent over the Internet using the ASCII character-set. Since data often contain characters outside the ASCII set, so it has to be converted into a valid ASCII format.

To find it yourself, you can visit, there you can find big tables of characters. The one you are looking is in Control Characters table.

Digging to table you can find

Oct Dec Hex Name 012 10 0A Line Feed

In the html file you can use Dec and Hex representation of charters

The Dec is represented with &#10;

The Hex is represented with &#x0A (or you can omit the leading zero &#xA)

There is a good converter at .

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP:

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server:

Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

Print debugging info from stored procedure in MySQL

I usually create log table with a stored procedure to log to it. The call the logging procedure wherever needed from the procedure under development.

Looking at other posts on this same question, it seems like a common practice, although there are some alternatives.

Override browser form-filling and input highlighting with HTML/CSS

After trying a lot of things, I found working solutions that nuked the autofilled fields and replaced them with duplicated. Not to loose attached events, i came up with another (a bit lengthy) solution.

At each "input" event it swiftly attaches "change" events to all involved inputs. It tests if they have been autofilled. If yes, then dispatch a new text event that will trick the browser to think that the value has been changed by the user, thus allowing to remove the yellow background.

var initialFocusedElement = null
  , $inputs = $('input[type="text"]');

var removeAutofillStyle = function() {
  if($(this).is(':-webkit-autofill')) {
    var val = this.value;

    // Remove change event, we won't need it until next "input" event.

    // Dispatch a text event on the input field to trick the browser
    event = document.createEvent('TextEvent');
    event.initTextEvent('textInput', true, true, window, '*');

    // Now the value has an asterisk appended, so restore it to the original
    this.value = val;

    // Always turn focus back to the element that received 
    // input that caused autofill

var onChange = function() {
  // Testing if element has been autofilled doesn't 
  // work directly on change event.
  var self = this;
  setTimeout(function() {;
  }, 1);

$inputs.on('input', function() {
  if(this === document.activeElement) {
    initialFocusedElement = this;

    // Autofilling will cause "change" event to be 
    // fired, so look for it
    $inputs.on('change', onChange);

How do I format a number in Java?

You and String.format() will be new best friends!

 String.format("%.2f", (double)value);

How To Set Text In An EditText

This is the solution in Kotlin

val editText: EditText = findViewById(
    editText.setText("This is a text.")

update query with join on two tables

this is Postgres UPDATE JOIN format:

UPDATE address 
SET cid =
FROM customers 

Here's the other variations:

ORA-01008: not all variables bound. They are bound

The solution in my situation was similar answer to Charles Burns; and the problem was related to SQL code comments.

I was building (or updating, rather) an already-functioning SSRS report with Oracle datasource. I added some more parameters to the report, tested it in Visual Studio, it works great, so I deployed it to the report server, and then when the report is executed the report on the server I got the error message:

"ORA-01008: not all variables bound"

I tried quite a few different things (TNSNames.ora file installed on the server, Removed single line comments, Validate dataset query mapping). What it came down to was I had to remove a comment block directly after the WHERE keyword. The error message was resolved after moving the comment block after the WHERE CLAUSE conditions. I have other comments in the code also. It was just the one after the WHERE keyword causing the error.

SQL with error: "ORA-01008: not all variables bound"...

    OHH.SHIP_DATE BETWEEN TO_DATE('10/1/2018', 'MM/DD/YYYY') AND TO_DATE('10/31/2018', 'MM/DD/YYYY')

    OHH.SHIP_DATE BETWEEN :paramStartDate AND :paramEndDate
    AND OHH.BILL_COMP_CODE IN (:paramCompany)
    AND LOAD.DEPART_FROM_WHSE_CODE IN (:paramWarehouse) 
    AND LOAD.CLASS_CODE IN (:paramClassCode) 
    AND CUST.CUST_CODE || '-' || CUST.CUST_SHIPTO_CODE IN (:paramShipto) 

SQL executes successfully on the report server...

    OHH.SHIP_DATE BETWEEN :paramStartDate AND :paramEndDate
    AND OHH.BILL_COMP_CODE IN (:paramCompany)
    AND LOAD.DEPART_FROM_WHSE_CODE IN (:paramWarehouse) 
    AND LOAD.CLASS_CODE IN (:paramClassCode) 
    AND CUST.CUST_CODE || '-' || CUST.CUST_SHIPTO_CODE IN (:paramShipto)   
    OHH.SHIP_DATE BETWEEN TO_DATE('10/1/2018', 'MM/DD/YYYY') AND TO_DATE('10/31/2018', 'MM/DD/YYYY')

Here is what the dataset parameter mapping screen looks like.

enter image description here

How to start up spring-boot application via command line?

I presume you are trying to compile the application and run it without using an IDE. I also presume you have maven installed and correctly added maven to your environment variable.

To install and add maven to environment variable visit Install maven if you are under a proxy check out add proxy to maven

Navigate to the root of the project via command line and execute the command

mvn spring-boot:run

The CLI will run your application on the configured port and you can access it just like you would if you start the app in an IDE.

Note: This will work only if you have maven added to your pom.xml

Git - Ignore node_modules folder everywhere

Create .gitignore file in root folder directly by code editor or by command

For Mac & Linux

 touch .gitignore 

For Windows

 echo >.gitignore 

open .gitignore declare folder or file name like this /foldername

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

If you are installing first time then please try login with username and password as root

MVC Razor Hidden input and passing values

You are doing it wrong since you try to map WebForms in the MVC application.

There are no server side controlls in MVC. Only the View and the Controller on the back-end. You send the data from server to the client by means of initialization of the View with your model.

This is happening on the HTTP GET request to your resource.

public ActionResult Home() 
  var model = new HomeModel { Greeatings = "Hi" };
  return View(model);

You send data from client to server by means of posting data to server. To make that happen, you create a form inside your view and [HttpPost] handler in your controller.

// View

@using (Html.BeginForm()) {
  @Html.TextBoxFor(m => m.Name)
  @Html.TextBoxFor(m => m.Password)

// Controller

public ActionResult Home(LoginModel model) 
  // do auth.. and stuff
  return Redirect();

include antiforgerytoken in ajax post ASP.NET MVC

it is so simple! when you use @Html.AntiForgeryToken() in your html code it means that server has signed this page and each request that is sent to server from this particular page has a sign that is prevented to send a fake request by hackers. so for this page to be authenticated by the server you should go through two steps:

1.send a parameter named __RequestVerificationToken and to gets its value use codes below:

<script type="text/javascript">
    function gettoken() {
        var token = '@Html.AntiForgeryToken()';
        token = $(token).val();
        return token;

for example take an ajax call

    type: "POST",
    url: "/Account/Login",
    data: {
        __RequestVerificationToken: gettoken(),
        uname: uname,
        pass: pass
    dataType: 'json',
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    success: successFu,

and step 2 just decorate your action method by [ValidateAntiForgeryToken]

Searching if value exists in a list of objects using Linq

Using Linq you have many possibilities, here one without using lambdas:

//assuming list is a List<Customer> or something queryable...
var hasJohn = (from customer in list
         where customer.FirstName == "John"
         select customer).Any();

Change app language programmatically in Android

According to this article. You will need to download referenced in that article.

  1. Create MyApplication class that will extends Application
  2. Override attachBaseContext() to update language.
  3. Register this class in manifest.

    public class MyApplication extends Application {
       protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
  4. Create BaseActivity and override onAttach() to update language. Needed for Android 6+

    public class BaseActivity extends Activity {
      protected void attachBaseContext(Context base) {
  5. Make all activities on your app extends from BaseActivity.

    public class LocaleHelper {
    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";
    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    public static Context setLocale(Context context, String language) {
        persist(context, language);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        return updateResourcesLegacy(context, language);
    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(SELECTED_LANGUAGE, language);
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Configuration configuration = context.getResources().getConfiguration();
        return context.createConfigurationContext(configuration);
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return context;

Reload activity in Android

Start with an intent your same activity and close the activity.

Intent refresh = new Intent(this, Main.class);
startActivity(refresh);//Start the same Activity
finish(); //finish Activity.

How do I change a tab background color when using TabLayout?

You can change the background color of the tab by this attribute


How to determine the version of android SDK installed in computer?

While some responses have shown how to get the versions of the installed Android SDKs and various Android SDK related tools using the Android SDK Manager GUI, here's a way to get the same information from the command line:

%ANDROID_HOME%\tools\bin\sdkmanager.bat --list

You can redirect the output to a file to ease review and sharing.

Note: In my corporate environment, I also had to use the --proxy, --proxy_host, and --proxy_port command line options. You may need to use them as well.

Algorithm to find Largest prime factor of a number

Not the quickest but it works!

    static bool IsPrime(long num)
        long checkUpTo = (long)Math.Ceiling(Math.Sqrt(num));
        for (long i = 2; i <= checkUpTo; i++)
            if (num % i == 0)
                return false;
        return true;

How does one sum only those rows in excel not filtered out?

You need to use the SUBTOTAL function. The SUBTOTAL function ignores rows that have been excluded by a filter.

The formula would look like this:


The function number 9, tells it to use the SUM function on the data range B1:B20.

If you are 'filtering' by hiding rows, the function number should be updated to 109.


The function number 109 is for the SUM function as well, but hidden rows are ignored.

Angular and Typescript: Can't find names - Error: cannot find name

I had the same problem and I solved it using the lib option in tsconfig.json. As said by basarat in his answer, a .d.ts file is implicitly included by TypeScript depending on the compile targetoption but this behaviour can be changed with the lib option.

You can specify additional definition files to be included without changing the targeted JS version. For examples this is part of my current compilerOptions for [email protected] and it adds support for es2015 features without installing anything else:

"compilerOptions": {
    "experimentalDecorators": true,
    "lib": ["es5", "dom", "es6", "dom.iterable", "scripthost"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noLib": false,
    "target": "es5",
    "types": ["node"]

For the complete list of available options check the official doc.

Note also that I added "types": ["node"] and installed npm install @types/node to support require('some-module') in my code.

Loop through all nested dictionary values?

These answers work for only 2 levels of sub-dictionaries. For more try this:

nested_dict = {'dictA': {'key_1': 'value_1', 'key_1A': 'value_1A','key_1Asub1': {'Asub1': 'Asub1_val', 'sub_subA1': {'sub_subA1_key':'sub_subA1_val'}}},
                'dictB': {'key_2': 'value_2'},
                1: {'key_3': 'value_3', 'key_3A': 'value_3A'}}

def print_dict(dictionary):
    dictionary_array = [dictionary]
    for sub_dictionary in dictionary_array:
        if type(sub_dictionary) is dict:
            for key, value in sub_dictionary.items():
                print("key=", key)
                print("value", value)
                if type(value) is dict:


Reload an iframe with jQuery

I'm pretty sure all of the examples above only reload the iframe with its original src, not its current URL.

$('#frameId').attr('src', function () { return $(this).contents().get(0).location.href });

That should reload using the current url.

Git - What is the difference between push.default "matching" and "simple"

git push can push all branches or a single one dependent on this configuration:

Push all branches

git config --global push.default matching

It will push all the branches to the remote branch and would merge them. If you don't want to push all branches, you can push the current branch if you fully specify its name, but this is much is not different from default.

Push only the current branch if its named upstream is identical

git config --global push.default simple

So, it's better, in my opinion, to use this option and push your code branch by branch. It's better to push branches manually and individually.

force line break in html table cell

It's hard to answer you without the HTML, but in general you can put:

style="width: 50%;"

On either the table cell, or place a div inside the table cell, and put the style on that.

But one problem is "50% of what?" It's 50% of the parent element which may not be what you want.

Post a copy of your HTML and maybe you'll get a better answer.

How to implement a property in an interface

The simple example of using a property in an interface:

using System;
interface IName
    string Name { get; set; }

class Employee : IName
    public string Name { get; set; }

class Company : IName
    private string _company { get; set; }
    public string Name
            return _company;
            _company = value;

class Client
    static void Main(string[] args)
        IName e = new Employee();
        e.Name = "Tim Bridges";

        IName c = new Company();
        c.Name = "Inforsoft";

        Console.WriteLine("{0} from {1}.", e.Name, c.Name);
 Tim Bridges from Inforsoft.

SQL Order By Count

Try using below Query:

    COUNT(*) AS Total_Count
    Total_Count DESC

How to create helper file full of functions in react native?

Quick note: You are importing a class, you can't call properties on a class unless they are static properties. Read more about classes here:

There's an easy way to do this, though. If you are making helper functions, you should instead make a file that exports functions like this:

export function HelloChandu() {


export function HelloTester() {


Then import them like so:

import { HelloChandu } from './helpers'


import functions from './helpers' then functions.HelloChandu

Java 8 stream's .min() and .max(): why does this compile?

Apart from the information given by David M. Lloyd one could add that the mechanism that allows this is called target typing.

The idea is that the type the compiler assigns to a lambda expressions or a method references does not depend only on the expression itself, but also on where it is used.

The target of an expression is the variable to which its result is assigned or the parameter to which its result is passed.

Lambda expressions and method references are assigned a type which matches the type of their target, if such a type can be found.

See the Type Inference section in the Java Tutorial for more information.

The opposite of Intersect()

This code enumerates each sequence only once and uses Select(x => x) to hide the result to get a clean Linq-style extension method. Since it uses HashSet<T> its runtime is O(n + m) if the hashes are well distributed. Duplicate elements in either list are omitted.

public static IEnumerable<T> SymmetricExcept<T>(this IEnumerable<T> seq1,
    IEnumerable<T> seq2)
    HashSet<T> hashSet = new HashSet<T>(seq1);
    return hashSet.Select(x => x);

How do Python functions handle the types of the parameters that you pass in?

Python is strongly typed because every object has a type, every object knows its type, it's impossible to accidentally or deliberately use an object of a type "as if" it was an object of a different type, and all elementary operations on the object are delegated to its type.

This has nothing to do with names. A name in Python doesn't "have a type": if and when a name's defined, the name refers to an object, and the object does have a type (but that doesn't in fact force a type on the name: a name is a name).

A name in Python can perfectly well refer to different objects at different times (as in most programming languages, though not all) -- and there is no constraint on the name such that, if it has once referred to an object of type X, it's then forevermore constrained to refer only to other objects of type X. Constraints on names are not part of the concept of "strong typing", though some enthusiasts of static typing (where names do get constrained, and in a static, AKA compile-time, fashion, too) do misuse the term this way.

ab load testing

The apache benchmark tool is very basic, and while it will give you a solid idea of some performance, it is a bad idea to only depend on it if you plan to have your site exposed to serious stress in production.

Having said that, here's the most common and simplest parameters:

-c: ("Concurrency"). Indicates how many clients (people/users) will be hitting the site at the same time. While ab runs, there will be -c clients hitting the site. This is what actually decides the amount of stress your site will suffer during the benchmark.

-n: Indicates how many requests are going to be made. This just decides the length of the benchmark. A high -n value with a -c value that your server can support is a good idea to ensure that things don't break under sustained stress: it's not the same to support stress for 5 seconds than for 5 hours.

-k: This does the "KeepAlive" funcionality browsers do by nature. You don't need to pass a value for -k as it it "boolean" (meaning: it indicates that you desire for your test to use the Keep Alive header from HTTP and sustain the connection). Since browsers do this and you're likely to want to simulate the stress and flow that your site will have from browsers, it is recommended you do a benchmark with this.

The final argument is simply the host. By default it will hit http:// protocol if you don't specify it.

ab -k -c 350 -n 20000

By issuing the command above, you will be hitting with 350 simultaneous connections until 20 thousand requests are met. It will be done using the keep alive header.

After the process finishes the 20 thousand requests, you will receive feedback on stats. This will tell you how well the site performed under the stress you put it when using the parameters above.

For finding out how many people the site can handle at the same time, just see if the response times (means, min and max response times, failed requests, etc) are numbers your site can accept (different sites might desire different speeds). You can run the tool with different -c values until you hit the spot where you say "If I increase it, it starts to get failed requests and it breaks".

Depending on your website, you will expect an average number of requests per minute. This varies so much, you won't be able to simulate this with ab. However, think about it this way: If your average user will be hitting 5 requests per minute and the average response time that you find valid is 2 seconds, that means that 10 seconds out of a minute 1 user will be on requests, meaning only 1/6 of the time it will be hitting the site. This also means that if you have 6 users hitting the site with ab simultaneously, you are likely to have 36 users in simulation, even though your concurrency level (-c) is only 6.

This depends on the behavior you expect from your users using the site, but you can get it from "I expect my user to hit X requests per minute and I consider an average response time valid if it is 2 seconds". Then just modify your -c level until you are hitting 2 seconds of average response time (but make sure the max response time and stddev is still valid) and see how big you can make -c.

I hope I explained this clear :) Good luck

Code for a simple JavaScript countdown timer?

Expanding upon the accepted answer, your machine going to sleep, etc. may delay the timer from working. You can get a true time, at the cost of a little processing. This will give a true time left.

<span id="timer"></span>

var now = new Date();
var timeup = now.setSeconds(now.getSeconds() + 30);
//var timeup = now.setHours(now.getHours() + 1);

var counter = setInterval(timer, 1000);

function timer() {
  now = new Date();
  count = Math.round((timeup - now)/1000);
  if (now > timeup) {
      window.location = "/logout"; //or somethin'
  var seconds = Math.floor((count%60));
  var minutes = Math.floor((count/60) % 60);
  document.getElementById("timer").innerHTML = minutes + ":" + seconds;

Angular 4: How to include Bootstrap?

Watch Video or Follow the step

Install bootstrap 4 in angular 2 / angular 4 / angular 5 / angular 6

There is three way to include bootstrap in your project
1) Add CDN Link in index.html file
2) Install bootstrap using npm and set path in angular.json Recommended
3) Install bootstrap using npm and set path in index.html file

I recommended you following 2 methods that are installed bootstrap using npm because its installed in your project directory and you can easily access it

Method 1

Add Bootstrap, Jquery and popper.js CDN path to you angular project index.html file


Method 2

1) Install bootstrap using npm

npm install bootstrap --save

after the installation of Bootstrap 4, we Need two More javascript Package that is Jquery and Popper.js without these two package bootstrap is not complete because Bootstrap 4 is using Jquery and popper.js package so we have to install as well

2) Install JQUERY

npm install jquery --save

3) Install Popper.js

npm install popper.js --save

Now Bootstrap is Install on you Project Directory inside node_modules Folder

open angular.json this file are available on you angular directory open that file and add the path of bootstrap, jquery, and popper.js files inside styles[] and scripts[] path see the below example

"styles": [   
  "scripts": [  

Note: Don't change a sequence of js file it should be like this

Method 3

Install bootstrap using npm follow Method 2 in method 3 we just set path inside index.html file instead of angular.json file


    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css",


<script src="node_modules/jquery/dist/jquery.min.js"><br>


<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"><br>


<script src="node_modules/popper.js/dist/umd/popper.min.js"><br>

Now Bootstrap Working fine Now

How do getters and setters work?

class Clock {  
        String time;  

        void setTime (String t) {  
           time = t;  

        String getTime() {  
           return time;  

class ClockTestDrive {  
   public static void main (String [] args) {  
   Clock c = new Clock;  

   String tod = c.getTime();  
   System.out.println(time: " + tod);  

When you run the program, program starts in mains,

  1. object c is created
  2. function setTime() is called by the object c
  3. the variable time is set to the value passed by
  4. function getTime() is called by object c
  5. the time is returned
  6. It will passe to tod and tod get printed out

Android Studio - Failed to notify project evaluation listener error

Just restart Android Studio - Usually then everything works again. (Invalidate Caches + Restart is actually not required).

Calling JMX MBean method from a shell script

You might want also to have a look at jmx4perl. It provides java-less access to a remote Java EE Server's MBeans. However, a small agent servlet needs to be installed on the target platform, which provides a restful JMX Access via HTTP with a JSON payload. (Version 0.50 will add an agentless mode by implementing a JSR-160 proxy).

Advantages are quick startup times compared to launching a local java JVM and ease of use. jmx4perl comes with a full set of Perl modules which can be easily used in your own scripts:

use JMX::Jmx4Perl;
use JMX::Jmx4Perl::Alias;   # Import certains aliases for MBeans

print "Memory Used: ",
          ->new(url => "http://localhost:8080/j4p")

You can also use alias for common MBean/Attribute/Operation combos (e.g. for most MXBeans). For additional features (Nagios-Plugin, XPath-like access to complex attribute types, ...), please refer to the documentation of jmx4perl.

convert date string to mysql datetime field

I assume we are talking about doing this in Bash?

I like to use sed to load the date values into an array so I can break down each field and do whatever I want with it. The following example assumes and input format of mm/dd/yyyy...

DATE_ARRAY=(`echo $DATE | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)

you also may want to read up on the date command in linux. It can be very useful:

Hope that helps... :)


Reflection - get attribute name and value on property

Use typeof(Book).GetProperties() to get an array of PropertyInfo instances. Then use GetCustomAttributes() on each PropertyInfo to see if any of them have the Author Attribute type. If they do, you can get the name of the property from the property info and the attribute values from the attribute.

Something along these lines to scan a type for properties that have a specific attribute type and to return data in a dictionary (note that this can be made more dynamic by passing types into the routine):

public static Dictionary<string, string> GetAuthors()
    Dictionary<string, string> _dict = new Dictionary<string, string>();

    PropertyInfo[] props = typeof(Book).GetProperties();
    foreach (PropertyInfo prop in props)
        object[] attrs = prop.GetCustomAttributes(true);
        foreach (object attr in attrs)
            AuthorAttribute authAttr = attr as AuthorAttribute;
            if (authAttr != null)
                string propName = prop.Name;
                string auth = authAttr.Name;

                _dict.Add(propName, auth);

    return _dict;

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

if you are using XDocument.Load(url); to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException

See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
        base.processOperator(operations, arguments);

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

simplest method is just the copy the text that you want to paste it in cmd and open cmd goto "properties"---> "option" tab----> check the (give tick mark) "quickEdit mode" and click "ok" you can paste any text from clipboard by doing right click from ur mouse.

Thank you..

How to concatenate multiple column values into a single column in Panda dataframe

df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3], 'new':['apple', 'banana', 'pear']})

df['combined'] = df['foo'].astype(str)+'_'+df['bar'].astype(str)

If you concatenate with string('_') please you convert the column to string which you want and after you can concatenate the dataframe.

Resizing an iframe based on content

Work with jquery on load (cross browser):

 <iframe src="your_url" marginwidth="0"  marginheight="0" scrolling="No" frameborder="0"  hspace="0" vspace="0" id="containiframe" onload="loaderIframe();" height="100%"  width="100%"></iframe>

function loaderIframe(){
var heightIframe = $('#containiframe').contents().find('body').height();
$('#frame').css("height", heightFrame);

on resize in responsive page:

if($('#containiframe').length !== 0) {
var heightIframe = $('#containiframe').contents().find('body').height();
 $('#frame').css("height", heightFrame);

What is __gxx_personality_v0 for?

It's part of the exception handling. The gcc EH mechanism allows to mix various EH models, and a personality routine is invoked to determine if an exception match, what finalization to invoke, etc. This specific personality routine is for C++ exception handling (as opposed to, say, gcj/Java exception handling).

Make just one slide different size in Powerpoint

You can't. You can only have one slide size and one orientation per presentation.

Are you projecting the presentation or delivering it on a laptop? If so, the size is sort of irrelevant.
Regardless of the slide size, the projected/displayed image will never be longer or wider than the projector/display accepts.

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

Use an online service like Image Baker.

image baker

It's simple. Upload the images and download processed assets for both Android and iOS.

Downloaded images

Note: Image Baker is a free service created by my friend and myself.

Replace string within file contents

Using pathlib (

from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))

If input and output files were different you would use two different variables for read_text and write_text.

If you wanted a change more complex than a single replacement, you would assign the result of read_text to a variable, process it and save the new content to another variable, and then save the new content with write_text.

If your file was large you would prefer an approach that does not read the whole file in memory, but rather process it line by line as show by Gareth Davidson in another answer (, which of course requires to use two distinct files for input and output.

Importing CommonCrypto in a Swift framework

Good news! Swift 4.2 (Xcode 10) finally provides CommonCrypto!

Just add import CommonCrypto in your swift file.

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:


So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"";

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

WordPress path url in js script file

For users working with the Genesis framework.

Add the following to your child theme functions.php

add_action( 'genesis_before', 'script_urls' );

function script_urls() {
    <script type="text/javascript">
     var stylesheetDir = '<?= get_bloginfo("stylesheet_directory"); ?>';

And use that variable to set the relative url in your script. For example: = " url('"+stylesheetDir+"/images/searchfield_clear.png') ";

Background blur with CSS

Use an empty element sized for the content as the background, and position the content over the blurred element.


  position: absolute;
  top: 40%;
  left: 50%;
  z-index: 50;
  margin-left: -200px;
  height: 200px;
  width: 400px;


  background: transparent;
  position: absolute;
  top: 40%;
  left: 50%;
  margin-left -200px;
  overflow: hidden;
  z-index: 51;

The background element can be inside of the content element, but not the other way around.

<div id='dialog_base'></div>
<div id='dialog_content'>
    Some Content
    <!-- Alternatively with z-index: <div id='dialog_base'></div> -->

This is not easy if the content is not always consistently sized, but it works.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

You need to decode data from input string into unicode, before using it, to avoid encoding problems.

field.text = data.decode("utf8")