Programs & Examples On #Html input

The input element represents a typed data field, usually with a form control to allow the user to edit the data.

How to force keyboard with numbers in mobile website in Android

<input type="number" />
<input type="tel" />

Both of these present the numeric keypad when the input gains focus.

<input type="search" /> shows a normal keyboard with an extra search button

Everything else seems to bring up the standard keyboard.

Html/PHP - Form - Input as array

HTML: Use names as

<input name="levels[level][]">
<input name="levels[build_time][]">

PHP:

$array = filter_input_array(INPUT_POST);
$newArray = array();
foreach (array_keys($array) as $fieldKey) {
    foreach ($array[$fieldKey] as $key=>$value) {
        $newArray[$key][$fieldKey] = $value;
    }
}  

$newArray will hold data as you want

Array ( 
  [0] => Array ( [level] => 1 [build_time] => 123 ) 
  [1] => Array ( [level] => 2 [build_time] => 456 )
)

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

"agree,false"

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

"false"

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

Change a HTML5 input's placeholder color with CSS

In Firefox and Internet Explorer, the normal input text color overrides the color property of placeholders. So, we need to

::-webkit-input-placeholder { 
    color: red; text-overflow: ellipsis; 
}
:-moz-placeholder { 
    color: #acacac !important; text-overflow: ellipsis; 
}
::-moz-placeholder { 
    color: #acacac !important; text-overflow: ellipsis; 
} /* For the future */
:-ms-input-placeholder { 
    color: #acacac !important; text-overflow: ellipsis; 
}

Using Pipes within ngModel on INPUT Elements in Angular

You can't use Template expression operators(pipe, save navigator) within template statement:

(ngModelChange)="Template statements"

(ngModelChange)="item.value | useMyPipeToFormatThatValue=$event"

https://angular.io/guide/template-syntax#template-statements

Like template expressions, template statements use a language that looks like JavaScript. The template statement parser differs from the template expression parser and specifically supports both basic assignment (=) and chaining expressions (with ; or ,).

However, certain JavaScript syntax is not allowed:

  • new
  • increment and decrement operators, ++ and --
  • operator assignment, such as += and -=
  • the bitwise operators | and &
  • the template expression operators

So you should write it as follows:

<input [ngModel]="item.value | useMyPipeToFormatThatValue" 
      (ngModelChange)="item.value=$event" name="inputField" type="text" />

Plunker Example

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

<input type='button' onclick='buttonClick()' />

<script>
function buttonClick(){
    //Validate Here
    document.getElementsByTagName('form')[0].submit();
}
</script>

<button> vs. <input type="button" />. Which to use?

  • Here's a page describing the differences (basically you can put html into a <button></button>)
  • And another page describing why people avoid <button></button> (Hint: IE6)

Another IE problem when using <button />:

And while we're talking about IE, it's got a couple of bugs related to the width of buttons. It'll mysteriously add extra padding when you're trying to add styles, meaning you have to add a tiny hack to get things under control.

change type of input field with jQuery

Try this
Demo is here

$(document).delegate('input[type="text"]','click', function() {
    $(this).replaceWith('<input type="password" value="'+this.value+'" id="'+this.id+'">');
}); 
$(document).delegate('input[type="password"]','click', function() {
    $(this).replaceWith('<input type="text" value="'+this.value+'" id="'+this.id+'">');
}); 

How do I get the value of text input field using JavaScript?

simple js

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}

How to add button inside input

I found a great code for you:

HTML

<form class="form-wrapper cf">
    <input type="text" placeholder="Search here..." required>
    <button type="submit">Search</button>
</form>

CSS

/*Clearing Floats*/
.cf:before, .cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

.cf {
    zoom:1;
}    
/* Form wrapper styling */
.form-wrapper {
    width: 450px;
    padding: 15px;
    margin: 150px auto 50px auto;
    background: #444;
    background: rgba(0,0,0,.2);
    border-radius: 10px;
    box-shadow: 0 1px 1px rgba(0,0,0,.4) inset, 0 1px 0 rgba(255,255,255,.2);
}

/* Form text input */

.form-wrapper input {
    width: 330px;
    height: 20px;
    padding: 10px 5px;
    float: left;   
    font: bold 15px 'lucida sans', 'trebuchet MS', 'Tahoma';
    border: 0;
    background: #eee;
    border-radius: 3px 0 0 3px;     
}

.form-wrapper input:focus {
    outline: 0;
    background: #fff;
    box-shadow: 0 0 2px rgba(0,0,0,.8) inset;
}

.form-wrapper input::-webkit-input-placeholder {
   color: #999;
   font-weight: normal;
   font-style: italic;
}

.form-wrapper input:-moz-placeholder {
    color: #999;
    font-weight: normal;
    font-style: italic;
}

.form-wrapper input:-ms-input-placeholder {
    color: #999;
    font-weight: normal;
    font-style: italic;
}   

/* Form submit button */
.form-wrapper button {
    overflow: visible;
    position: relative;
    float: right;
    border: 0;
    padding: 0;
    cursor: pointer;
    height: 40px;
    width: 110px;
    font: bold 15px/40px 'lucida sans', 'trebuchet MS', 'Tahoma';
    color: #fff;
    text-transform: uppercase;
    background: #d83c3c;
    border-radius: 0 3px 3px 0;     
    text-shadow: 0 -1px 0 rgba(0, 0 ,0, .3);
}  

.form-wrapper button:hover {    
    background: #e54040;
}  

.form-wrapper button:active,
.form-wrapper button:focus {  
    background: #c42f2f;
    outline: 0;  
}

.form-wrapper button:before { /* left arrow */
    content: '';
    position: absolute;
    border-width: 8px 8px 8px 0;
    border-style: solid solid solid none;
    border-color: transparent #d83c3c transparent;
    top: 12px;
    left: -6px;
}

.form-wrapper button:hover:before {
    border-right-color: #e54040;
}

.form-wrapper button:focus:before,
.form-wrapper button:active:before {
        border-right-color: #c42f2f;
}     

.form-wrapper button::-moz-focus-inner { /* remove extra button spacing for Mozilla Firefox */
    border: 0;
    padding: 0;
}    

Demo: On fiddle Source: Speckyboy

Get data from file input in JQuery

input element, of type file

<input id="fileInput" type="file" />

On your input change use the FileReader object and read your input file property:

$('#fileInput').on('change', function () {
    var fileReader = new FileReader();
    fileReader.onload = function () {
      var data = fileReader.result;  // data <-- in this var you have the file data in Base64 format
    };
    fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});

FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)

HTML5 Email input pattern attribute

Unfortunately, all suggestions except from B-Money are invalid for most cases.

Here is a lot of valid emails like:

Because of complexity to get validation right, I propose a very generic solution:

<input type="text" pattern="[^@\s]+@[^@\s]+\.[^@\s]+" title="Invalid email address" />

It checks if email contains at least one character (also number or whatever except another "@" or whitespace) before "@", at least two characters (or whatever except another "@" or whitespace) after "@" and one dot in between. This pattern does not accept addresses like lol@company, sometimes used in internal networks. But this one could be used, if required:

<input type="text" pattern="[^@\s]+@[^@\s]+" title="Invalid email address" />

Both patterns accepts also less valid emails, for example emails with vertical tab. But for me it's good enough. Stronger checks like trying to connect to mail-server or ping domain should happen anyway on the server side.

BTW, I just wrote angular directive (not well tested yet) for email validation with novalidate and without based on pattern above to support DRY-principle:

.directive('isEmail', ['$compile', '$q', 't', function($compile, $q, t) {
    var EMAIL_PATTERN = '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$';
    var EMAIL_REGEXP = new RegExp(EMAIL_PATTERN, 'i');
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModel){
            function validate(value) {
                var valid = angular.isUndefined(value)
                    || value.length === 0
                    || EMAIL_REGEXP.test(value);
                ngModel.$setValidity('email', valid);
                return valid ? value : undefined;
            }
            ngModel.$formatters.unshift(validate);
            ngModel.$parsers.unshift(validate);
            elem.attr('pattern', EMAIL_PATTERN);
            elem.attr('title', 'Invalid email address');
        }
    };
}])

Usage:

<input type="text" is-email />

For B-Money's pattern is "@" just enough. But it decline two or more "@" and all spaces.

How do I make a text input non-editable?

Add readonly:

<input type="text" value="3" class="field left" readonly>

If you want the value to be not submitted in a form, instead add the disabled attribute.

<input type="text" value="3" class="field left" disabled>

There is no way to use CSS that always works to do this.

Why? CSS can't "disable" anything. You can still turn off display or visibility and use pointer-events: none but pointer-events doesn't work on versions of IE that came out earlier than IE 11.

How to set default value to the input[type="date"]

A possible solution:

document.getElementById("yourDatePicker").valueAsDate = new Date();

Using Moment.js:

var today = moment().format('YYYY-MM-DD');
document.getElementById("datePicker").value = today;

input checkbox true or checked or yes

Accordingly to W3C checked input's attribute can be absent/ommited or have "checked" as its value. This does not invalidate other values because there's no restriction to the browser implementation to allow values like "true", "on", "yes" and so on. To guarantee that you'll write a cross-browser checkbox/radio use checked="checked", as recommended by W3C.

disabled, readonly and ismap input's attributes go on the same way.

EDITED

empty is not a valid value for checked, disabled, readonly and ismap input's attributes, as warned by @Quentin

Input type DateTime - Value format?

This article seems to show the valid types that are acceptable

<time>2009-11-13</time>
 <!-- without @datetime content must be a valid date, time, or precise datetime -->
<time datetime="2009-11-13">13<sup>th</sup> November</time>
 <!-- when using @datetime the content can be anything relevant -->
<time datetime="20:00">starting at 8pm</time>
 <!-- time example -->
<time datetime="2009-11-13T20:00+00:00">8pm on my birthday</time>
 <!-- datetime with time-zone example -->
<time datetime="2009-11-13T20:00Z">8pm on my birthday</time>
 <!-- datetime with time-zone “Z” -->

This one covers using it in the <input> field:

<input type="date" name="d" min="2011-08-01" max="2011-08-15"> This example of the HTML5 input type "date" combine with the attributes min and max shows how we can restrict the dates a user can input. The attributes min and max are not dependent on each other and can be used independently.

<input type="time" name="t" value="12:00"> The HTML5 input type "time" allows users to choose a corresponding time that is displayed in a 24hour format. If we did not include the default value of "12:00" the time would set itself to the time of the users local machine.

<input type="week" name="w"> The HTML5 Input type week will display the numerical version of the week denoted by a "W" along with the corresponding year.

<input type="month" name="m"> The HTML5 input type month does exactly what you might expect it to do. It displays the month. To be precise it displays the numerical version of the month along with the year.

<input type="datetime" name="dt"> The HTML5 input type Datetime displays the UTC date and time code. User can change the the time steps forward or backward in one minute increments. If you wish to display the local date and time of the user you will need to use the next example datetime-local

<input type="datetime-local" name="dtl" step="7200"> Because datetime steps through one minute at a time, you may want to change the default increment by using the attribute "step". In the following example we will have it increment by two hours by setting the attribute step to 7200 (60seconds X 60 minutes X 2).

Drop Down Menu/Text Field in one

I like jQuery Token input. Actually prefer the UI over some of the other options mentioned above.

http://loopj.com/jquery-tokeninput/

Also see: http://railscasts.com/episodes/258-token-fields for an explanation

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

CSS selector for text input fields?

With attribute selector we target input type text in CSS

input[type=text] {
background:gold;
font-size:15px;
 }

Phone: numeric keyboard for text input

You can do <input type="text" pattern="\d*">. This will cause the numeric keyboard to appear.

See here for more detail: Text, Web, and Editing Programming Guide for iOS

_x000D_
_x000D_
<form>_x000D_
  <input type="text" pattern="\d*">_x000D_
  <button type="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Best way to remove an event handler in jQuery?

jQuery = 1.7

With jQuery 1.7 onward the event API has been updated, .bind()/.unbind() are still available for backwards compatibility, but the preferred method is using the on()/off() functions. The below would now be,

$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');

jQuery < 1.7

In your example code you are simply adding another click event to the image, not overriding the previous one:

$('#myimage').click(function() { return false; }); // Adds another click event

Both click events will then get fired.

As people have said you can use unbind to remove all click events:

$('#myimage').unbind('click');

If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing:

$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ });

and to remove just your event:

$('#myimage').unbind('click.mynamespace');

Get the value in an input text box

For those who just like me are newbies in JS and getting undefined instead of text value make sure that your id doesn't contain invalid characters.

Set the value of an input field

Try out these.

document.getElementById("current").value = 12

// or

var current = document.getElementById("current");
current.value = 12

How to align texts inside of an input?

If you want to get it aligned to the right after the text looses focus you can try to use the direction modifier. This will show the right part of the text after loosing focus. e.g. useful if you want to show the file name in a large path.

_x000D_
_x000D_
input.rightAligned {_x000D_
  direction:ltr;_x000D_
  overflow:hidden;_x000D_
}_x000D_
input.rightAligned:not(:focus) {_x000D_
  direction:rtl;_x000D_
  text-align: left;_x000D_
  unicode-bidi: plaintext;_x000D_
  text-overflow: ellipsis;_x000D_
}
_x000D_
<form>_x000D_
    <input type="text" class="rightAligned" name="name" value="">_x000D_
</form>
_x000D_
_x000D_
_x000D_

The not selector is currently well supported : Browser support

Disable/enable an input with jQuery?

You can put this somewhere global in your code:

$.prototype.enable = function () {
    $.each(this, function (index, el) {
        $(el).removeAttr('disabled');
    });
}

$.prototype.disable = function () {
    $.each(this, function (index, el) {
        $(el).attr('disabled', 'disabled');
    });
}

And then you can write stuff like:

$(".myInputs").enable();
$("#otherInput").disable();

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

I think this may help:


First read all the specs from Microsoft and W3.org.
You'd see that the setting the actual element of a checkbox needs to be done on the ELEMENT PROPERTY, not the UI or attribute.
$('mycheckbox')[0].checked

Secondly, you need to be aware that the checked attribute RETURNS a string "true", "false"
Why is this important? Because you need to use the correct Type. A string, not a boolean. This also important when parsing your checkbox.
$('mycheckbox')[0].checked = "true"

if($('mycheckbox')[0].checked === "true"){ //do something }

You also need to realize that the "checked" ATTRIBUTE is for setting the value of the checkbox initially. This doesn't do much once the element is rendered to the DOM. Picture this working when the webpage loads and is initially parsed.
I'll go with IE's preference on this one: <input type="checkbox" checked="checked"/>

Lastly, the main aspect of confusion for a checkbox is that the checkbox UI element is not the same as the element's property value. They do not correlate directly. If you work in .net, you'll discover that the user "checking" a checkbox never reflects the actual bool value passed to the controller. To set the UI, I use both $('mycheckbox').val(true); and $('mycheckbox').attr('checked', 'checked');


In short, for a checked checkbox you need:
Initial DOM: <input type="checkbox" checked="checked">
Element Property: $('mycheckbox')[0].checked = "true";
UI: $('mycheckbox').val(true); and $('mycheckbox').attr('checked', 'checked');

Disable Auto Zoom in Input "Text" tag - Safari on iPhone

Even with these answers it took me three days to figure out what was going on and I may need the solution again in the future.

My situation was slightly different from the one described.

In mine, I had some contenteditable text in a div on the page. When the user clicked on a DIFFERENT div, a button of sorts, I automatically selected some text in the contenteditable div (a selection range that had previously been saved and cleared), ran a rich text execCommand on that selection, and cleared it again.

This enabled me to invisibly change text colors based on user interactions with color divs elsewhere on the page, while keeping the selection normally hidden to let them see the colors in the proper context.

Well, on iPad's Safari, clicking the color div resulted in the on-screen keyboard coming up, and nothing I did would prevent it.

I finally figured out how the iPad's doing this.

It listens for a touchstart and touchend sequence that triggers a selection of editable text.

When that combination happens, it shows the on-screen keyboard.

Actually, it does a dolly zoom where it expands the underlying page while zooming in on the editable text. It took me a day just to understand what I was seeing.

So the solution I used was to intercept both touchstart and touchend on those particular color divs. In both handlers I stop propagation and bubbling and return false. But in the touchend event I trigger the same behavior that click triggered.

So, before, Safari was triggering what I think was "touchstart", "mousedown", "touchend", "mouseup", "click", and because of my code, a text selection, in that order.

The new sequence because of the intercepts is simply the text selection. Everything else gets intercepted before Safari can process it and do its keyboard stuff. The touchstart and touchend intercepts prevent the mouse events from triggering as well, and in context this is totally fine.

I don't know an easier way to describe this but I think it's important to have it here because I found this thread within an hour of first encountering the issue.

I'm 98% sure the same fix will work with input boxes and anything else. Intercept the touch events and process them separately without letting them propagate or bubble, and consider doing any selections after a tiny timeout just to make sure Safari doesn't recognize the sequence as the keyboard trigger.

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="0.01" /> if you are targeting 2 decimal places :-).

How to handle floats and decimal separators with html5 input type number

When you call $("#my_input").val(); it returns as string variable. So use parseFloat and parseIntfor converting. When you use parseFloat your desktop or phone ITSELF understands the meaning of variable.

And plus you can convert a float to string by using toFixed which has an argument the count of digits as below:

var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01

HTML input - name vs. id

The id is used to uniquely identify an element in JavaScript or CSS.

The name is used in form submission. When you submit a form only the fields with a name will be submitted.

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

Try to use:

pattern="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}"

How to pass optional parameters while omitting some other optional parameters?

You can specify multiple method signatures on the interface then have multiple method overloads on the class method:

interface INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
    error(message: string, autoHideAfter: number);
}

class MyNotificationService implements INotificationService {
    error(message: string, title?: string, autoHideAfter?: number);
    error(message: string, autoHideAfter?: number);
    error(message: string, param1?: (string|number), param2?: number) {
        var autoHideAfter: number,
            title: string;

        // example of mapping the parameters
        if (param2 != null) {
            autoHideAfter = param2;
            title = <string> param1;
        }
        else if (param1 != null) {
            if (typeof param1 === "string") {
                title = param1;
            }
            else {
                autoHideAfter = param1;
            }
        }

        // use message, autoHideAfter, and title here
    }
}

Now all these will work:

var service: INotificationService = new MyNotificationService();
service.error("My message");
service.error("My message", 1000);
service.error("My message", "My title");
service.error("My message", "My title", 1000);

...and the error method of INotificationService will have the following options:

Overload intellisense

Playground

Close Bootstrap modal on form submit

You can use one of this two options:

1) Add data-dismiss to the submit button i.e.

<button type="submit" class="btn btn-success" data-dismiss="modal"><i class="glyphicon glyphicon-ok"></i> Save</button>

2) Do it in JS like

$('#frmStudent').submit(function() {
    $('#StudentModal').modal('hide');
});

What are the true benefits of ExpandoObject?

Interop with other languages founded on the DLR is #1 reason I can think of. You can't pass them a Dictionary<string, object> as it's not an IDynamicMetaObjectProvider. Another added benefit is that it implements INotifyPropertyChanged which means in the databinding world of WPF it also has added benefits beyond what Dictionary<K,V> can provide you.

Input jQuery get old value before onchange and get value after on change

The simplest way is to save the original value using data() when the element gets focus. Here is a really basic example:

JSFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/

$('input').on('focusin', function(){
    console.log("Saving value " + $(this).val());
    $(this).data('val', $(this).val());
});

$('input').on('change', function(){
    var prev = $(this).data('val');
    var current = $(this).val();
    console.log("Prev value " + prev);
    console.log("New value " + current);
});

Better to use Delegated Event Handlers

Note: it is generally more efficient to use a delegated event handler when there can be multiple matching elements. This way only a single handler is added (smaller overhead and faster initialisation) and any speed difference at event time is negligible.

Here is the same example using delegated events connected to document:

$(document).on('focusin', 'input', function(){
    console.log("Saving value " + $(this).val());
    $(this).data('val', $(this).val());
}).on('change','input', function(){
    var prev = $(this).data('val');
    var current = $(this).val();
    console.log("Prev value " + prev);
    console.log("New value " + current);
});

JsFiddle: http://jsfiddle.net/TrueBlueAussie/e4ovx435/65/

Delegated events work by listening for an event (focusin, change etc) on an ancestor element (document* in this case), then applying the jQuery filter (input) to only the elements in the bubble chain then applying the function to only those matching elements that caused the event.

*Note: A a general rule, use document as the default for delegated events and not body. body has a bug, to do with styling, that can cause it to not get bubbled mouse events. Also document always exists so you can attach to it outside of a DOM ready handler :)

Property [title] does not exist on this collection instance

When you're using get() you get a collection. In this case you need to iterate over it to get properties:

@foreach ($collection as $object)
    {{ $object->title }}
@endforeach

Or you could just get one of objects by it's index:

{{ $collection[0]->title }}

Or get first object from collection:

{{ $collection->first() }}

When you're using find() or first() you get an object, so you can get properties with simple:

{{ $object->title }}

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

document.getElementById("test").style.display="hidden" not working

Set CSS display property to none.

document.getElementById("test").style.display = "none";

Also, you do not need javascript: for the onclick attribute.

<input type="image" src="../images/btnFind.png" id="find" name="find" 
    onclick="hide();" />

Finally, make sure you do not have multiple elements with the same ID.

If your form goes nowhere, Phil suggested that you should prevent submission of the form. Simply return false in the onsubmit handler.

<form method="post" id="test" onsubmit="return false;">

If you want the form to post, but hide the div on subsequent page load, you will have to use server-side code to hide the element:

<script type="text/javascript">
function hide() {
    document.getElementById("test").style.display = "none";
}
window.onload = function() {
    // if form was submitted, PHP will print the below, 
    //    which runs function hide() on page load
    <?= ($_POST['ampid'] != '') ? 'hide();' : '' ?>
}
</script>

How do I replace a character in a string in Java?

//I think this will work, you don't have to replace on the even, it's just an example. 

 public void emphasize(String phrase, char ch)
    {
        char phraseArray[] = phrase.toCharArray(); 
        for(int i=0; i< phrase.length(); i++)
        {
            if(i%2==0)// even number
            {
                String value = Character.toString(phraseArray[i]); 
                value = value.replace(value,"*"); 
                phraseArray[i] = value.charAt(0);
            }
        }
    }

PHP form send email to multiple recipients

You can add your receipients to $email_to variable separating them with comma (,). Or you can add new fields to headers, namely CC: or BCC: and put your receipients there. BCC is most recommended

Most Useful Attributes

I always use the DisplayName, Description and DefaultValue attributes over public properties of my user controls, custom controls or any class I'll edit through a property grid. These tags are used by the .NET PropertyGrid to format the name, the description panel, and bolds values that are not set to the default values.

[DisplayName("Error color")]
[Description("The color used on nodes containing errors.")]
[DefaultValue(Color.Red)]
public Color ErrorColor
{
    ...
} 

I just wish Visual Studio's IntelliSense would take the Description attribute into account if no XML comment are found. It would avoid having to repeat the same sentence twice.

Android Error - Open Failed ENOENT

With sdk, you can't write to the root of internal storage. This cause your error.

Edit :

Based on your code, to use internal storage with sdk:

final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");

Add new row to dataframe, at specific row-index, not appended?

for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this

allEdges <- data.frame(c(edges$V1,edges$V2))

What's wrong with using == to compare floats in Java?

Just to give the reason behind what everyone else is saying.

The binary representation of a float is kind of annoying.

In binary, most programmers know the correlation between 1b=1d, 10b=2d, 100b=4d, 1000b=8d

Well it works the other way too.

.1b=.5d, .01b=.25d, .001b=.125, ...

The problem is that there is no exact way to represent most decimal numbers like .1, .2, .3, etc. All you can do is approximate in binary. The system does a little fudge-rounding when the numbers print so that it displays .1 instead of .10000000000001 or .999999999999 (which are probably just as close to the stored representation as .1 is)

Edit from comment: The reason this is a problem is our expectations. We fully expect 2/3 to be fudged at some point when we convert it to decimal, either .7 or .67 or .666667.. But we don't automatically expect .1 to be rounded in the same way as 2/3--and that's exactly what's happening.

By the way, if you are curious the number it stores internally is a pure binary representation using a binary "Scientific Notation". So if you told it to store the decimal number 10.75d, it would store 1010b for the 10, and .11b for the decimal. So it would store .101011 then it saves a few bits at the end to say: Move the decimal point four places right.

(Although technically it's no longer a decimal point, it's now a binary point, but that terminology wouldn't have made things more understandable for most people who would find this answer of any use.)

Remove Blank option from Select Option with AngularJS

Another method to resolve is by making use of: $first in ng-repeat

Usage:

<select ng-model="feed.config">
    <option ng-repeat="template in configs" ng-selected="$first">{{template.name}}</option>
</select>

References:

ngSelected : https://docs.angularjs.org/api/ng/directive/ngSelected

$first : https://docs.angularjs.org/api/ng/directive/ngRepeat

Cheers

How to open SharePoint files in Chrome/Firefox

You can use web-based protocol handlers for the links as per https://sharepoint.stackexchange.com/questions/70178/how-does-sharepoint-2013-enable-editing-of-documents-for-chrome-and-fire-fox

Basically, just prepend ms-word:ofe|u| to the links to your SharePoint hosted Word documents.

What does `void 0` mean?

void 0 returns undefined and can not be overwritten while undefined can be overwritten.

var undefined = "HAHA";

Practical uses for AtomicInteger

If you look at the methods AtomicInteger has, you'll notice that they tend to correspond to common operations on ints. For instance:

static AtomicInteger i;

// Later, in a thread
int current = i.incrementAndGet();

is the thread-safe version of this:

static int i;

// Later, in a thread
int current = ++i;

The methods map like this:
++i is i.incrementAndGet()
i++ is i.getAndIncrement()
--i is i.decrementAndGet()
i-- is i.getAndDecrement()
i = x is i.set(x)
x = i is x = i.get()

There are other convenience methods as well, like compareAndSet or addAndGet

What is the correct format to use for Date/Time in an XML file

What does the DTD have to say?

If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.

If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.

Disabling user input for UITextfield in swift

Try this:

Swift 2.0:

textField.userInteractionEnabled = false

Swift 3.0:

textField.isUserInteractionEnabled = false

Or in storyboard uncheck "User Interaction Enabled"

enter image description here

Cross-Origin Read Blocking (CORB)

Try to install "Moesif CORS" extension if you are facing issue in google chrome. As it is cross origin request, so chrome is not accepting a response even when the response status code is 200

Capture Video of Android's Screen

I know this is an old question but since it appears to be unanswered to the OPs liking. There is an app that accopmlishes this in the Android Market Screencast link

How to run ssh-add on windows?

I have been in similar situation before. In Command prompt, you type 'start-ssh-agent' and voila! The ssh-agent will be started. Input the passphrase if it asked you.

pull access denied repository does not exist or may require docker login

If the repository is private you have to assign permissions to download it. You have two options, with the docker login command, or put in ~/.docker/docker.config the file generated once you login.

WampServer orange icon

It can happen because of one of the three reasons:-

1) Missing VC++ installation: Install All versions of VC++ redistribution packages VC9, VC10, VC11, VC13, VC14 and VC15. See the link provided at the end for download link. If you have a 64-bit Windows, you must install both 32 and 64bit versions of each VisualC++ package, even if you do not use Wampserver 64 bit.

2) You forgot to provide Admin Privileges to WAMP Server : Launch and Install with the "Run as administrator" option, very important.

3) WAMP, IIS and Skype fighting over same port :

enter image description here

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

The reason in my case was the target build was not the same between project debugger and test runner. To unify those elements:

  1. Test>Test Settings>Default Processor Architecture. then select either X64 or X86.
  2. Project>(your project)Properties>Build(tab)>platform target.

After they are identical, rebuild your solution then test methods will appear for you.

Spring MVC - How to get all request params in a map in Spring controller?

While the other answers are correct it certainly is not the "Spring way" to use the HttpServletRequest object directly. The answer is actually quite simple and what you would expect if you're familiar with Spring MVC.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

Elegant way to read file into byte[] array in Java

This will also work:

import java.io.*;

public class IOUtil {

    public static byte[] readFile(String file) throws IOException {
        return readFile(new File(file));
    }

    public static byte[] readFile(File file) throws IOException {
        // Open file
        RandomAccessFile f = new RandomAccessFile(file, "r");
        try {
            // Get and check length
            long longlength = f.length();
            int length = (int) longlength;
            if (length != longlength)
                throw new IOException("File size >= 2 GB");
            // Read file and return data
            byte[] data = new byte[length];
            f.readFully(data);
            return data;
        } finally {
            f.close();
        }
    }
}

reading text file with utf-8 encoding using java

Use

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;     
    public class test {
    public static void main(String[] args){

    try {
        File fileDir = new File("PATH_TO_FILE");

        BufferedReader in = new BufferedReader(
           new InputStreamReader(new FileInputStream(fileDir), "UTF-8"));

        String str;

        while ((str = in.readLine()) != null) {
            System.out.println(str);
        }

                in.close();
        } 
        catch (UnsupportedEncodingException e) 
        {
            System.out.println(e.getMessage());
        } 
        catch (IOException e) 
        {
            System.out.println(e.getMessage());
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

You need to put UTF-8 in quotes

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

In my case, there was something wrong with the .NET Core Windows Hosting Bundle installation.

I had that installed and had restarted IIS using ("net stop was /y" and "net start w3svc") after installation, but I would get that 500.19 error with Error Code 0x8007000d and Config Source -1: 0:.

I managed to resolve the issue by repairing the .NET Core Windows Hosting Bundle installation and restarting IIS using the commands I mentioned above.

Hope this helps someone!

What is difference between Lightsail and EC2?

Check official website https://aws.amazon.com/free/compute/lightsail-vs-ec2/

enter image description here

Amazon Lightsail – The Power of AWS, the Simplicity of a VPS https://aws.amazon.com/blogs/aws/amazon-lightsail-the-power-of-aws-the-simplicity-of-a-vps/

Amazon EC2 vs Amazon Lightsail (comparison on point )

  • Web Performances
  • Plans
  • Features and Usability enter image description here

Source : https://www.vpsbenchmarks.com/compare/features/ec2_vs_lightsail

How to convert AAR to JAR

Resource based .aar-projects

Finding the classes.jar file inside the .aar file is pretty trivial. However, that approach does not work, if the .aar-project defined some resources (example: R.layout.xyz)

  • Therefore deaar from CommonsGuy helped me to get a valid ADT-friendly project out of an .aar-file. In my case I converted subsampling-scale-image-view. It took me about an hour to set up ruby on my PC.

  • Another approach is using android-maven-plugin for Eclipse/ADT as CommonsGuy writes in his blog.

  • Yet another approach could be, just cloning the whole desired project as source from git and import it as "Existing Android project"

VSCode Change Default Terminal

If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts") `

//with this you can select what type of console you want
{
    "key": "ctrl+shift+t",
    "command": "shellLauncher.launch"
},

//and this will help you quickly change console
{ 
    "key": "ctrl+shift+j", 
    "command": "workbench.action.terminal.focusNext" 
},
{
    "key": "ctrl+shift+k", 
    "command": "workbench.action.terminal.focusPrevious" 
}`

How to create a backup of a single table in a postgres database?

I was trying to run pg_dump from within psql command prompt and I was not able to trace output file anywhere on my ubuntu 20.04 box. I tried finding by find / -name "myfilename.sql".

Instead When I tried pg_dump from /home/ubuntu, I found my output file in /home/ubuntu

How to insert element into arrays at specific position?

I just created an ArrayHelper class that would make this very easy for numeric indexes.

class ArrayHelper
{
    /*
        Inserts a value at the given position or throws an exception if
        the position is out of range.
        This function will push the current values up in index. ex. if 
        you insert at index 1 then the previous value at index 1 will 
        be pushed to index 2 and so on.
        $pos: The position where the inserted value should be placed. 
        Starts at 0.
    */
    public static function insertValueAtPos(array &$array, $pos, $value) {
        $maxIndex = count($array)-1;

        if ($pos === 0) {
            array_unshift($array, $value);
        } elseif (($pos > 0) && ($pos <= $maxIndex)) {
            $firstHalf = array_slice($array, 0, $pos);
            $secondHalf = array_slice($array, $pos);
            $array = array_merge($firstHalf, array($value), $secondHalf);
        } else {
            throw new IndexOutOfBoundsException();
        }

    }
}

Example:

$array = array('a', 'b', 'c', 'd', 'e');
$insertValue = 'insert';
\ArrayHelper::insertValueAtPos($array, 3, $insertValue);

Beginning $array:

Array ( 
    [0] => a 
    [1] => b 
    [2] => c 
    [3] => d 
    [4] => e 
)

Result:

Array ( 
    [0] => a 
    [1] => b 
    [2] => c 
    [3] => insert 
    [4] => d 
    [5] => e 
)

What is the purpose of the single underscore "_" variable in Python?

It's just a variable name, and it's conventional in python to use _ for throwaway variables. It just indicates that the loop variable isn't actually used.

How to use order by with union all in sql?

SELECT  * 
FROM 
        (
            SELECT * FROM TABLE_A 
            UNION ALL 
            SELECT * FROM TABLE_B
        ) dum
-- ORDER BY .....

but if you want to have all records from Table_A on the top of the result list, the you can add user define value which you can use for ordering,

SELECT  * 
FROM 
        (
            SELECT *, 1 sortby FROM TABLE_A 
            UNION ALL 
            SELECT *, 2 sortby FROM TABLE_B
        ) dum
ORDER   BY sortby 

How do I subscribe to all topics of a MQTT broker

Concrete example

mosquitto.org is very active (at the time of this posting). This is a nice smoke test for a MQTT subscriber linux device:

mosquitto_sub -h test.mosquitto.org -t "#" -v

The "#" is a wildcard for topics and returns all messages (topics): the server had a lot of traffic, so it returned a 'firehose' of messages.

If your MQTT device publishes a topic of irisys/V4D-19230005/ to the test MQTT broker , then you could filter the messages:

mosquitto_sub -h test.mosquitto.org -t "irisys/V4D-19230005/#" -v

Options:

  • -h the hostname (default MQTT port = 1883)
  • -t precedes the topic

C# Break out of foreach loop after X number of items

Or just use a regular for loop instead of foreach. A for loop is slightly faster (though you won't notice the difference except in very time critical code).

The maximum value for an int type in Go

https://golang.org/ref/spec#Numeric_types for physical type limits.

The max values are defined in the math package so in your case: math.MaxUint32

Watch out as there is no overflow - incrementing past max causes wraparound.

Git Push ERROR: Repository not found

I faced same error after updating my ubuntu to next version

I just deleted my sshkey on github account and then re added an sshkey to that account.

Can you use CSS to mirror/flip text?

direction: rtl; is probably what you are looking for.

how to check confirm password field in form without reloading page

Solution Using jQuery

 <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>

 <style>
    #form label{float:left; width:140px;}
    #error_msg{color:red; font-weight:bold;}
 </style>

 <script>
    $(document).ready(function(){
        var $submitBtn = $("#form input[type='submit']");
        var $passwordBox = $("#password");
        var $confirmBox = $("#confirm_password");
        var $errorMsg =  $('<span id="error_msg">Passwords do not match.</span>');

        // This is incase the user hits refresh - some browsers will maintain the disabled state of the button.
        $submitBtn.removeAttr("disabled");

        function checkMatchingPasswords(){
            if($confirmBox.val() != "" && $passwordBox.val != ""){
                if( $confirmBox.val() != $passwordBox.val() ){
                    $submitBtn.attr("disabled", "disabled");
                    $errorMsg.insertAfter($confirmBox);
                }
            }
        }

        function resetPasswordError(){
            $submitBtn.removeAttr("disabled");
            var $errorCont = $("#error_msg");
            if($errorCont.length > 0){
                $errorCont.remove();
            }  
        }


        $("#confirm_password, #password")
             .on("keydown", function(e){
                /* only check when the tab or enter keys are pressed
                 * to prevent the method from being called needlessly  */
                if(e.keyCode == 13 || e.keyCode == 9) {
                    checkMatchingPasswords();
                }
             })
             .on("blur", function(){                    
                // also check when the element looses focus (clicks somewhere else)
                checkMatchingPasswords();
            })
            .on("focus", function(){
                // reset the error message when they go to make a change
                resetPasswordError();
            })

    });
  </script>

And update your form accordingly:

<form id="form" name="form" method="post" action="registration.php"> 
    <label for="username">Username : </label>
    <input name="username" id="username" type="text" /></label><br/>

    <label for="password">Password :</label> 
    <input name="password" id="password" type="password" /><br/>

    <label for="confirm_password">Confirm Password:</label>
    <input type="password" name="confirm_password" id="confirm_password" /><br/>

    <input type="submit" name="submit"  value="registration"  />
</form>

This will do precisely what you asked for:

  • validate that the password and confirm fields are equal without clicking the register button
  • If password and confirm password field will not match it will place an error message at the side of confirm password field and disable registration button

It is advisable not to use a keyup event listener for every keypress because really you only need to evaluate it when the user is done entering information. If someone types quickly on a slow machine, they may perceive lag as each keystroke will kick off the function.

Also, in your form you are using labels wrong. The label element has a "for" attribute which should correspond with the id of the form element. This is so that when visually impaired people use a screen reader to call out the form field, it will know text belongs to which field.

What is System, out, println in System.out.println() in Java

The first answer you posted (System is a built-in class...) is pretty spot on.

You can add that the System class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out printstream to the native output stream associated with the "standard out" (console).

Adding Google Play services version to your app's manifest?

In my case i had to install google repository from the SDK manager.

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

JavaScript function to add X months to a date

This function handles edge cases and is fast:

function addMonthsUTC (date, count) {
  if (date && count) {
    var m, d = (date = new Date(+date)).getUTCDate()

    date.setUTCMonth(date.getUTCMonth() + count, 1)
    m = date.getUTCMonth()
    date.setUTCDate(d)
    if (date.getUTCMonth() !== m) date.setUTCDate(0)
  }
  return date
}

test:

> d = new Date('2016-01-31T00:00:00Z');
Sat Jan 30 2016 18:00:00 GMT-0600 (CST)
> d = addMonthsUTC(d, 1);
Sun Feb 28 2016 18:00:00 GMT-0600 (CST)
> d = addMonthsUTC(d, 1);
Mon Mar 28 2016 18:00:00 GMT-0600 (CST)
> d.toISOString()
"2016-03-29T00:00:00.000Z"

Update for non-UTC dates: (by A.Hatchkins)

function addMonths (date, count) {
  if (date && count) {
    var m, d = (date = new Date(+date)).getDate()

    date.setMonth(date.getMonth() + count, 1)
    m = date.getMonth()
    date.setDate(d)
    if (date.getMonth() !== m) date.setDate(0)
  }
  return date
}

test:

> d = new Date(2016,0,31);
Sun Jan 31 2016 00:00:00 GMT-0600 (CST)
> d = addMonths(d, 1);
Mon Feb 29 2016 00:00:00 GMT-0600 (CST)
> d = addMonths(d, 1);
Tue Mar 29 2016 00:00:00 GMT-0600 (CST)
> d.toISOString()
"2016-03-29T06:00:00.000Z"

Laravel Blade html image

in my case this worked perfectly

<img  style="border-radius: 50%;height: 50px;width: 80px;"  src="<?php echo asset("storage/TeacherImages/{$studydata->teacher->profilePic}")?>">

this code is used to display image from folder

Show history of a file?

You can use git log to display the diffs while searching:

git log -p -- path/to/file

How to display image from database using php

put you $image in img tag of html

try this

echo '<img src="your_path_to_image/'.$image.'" />';

instead of

print $image;

your_path_to_image would be absolute path of your image folder like eg: /home/son/public_html/images/ or as your folder structure on server.

Update 2 :

if your image is resides in the same folder where this page file is exists
you can user this

echo '<img src="'.$image.'" />';

How to fix java.net.SocketException: Broken pipe?

The cause is that the remote peer closes its socket (crash for example), so if you try to write data to him for example, you will get this. to solve that, protect read/write to socket operations between (try catch), then manage the lose connection case into the catch (renew connection, stop program, ...etc):

 try {
      /* your code */
 } catch (SocketException e) {
      e.printStackTrace();
      /* insert your failure processings here */
 }

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.

You can use JavaScript/Canvas to do the job but it is still experimental.

PHP Error: Function name must be a string

Try square braces with your $_COOKIE, not parenthesis. Like this:

<?php
if ($_COOKIE['CaptchaResponseValue'] == "false")
{
    header('Location: index.php');
    return;
}
?>

I also corrected your location header call a little too.

Replace NA with 0 in a data frame column

Since nobody so far felt fit to point out why what you're trying doesn't work:

  1. NA == NA doesn't return TRUE, it returns NA (since comparing to undefined values should yield an undefined result).
  2. You're trying to call apply on an atomic vector. You can't use apply to loop over the elements in a column.
  3. Your subscripts are off - you're trying to give two indices into a$x, which is just the column (an atomic vector).

I'd fix up 3. to get to a$x[is.na(a$x)] <- 0

Replace all spaces in a string with '+'

Use global search in the string. g flag

str.replace(/\s+/g, '+');

source: replaceAll function

jquery change div text

best and simple way is to put title inside a span and replace then.

'<div id="'+div_id+'" class="widget" style="height:60px;width:110px">\n\
        <div class="widget-head ui-widget-header" 
                style="cursor:move;height:20px;width:130px">'+
     '<span id="'+span_id+'" style="float:right; cursor:pointer" 
            class="dialog_link ui-icon ui-icon-newwin ui-icon-pencil"></span>' +
      '<span id="spTitle">'+
      dialog_title+ '</span>'
 '</div></div>

now you can simply use this:

$('#'+div_id+' .widget-head sp#spTitle').text("new dialog title");

How to implement Enums in Ruby?

I use the following approach:

class MyClass
  MY_ENUM = [MY_VALUE_1 = 'value1', MY_VALUE_2 = 'value2']
end

I like it for the following advantages:

  1. It groups values visually as one whole
  2. It does some compilation-time checking (in contrast with just using symbols)
  3. I can easily access the list of all possible values: just MY_ENUM
  4. I can easily access distinct values: MY_VALUE_1
  5. It can have values of any type, not just Symbol

Symbols may be better cause you don't have to write the name of outer class, if you are using it in another class (MyClass::MY_VALUE_1)

Convert regular Python string to raw string

With a little bit correcting @Jolly1234's Answer: here is the code:

raw_string=path.encode('unicode_escape').decode()

Using Google maps API v3 how do I get LatLng with a given address?

There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

To shorten it up a little:

geocoder = new google.maps.Geocoder();

function codeAddress() {

    //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
    var address = document.getElementById( 'address' ).value;

    geocoder.geocode( { 'address' : address }, function( results, status ) {
        if( status == google.maps.GeocoderStatus.OK ) {

            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter( results[0].geometry.location );
            var marker = new google.maps.Marker( {
                map     : map,
                position: results[0].geometry.location
            } );
        } else {
            alert( 'Geocode was not successful for the following reason: ' + status );
        }
    } );
}

Making interface implementations async

Better solution is to introduce another interface for async operations. New interface must inherit from original interface.

Example:

interface IIO
{
    void DoOperation();
}

interface IIOAsync : IIO
{
    Task DoOperationAsync();
}


class ClsAsync : IIOAsync
{
    public void DoOperation()
    {
        DoOperationAsync().GetAwaiter().GetResult();
    }

    public async Task DoOperationAsync()
    {
        //just an async code demo
        await Task.Delay(1000);
    }
}


class Program
{
    static void Main(string[] args)
    {
        IIOAsync asAsync = new ClsAsync();
        IIO asSync = asAsync;

        Console.WriteLine(DateTime.Now.Second);

        asAsync.DoOperation();
        Console.WriteLine("After call to sync func using Async iface: {0}", 
            DateTime.Now.Second);

        asAsync.DoOperationAsync().GetAwaiter().GetResult();
        Console.WriteLine("After call to async func using Async iface: {0}", 
            DateTime.Now.Second);

        asSync.DoOperation();
        Console.WriteLine("After call to sync func using Sync iface: {0}", 
            DateTime.Now.Second);

        Console.ReadKey(true);
    }
}

P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.

Why is there no Char.Empty like String.Empty?

In terms of C# language, the following may not make much sense. And this is not a direct answer to the question. But following is what I did in one of my business scenarios.

char? myCharFromUI = Convert.ToChar(" ");
string myStringForDatabaseInsert = myCharFromUI.ToString().Trim();
if (String.IsNullOrEmpty(myStringForDatabaseInsert.Trim()))
{
    Console.Write("Success");
}

The null and white space had different business flows in my project. While inserting into database, I need to insert empty string to the database if it is white space.

One line if/else condition in linux shell scripting

You can use like bellow:

(( var0 = var1<98?9:21 ))

the same as

if [ "$var1" -lt 98 ]; then
   var0=9
else
   var0=21
fi

extends

condition?result-if-true:result-if-false

I found the interested thing on the book "Advanced Bash-Scripting Guide"

RestClientException: Could not extract response. no suitable HttpMessageConverter found

Spring sets the default content-type to octet-stream when the response is missing that field. All you need to do is to add a message converter to fix this.

How to split the screen with two equal LinearLayouts?

Use the layout_weight attribute. The layout will roughly look like this:

<LinearLayout android:orientation="horizontal"
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent">

    <LinearLayout 
        android:layout_weight="1" 
        android:layout_height="fill_parent" 
        android:layout_width="0dp"/>

    <LinearLayout 
        android:layout_weight="1" 
        android:layout_height="fill_parent" 
        android:layout_width="0dp"/>

</LinearLayout>

How to call a SOAP web service on Android

About a year ago I was reading this thread trying to figure out how to do SOAP calls on Android - the suggestions to build my own using HttpClient resulted in me building my own SOAP library for Android:

IceSoap

Basically it allows you to build up envelopes to send via a simple Java API, then automatically parses them into objects that you define via XPath... for example:

<Dictionary>
    <Id></Id>
    <Name></Name>
</Dictionary>

Becomes:

@XMLObject("//Dictionary")
public class Dictionary {
    @XMLField("Id")
    private String id;

    @XMLField("Name")
    private String name;
}

I was using it for my own project but I figured it might help some other people so I've spent some time separating it out and documenting it. I'd really love it if some of your poor souls who stumble on this thread while googling "SOAP Android" could give it a go and get some benefit.

Load RSA public key from file

Once you have your key stored in a PEM file, you can read it back easily using PemObject and PemReader classes provided by BouncyCastle, as shown in this this tutorial.

Create a PemFile class that encapsulates file handling:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;

public class PemFile {

    private PemObject pemObject;

    public PemFile(String filename) throws FileNotFoundException, IOException {
        PemReader pemReader = new PemReader(new InputStreamReader(
                new FileInputStream(filename)));
        try {
            this.pemObject = pemReader.readPemObject();
        } finally {
            pemReader.close();
        }
    }

    public PemObject getPemObject() {
        return pemObject;
    }
}

Then instantiate private and public keys as usual:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.log4j.Logger;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class Main {

    protected final static Logger LOGGER = Logger.getLogger(Main.class);

    public final static String RESOURCES_DIR = "src/main/resources/rsa-sample/";

    public static void main(String[] args) throws FileNotFoundException,
            IOException, NoSuchAlgorithmException, NoSuchProviderException {
        Security.addProvider(new BouncyCastleProvider());
        LOGGER.info("BouncyCastle provider added.");

        KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
        try {
            PrivateKey priv = generatePrivateKey(factory, RESOURCES_DIR
                    + "id_rsa");
            LOGGER.info(String.format("Instantiated private key: %s", priv));

            PublicKey pub = generatePublicKey(factory, RESOURCES_DIR
                    + "id_rsa.pub");
            LOGGER.info(String.format("Instantiated public key: %s", pub));
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }

    private static PrivateKey generatePrivateKey(KeyFactory factory,
            String filename) throws InvalidKeySpecException,
            FileNotFoundException, IOException {
        PemFile pemFile = new PemFile(filename);
        byte[] content = pemFile.getPemObject().getContent();
        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
        return factory.generatePrivate(privKeySpec);
    }

    private static PublicKey generatePublicKey(KeyFactory factory,
            String filename) throws InvalidKeySpecException,
            FileNotFoundException, IOException {
        PemFile pemFile = new PemFile(filename);
        byte[] content = pemFile.getPemObject().getContent();
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
        return factory.generatePublic(pubKeySpec);
    }
}

Hope this helps.

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

How to change column order in a table using sql query in sql server 2005?

Use

SELECT * FROM TABLE1

which displays the default column order of the table.

If you want to change the order of the columns.

Specify the column name to display correspondingly

SELECT COLUMN1, COLUMN5, COLUMN4, COLUMN3, COULMN2 FROM TABLE1

How to switch from the default ConstraintLayout to RelativeLayout in Android Studio

Android studio 3.0

step0:

Close android studio

step1:

Goto C:\Program Files\Android\Android Studio\plugins\android\lib\templates\activities\common\root\res\layout\

step2:

Backup simple.xml.ftl

step3:

Change simple.xml.ftl to code below and save :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}">


<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="12dp"
    android:layout_marginTop="21dp"
    android:text="don't forget to click useful if this helps. this is my first post at stackoverflow!"
    android:textSize="20sp"
    />

</RelativeLayout>

How do I select last 5 rows in a table without sorting?

Without an order, this is impossible. What defines the "bottom"? The following will select 5 rows according to how they are stored in the database.

SELECT TOP 5 * FROM [TableName]

Responsive font size in CSS

The text size can be set with a vw unit, which means the "viewport width". That way the text size will follow the size of the browser window:

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_responsive_text

For my personal project I used vw and @meida. It works perfectly.

.mText {
    font-size: 6vw;
}

@media only screen and (max-width: 1024px) {
    .mText {
        font-size: 10vw;
    }
}


.sText {
    font-size: 4vw;
}

@media only screen and (max-width: 1024px) {
    .sText {
        font-size: 7vw;
    }
}

How can I select the row with the highest ID in MySQL?

Suppose you have mulitple record for same date or leave_type but different id and you want the maximum no of id for same date or leave_type as i also sucked with this issue, so Yes you can do it with the following query:

select * from tabel_name where employee_no='123' and id=(
   select max(id) from table_name where employee_no='123' and leave_type='5'
)

Is there any way to wait for AJAX response and halt execution?

use async:false attribute along with url and data. this will help to execute ajax call immediately and u can fetch and use data from server.

function functABC(){
    $.ajax({
        url: 'myPage.php',
        data: {id: id},
        async:false
        success: function(data) {
            return data;
        }
    });
}

What does it mean by select 1 from table?

If you don't know there exist any data in your table or not, you can use following query:

SELECT cons_value FROM table_name;

For an Example:

SELECT 1 FROM employee;
  1. It will return a column which contains the total number of rows & all rows have the same constant value 1 (for this time it returns 1 for all rows);
  2. If there is no row in your table it will return nothing.

So, we use this SQL query to know if there is any data in the table & the number of rows indicates how many rows exist in this table.

How to add Tomcat Server in eclipse

Right Click on the server tab, go for NEW-> Server. then choose recent version of tomcat server. Click on next, and then give path for your tomcat server.(You can download tomcat server from this link https://tomcat.apache.org/download-80.cgi#8.5.32). Click on finish.

You can start your server now..!!

Programmatically navigate to another view controller/scene

let signUpVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SignUp")
// self.present(signUpVC, animated: false, completion: nil)
self.navigationController?.pushViewController(signUpVC, animated: true)

What does the "$" sign mean in jQuery or JavaScript?

The $ is just a function. It is actually an alias for the function called jQuery, so your code can be written like this with the exact same results:

jQuery('#Text').click(function () {
  jQuery('#Text').css('color', 'red');
});

Converting a sentence string to a string array of words in Java

Use string.replace(".", "").replace(",", "").replace("?", "").replace("!","").split(' ') to split your code into an array with no periods, commas, question marks, or exclamation marks. You can add/remove as many replace calls as you want.

Fill formula down till last row in column

Wonderful answer! I needed to fill in the empty cells in a column where there were titles in cells that applied to the empty cells below until the next title cell.

I used your code above to develop the code that is below my example sheet here. I applied this code as a macro ctl/shft/D to rapidly run down the column copying the titles.

--- Example Spreadsheet ------------ Title1 is copied to rows 2 and 3; Title2 is copied to cells below it in rows 5 and 6. After the second run of the Macro the active cell is the Title3 cell.

 ' **row** **Column1**        **Column2**
 '    1     Title1         Data 1 for title 1
 '    2                    Data 2 for title 1
 '    3                    Data 3 for title 1
 '    4     Title2         Data 1 for title 2
 '    5                    Data 2 for title 2
 '    6                    Data 3 for title 2
 '    7   Title 3          Data 1 for title 3

----- CopyDown code ----------

Sub CopyDown()
Dim Lastrow As String, FirstRow As String, strtCell As Range
'
' CopyDown Macro
' Copies the current cell to any empty cells below it.   
'
' Keyboard Shortcut: Ctrl+Shift+D
'
    Set strtCell = ActiveCell
    FirstRow = strtCell.Address
' Lastrow is address of the *list* of empty cells
    Lastrow = Range(Selection, Selection.End(xlDown).Offset(-1, 0)).Address
'   MsgBox Lastrow
    Range(Lastrow).Formula = strtCell.Formula

    Range(Lastrow).End(xlDown).Select
 End Sub

C# DateTime to "YYYYMMDDHHMMSS" format

DateTime.Now.ToString("MM/dd/yyyy") 05/29/2015
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 05:50
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 05:50 AM
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 5:50
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 5:50 AM
DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss")    Friday, 29 May 2015 05:50:06
DateTime.Now.ToString("MM/dd/yyyy HH:mm")   05/29/2015 05:50
DateTime.Now.ToString("MM/dd/yyyy hh:mm tt")    05/29/2015 05:50 AM
DateTime.Now.ToString("MM/dd/yyyy H:mm")    05/29/2015 5:50
DateTime.Now.ToString("MM/dd/yyyy h:mm tt") 05/29/2015 5:50 AM
DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")    05/29/2015 05:50:06
DateTime.Now.ToString("MMMM dd")    May 29
DateTime.Now.ToString("yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK") 2015-05-16T05:50:06.7199222-04:00
DateTime.Now.ToString("ddd, dd MMM yyy HH’:’mm’:’ss ‘GMT’") Fri, 16 May 2015 05:50:06 GMT
DateTime.Now.ToString("yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss")  2015-05-16T05:50:06
DateTime.Now.ToString("HH:mm")  05:50
DateTime.Now.ToString("hh:mm tt")   05:50 AM
DateTime.Now.ToString("H:mm")   5:50
DateTime.Now.ToString("h:mm tt")    5:50 AM
DateTime.Now.ToString("HH:mm:ss")   05:50:06
DateTime.Now.ToString("yyyy MMMM")  2015 May

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

In previous answers a few registry keys that might not exist are missed. They are SchUseStrongCrypto that must exist to allow to TLS protocols work properly.

After the registry keys have been imported to registry it should not be required to make changes in code like

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

Below there are all registry keys and values that are needed for x64 windows OS. If you have 32bit OS (x86) just remove the last 2 lines. TLS 1.0 will be disabled by the registry script. Restarting OS is required.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"DisabledByDefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\server]
"disabledbydefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\ssl 3.0]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\ssl 3.0\client]
"disabledbydefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\ssl 3.0\server]
"disabledbydefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.0]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.0\client]
"disabledbydefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.0\server]
"disabledbydefault"=dword:00000001
"enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.1]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.1\client]
"disabledbydefault"=dword:00000000
"enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.1\server]
"disabledbydefault"=dword:00000000
"enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.2]

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.2\client]
"disabledbydefault"=dword:00000000
"enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\tls 1.2\server]
"disabledbydefault"=dword:00000000
"enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

Loading existing .html file with android WebView

ok, that was my very stupid mistake. I post the answer here just in case someone has the same problem.

The correct path for files stored in assets folder is file:///android_asset/* (with no "s" for assets folder which i was always thinking it must have a "s").

And, mWebView.loadUrl("file:///android_asset/myfile.html"); works under all API levels.

I still not figure out why mWebView.loadUrl("file:///android_res/raw/myfile.html"); works only on API level 8. But it doesn't matter now.

Fastest way to implode an associative array with keys

As an aside, I was in search to find the best way to implode an associative array but using my own seperators etc...

So I did this using PHP's array_walk() function to let me join an associative array into a list of parameters that could then be applied to a HTML tag....

// Create Params Array
$p = Array("id"=>"blar","class"=>"myclass","onclick"=>"myJavascriptFunc()");

// Join Params
array_walk($p, create_function('&$i,$k','$i=" $k=\"$i\"";'));
$p_string = implode($p,"");

// Now use $p_string for your html tag

Obviously, you could stick that in your own function somehow but it gives you an idea of how you can join an associative array using your own method. Hope that helps someone :)

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

The problem is that these two queries are each returning more than one row:

select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close')
select isbn from dbo.lending where lended_date between @fdate and @tdate

You have two choices, depending on your desired outcome. You can either replace the above queries with something that's guaranteed to return a single row (for example, by using SELECT TOP 1), OR you can switch your = to IN and return multiple rows, like this:

select * from dbo.books where isbn IN (select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close'))

How to import NumPy in the Python shell

On Debian/Ubuntu:

aptitude install python-numpy

On Windows, download the installer:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems, download the tar.gz and run the following:

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

C# listView, how do I add items to columns 2, 3 and 4 etc?

There are several ways to do it, but here is one solution (for 4 columns).

string[] row1 = { "s1", "s2", "s3" };
listView1.Items.Add("Column1Text").SubItems.AddRange(row1);

And a more verbose way is here:

ListViewItem item1 = new ListViewItem("Something");
item1.SubItems.Add("SubItem1a");
item1.SubItems.Add("SubItem1b");
item1.SubItems.Add("SubItem1c");

ListViewItem item2 = new ListViewItem("Something2");
item2.SubItems.Add("SubItem2a");
item2.SubItems.Add("SubItem2b");
item2.SubItems.Add("SubItem2c");

ListViewItem item3 = new ListViewItem("Something3");
item3.SubItems.Add("SubItem3a");
item3.SubItems.Add("SubItem3b");
item3.SubItems.Add("SubItem3c");

ListView1.Items.AddRange(new ListViewItem[] {item1,item2,item3});

jQuery disable/enable submit button

you can also use something like this :

$(document).ready(function() {
    $('input[type="submit"]').attr('disabled', true);
    $('input[type="text"]').on('keyup',function() {
        if($(this).val() != '') {
            $('input[type="submit"]').attr('disabled' , false);
        }else{
            $('input[type="submit"]').attr('disabled' , true);
        }
    });
});

here is Live example

.prop('checked',false) or .removeAttr('checked')?

Another alternative to do the same thing is to filter on type=checkbox attribute:

$('input[type="checkbox"]').removeAttr('checked');

or

$('input[type="checkbox"]').prop('checked' , false);

Remeber that The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Know more...

How to apply filters to *ngFor?

This is your array

products: any = [
        {
            "name": "John-Cena",
                    },
        {
            "name": "Brock-Lensar",

        }
    ];

This is your ngFor loop Filter By :

<input type="text" [(ngModel)]='filterText' />
    <ul *ngFor='let product of filterProduct'>
      <li>{{product.name }}</li>
    </ul>

There I'm using filterProduct instant of products, because i want to preserve my original data. Here model _filterText is used as a input box.When ever there is any change setter function will call. In setFilterText performProduct is called it will return the result only those who match with the input. I'm using lower case for case insensitive.

filterProduct = this.products;
_filterText : string;
    get filterText() : string {
        return this._filterText;
    }

    set filterText(value : string) {
        this._filterText = value;
        this.filterProduct = this._filterText ? this.performProduct(this._filterText) : this.products;

    } 

    performProduct(value : string ) : any {
            value = value.toLocaleLowerCase();
            return this.products.filter(( products : any ) => 
                products.name.toLocaleLowerCase().indexOf(value) !== -1);
        }

How can I get the current page name in WordPress?

Ok, you must grab the page title before the loop.

$page_title = $wp_query->post->post_title;

Check for the reference: http://codex.wordpress.org/Function_Reference/WP_Query#Properties.

Do a

print_r($wp_query)

before the loop to see all the values of the $wp_query object.

Remove a HTML tag but keep the innerHtml

The simplest way to remove inner html elements and return only text would the JQuery .text() function.

Example:

var text = $('<p>A nice house was found in <b>Toronto</b></p>');

alert( text.html() );
//Outputs A nice house was found in <b>Toronto</b>

alert( text.text() );
////Outputs A nice house was found in Toronto

jsFiddle Demo

How to pass parameters on onChange of html select

_x000D_
_x000D_
function getComboA(selectObject) {_x000D_
  var value = selectObject.value;  _x000D_
  console.log(value);_x000D_
}
_x000D_
<select id="comboA" onchange="getComboA(this)">_x000D_
  <option value="">Select combo</option>_x000D_
  <option value="Value1">Text1</option>_x000D_
  <option value="Value2">Text2</option>_x000D_
  <option value="Value3">Text3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

The above example gets you the selected value of combo box on OnChange event.

How to Identify Microsoft Edge browser via CSS?

For Internet Explorer 

@media all and (-ms-high-contrast: none) {
        .banner-wrapper{
            background: rgba(0, 0, 0, 0.16)
         }
}

For Edge
@supports (-ms-ime-align:auto) {
    .banner-wrapper{
            background: rgba(0, 0, 0, 0.16);
         }
}

Send Email Intent

Please use the below code :

                try {

                    String uriText =
                            "mailto:emailid" +
                                    "?subject=" + Uri.encode("Feedback for app") +
                                    "&body=" + Uri.encode(deviceInfo);
                    Uri uri = Uri.parse(uriText);
                    Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
                    emailIntent.setData(uri);
                    startActivity(Intent.createChooser(emailIntent, "Send email using..."));
                } catch (android.content.ActivityNotFoundException ex) {
                    Toast.makeText(ContactUsActivity.this, "No email clients installed.", Toast.LENGTH_SHORT).show();
                }

Decode JSON with unknown structure

You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;

package main

import (
    "fmt"
    "encoding/json"
)

type Data struct {
    Votes *Votes `json:"votes"`
    Count string `json:"count,omitempty"`
}

type Votes struct {
    OptionA string `json:"option_A"`
}

func main() {
    s := `{ "votes": { "option_A": "3" } }`
    data := &Data{
        Votes: &Votes{},
    }
    err := json.Unmarshal([]byte(s), data)
    fmt.Println(err)
    fmt.Println(data.Votes)
    s2, _ := json.Marshal(data)
    fmt.Println(string(s2))
    data.Count = "2"
    s3, _ := json.Marshal(data)
    fmt.Println(string(s3))
}

https://play.golang.org/p/ScuxESTW5i

Based on your most recent comment you could address that by using an interface{} to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{} which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.

Error: Cannot match any routes. URL Segment: - Angular 2

Solved myself. Done some small structural changes also. Route from Component1 to Component2 is done by a single <router-outlet>. Component2 to Comonent3 and Component4 is done by multiple <router-outlet name= "xxxxx"> The resulting contents are :

Component1.html

<nav>
    <a routerLink="/two" class="dash-item">Go to 2</a>
</nav>
    <router-outlet></router-outlet>

Component2.html

 <a [routerLink]="['/two', {outlets: {'nameThree': ['three']}}]">In Two...Go to 3 ...       </a>
 <a [routerLink]="['/two', {outlets: {'nameFour': ['four']}}]">   In Two...Go to 4 ...</a>

 <router-outlet name="nameThree"></router-outlet>
 <router-outlet name="nameFour"></router-outlet>

The '/two' represents the parent component and ['three']and ['four'] represents the link to the respective children of component2 . Component3.html and Component4.html are the same as in the question.

router.module.ts

const routes: Routes = [
{
    path: '',
    redirectTo: 'one',
    pathMatch: 'full'
},
{
    path: 'two',
    component: ClassTwo, children: [

        {
            path: 'three',
            component: ClassThree,
            outlet: 'nameThree'
        },
        {
            path: 'four',
            component: ClassFour,
            outlet: 'nameFour'
        }
    ]
},];

Validating a Textbox field for only numeric input.

If you want to prevent the user from enter non-numeric values at the time of enter the information in the TextBox, you can use the Event OnKeyPress like this:

private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar)) e.Handled = true;         //Just Digits
            if (e.KeyChar == (char)8) e.Handled = false;            //Allow Backspace
            if (e.KeyChar == (char)13) btnSearch_Click(sender, e);  //Allow Enter            
        }

This solution doesn't work if the user paste the information in the TextBox using the mouse (right click / paste) in that case you should add an extra validation.

process.start() arguments

Try fully qualifying the filenames in the arguments - I notice you're specifying the path in the FileName part, so it's possible that the process is being started elsewhere, then not finding the arguments and causing an error.

If that works, then setting the WorkingDirectory property on the StartInfo may be of use.

Actually, according to the link

The WorkingDirectory property must be set if UserName and Password are provided. If the property is not set, the default working directory is %SYSTEMROOT%\system32.

Add a background image to shape in XML Android

This is a circle shape with icon inside:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/ok_icon"/>
    <item>
        <shape
                android:shape="oval">
            <solid android:color="@color/transparent"/>
            <stroke android:width="2dp" android:color="@color/button_grey"/>
        </shape>
    </item>
</layer-list>

Removing object from array in Swift 3

This is what I've used (Swift 5)...

    extension Array where Element:Equatable
    {
        @discardableResult
        mutating func removeFirst(_ item:Any ) -> Any? {
            for index in 0..<self.count {
                if(item as? Element == self[index]) {
                    return self.remove(at: index)
                }
            }
            return nil
        }
        @discardableResult
        mutating func removeLast(_ item:Any ) -> Any? {
            var index = self.count-1
            while index >= 0 {
                if(item as? Element == self[index]) {
                    return self.remove(at: index)
                }
                index -= 1
            }
            return nil
        }
    }

    var arrContacts:[String] = ["A","B","D","C","B","D"]
    var contacts: [Any] = ["B","D"]
    print(arrContacts)
    var index = 1
    arrContacts.removeFirst(contacts[index])
    print(arrContacts)
    index = 0
    arrContacts.removeLast(contacts[index])
    print(arrContacts)

Results:

   ["A", "B", "D", "C", "B", "D"]
   ["A", "B", "C", "B", "D"]
   ["A", "B", "C", "D"]

Important: The array from which you remove items must contain Equatable elements (such as objects, strings, number, etc.)

Add my custom http header to Spring RestTemplate request / extend RestTemplate

You can pass custom http headers with RestTemplate exchange method as below.

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<RestRequest> entityReq = new HttpEntity<RestRequest>(request, headers);

RestTemplate template = new RestTemplate();

ResponseEntity<RestResponse> respEntity = template
    .exchange("RestSvcUrl", HttpMethod.POST, entityReq, RestResponse.class);

EDIT : Below is the updated code. This link has several ways of calling rest service with examples

RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-TP-DeviceID", "your value");

HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

ResponseEntity<Mall[]> respEntity = restTemplate.exchange(url, HttpMethod.POST, entity, Mall[].class);

Mall[] resp = respEntity.getBody();

How to click or tap on a TextView text

You can use TextWatcher for TextView, is more flexible than ClickLinstener (not best or worse, only more one way).

holder.bt_foo_ex.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // code during!

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // code before!

        }

        @Override
        public void afterTextChanged(Editable s) {
            // code after!

        }
    });

How to set Sqlite3 to be case insensitive when string comparing?

You can use COLLATE NOCASE in your SELECT query:

SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE

Additionaly, in SQLite, you can indicate that a column should be case insensitive when you create the table by specifying collate nocase in the column definition (the other options are binary (the default) and rtrim; see here). You can specify collate nocase when you create an index as well. For example:

create table Test
(
  Text_Value  text collate nocase
);

insert into Test values ('A');
insert into Test values ('b');
insert into Test values ('C');

create index Test_Text_Value_Index
  on Test (Text_Value collate nocase);

Expressions involving Test.Text_Value should now be case insensitive. For example:

sqlite> select Text_Value from Test where Text_Value = 'B';
Text_Value      
----------------
b               

sqlite> select Text_Value from Test order by Text_Value;
Text_Value      
----------------
A               
b               
C    

sqlite> select Text_Value from Test order by Text_Value desc;
Text_Value      
----------------
C               
b               
A               

The optimiser can also potentially make use of the index for case-insensitive searching and matching on the column. You can check this using the explain SQL command, e.g.:

sqlite> explain select Text_Value from Test where Text_Value = 'b';
addr              opcode          p1          p2          p3                               
----------------  --------------  ----------  ----------  ---------------------------------
0                 Goto            0           16                                           
1                 Integer         0           0                                            
2                 OpenRead        1           3           keyinfo(1,NOCASE)                
3                 SetNumColumns   1           2                                            
4                 String8         0           0           b                                
5                 IsNull          -1          14                                           
6                 MakeRecord      1           0           a                                
7                 MemStore        0           0                                            
8                 MoveGe          1           14                                           
9                 MemLoad         0           0                                            
10                IdxGE           1           14          +                                
11                Column          1           0                                            
12                Callback        1           0                                            
13                Next            1           9                                            
14                Close           1           0                                            
15                Halt            0           0                                            
16                Transaction     0           0                                            
17                VerifyCookie    0           4                                            
18                Goto            0           1                                            
19                Noop            0           0                                            

Unable to connect PostgreSQL to remote database using pgAdmin

If you're using PostgreSQL 8 or above, you may need to modify the listen_addresses setting in /etc/postgresql/8.4/main/postgresql.conf.

Try adding the line:

listen_addresses = *

which will tell PostgreSQL to listen for connections on all network interfaces.

If not explicitly set, this setting defaults to localhost which means it will only accept connections from the same machine.

Get total number of items on Json object?

That's an Object and you want to count the properties of it.

Object.keys(jsonArray).length

References:

Javascript switch vs. if...else if...else

Sometimes it's better to use neither. For example, in a "dispatch" situation, Javascript lets you do things in a completely different way:

function dispatch(funCode) {
  var map = {
    'explode': function() {
      prepExplosive();
      if (flammable()) issueWarning();
      doExplode();
    },

    'hibernate': function() {
      if (status() == 'sleeping') return;
      // ... I can't keep making this stuff up
    },
    // ...
  };

  var thisFun = map[funCode];
  if (thisFun) thisFun();
}

Setting up multi-way branching by creating an object has a lot of advantages. You can add and remove functionality dynamically. You can create the dispatch table from data. You can examine it programmatically. You can build the handlers with other functions.

There's the added overhead of a function call to get to the equivalent of a "case", but the advantage (when there are lots of cases) of a hash lookup to find the function for a particular key.

Access camera from a browser

Video Tutorial: Accessing the Camera with HTML5 & appMobi API will be helpful for you.

Also, you may try the getUserMedia method (supported by Opera 12)

enter image description here

How to get images in Bootstrap's card to be the same height/width?

I found the below works for my setup using cards and grid system. I set the flex-grow property of card-image-top class to 1 and the object fit on the same to contain and the flex-grow property of the body to 0.

HTML

<div class="container-fluid">
    <div class="row row-cols-2 row-cols-md-4">
        <div class="col mb-4">
            <div class="card h-100">
                <img src="https://i0.wp.com/www.impact-media.be/wp-content/uploads/2019/09/placeholder-1-e1533569576673-960x960.png" class="card-img-top">
                <div class="card-body">
                    <p class="card-text">Test</p>
                </div>
            </div>
        </div>
        <div class="col mb-4">
            <div class="card h-100">
                <img src="http://www.nebero.com/wp-content/uploads/2014/05/placeholder.jpg" class="card-img-top">
                <div class="card-body">
                    <p class="card-text">Test</p>
                </div>
            </div>
        </div>
        <div class="col mb-4">
            <div class="card h-100">
                <img src="http://www.nebero.com/wp-content/uploads/2014/05/placeholder.jpg" class="card-img-top">
                <div class="card-body">
                    <p class="card-text">Test</p>
                </div>
            </div>
        </div>
        <div class="col mb-4">
            <div class="card h-100">
                <img src="https://i0.wp.com/www.impact-media.be/wp-content/uploads/2019/09/placeholder-1-e1533569576673-960x960.png" class="card-img-top">
                <div class="card-body">
                    <p class="card-text">Test</p>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

.card-img-top {
    flex-grow: 1;
    object-fit:contain;
}
.card-body{
    flex-grow:0;
}

javascript : sending custom parameters with window.open() but its not working

To concatenate strings, use the + operator.

To insert data into a URI, encode it for URIs.

Bad:

var url = "http://localhost:8080/login?cid='username'&pwd='password'"

Good:

var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;

The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.

… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).

How does BitLocker affect performance?

I used to use the PGP disk encryption product on a laptop (and ran NTFS compressed on top of that!). It didn't seem to have much effect if the amount of disk to be read was small; and most software sources aren't huge by disk standards.

You have lots of RAM and pretty fast processors. I spent most of my time thinking, typing or debugging.

I wouldn't worry very much about it.

Trying to Validate URL Using JavaScript

best regex I found from http://angularjs.org/

var urlregex = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;

Convert timestamp to date in Oracle SQL

CAST(timestamp_expression AS DATE)

For example, The query is : SELECT CAST(SYSTIMESTAMP AS DATE) FROM dual;

Getting all request parameters in Symfony 2

With Recent Symfony 2.6+ versions as a best practice Request is passed as an argument with action in that case you won't need to explicitly call $this->getRequest(), but rather call $request->request->all()

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\HttpFoundation\RedirectResponse;

    class SampleController extends Controller
    {


        public function indexAction(Request $request) {

           var_dump($request->request->all());
        }

    }

Convert columns to string in Pandas

If you need to convert ALL columns to strings, you can simply use:

df = df.astype(str)

This is useful if you need everything except a few columns to be strings/objects, then go back and convert the other ones to whatever you need (integer in this case):

 df[["D", "E"]] = df[["D", "E"]].astype(int) 

How to prevent custom views from losing state across screen orientation changes

I found that this answer was causing some crashes on Android versions 9 and 10. I think it's a good approach but when I was looking at some Android code I found out it was missing a constructor. The answer is quite old so at the time there probably was no need for it. When I added the missing constructor and called it from the creator the crash was fixed.

So here is the edited code:

public class CustomView extends LinearLayout {

    private int stateToSave;

    ...

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);

        // your custom state
        ss.stateToSave = this.stateToSave;

        return ss;
    }

    @Override
    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container)
    {
        dispatchFreezeSelfOnly(container);
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());

        // your custom state
        this.stateToSave = ss.stateToSave;
    }

    @Override
    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container)
    {
        dispatchThawSelfOnly(container);
    }

    static class SavedState extends BaseSavedState {
        int stateToSave;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            this.stateToSave = in.readInt();
        }

        // This was the missing constructor
        @RequiresApi(Build.VERSION_CODES.N)
        SavedState(Parcel in, ClassLoader loader)
        {
            super(in, loader);
            this.stateToSave = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(this.stateToSave);
        }    
        
        public static final Creator<SavedState> CREATOR =
            new ClassLoaderCreator<SavedState>() {
          
            // This was also missing
            @Override
            public SavedState createFromParcel(Parcel in, ClassLoader loader)
            {
                return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new SavedState(in, loader) : new SavedState(in);
            }

            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in, null);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };
    }
}

Copying files from server to local computer using SSH

You need to name the file in both directory paths.

scp [email protected]:/dir/of/file.txt \local\dir\file.txt

Convert Mat to Array/Vector in OpenCV

If the memory of the Mat mat is continuous (all its data is continuous), you can directly get its data to a 1D array:

std::vector<uchar> array(mat.rows*mat.cols*mat.channels());
if (mat.isContinuous())
    array = mat.data;

Otherwise, you have to get its data row by row, e.g. to a 2D array:

uchar **array = new uchar*[mat.rows];
for (int i=0; i<mat.rows; ++i)
    array[i] = new uchar[mat.cols*mat.channels()];

for (int i=0; i<mat.rows; ++i)
    array[i] = mat.ptr<uchar>(i);

UPDATE: It will be easier if you're using std::vector, where you can do like this:

std::vector<uchar> array;
if (mat.isContinuous()) {
  // array.assign(mat.datastart, mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
  array.assign(mat.data, mat.data + mat.total()*mat.channels());
} else {
  for (int i = 0; i < mat.rows; ++i) {
    array.insert(array.end(), mat.ptr<uchar>(i), mat.ptr<uchar>(i)+mat.cols*mat.channels());
  }
}

p.s.: For cv::Mats of other types, like CV_32F, you should do like this:

std::vector<float> array;
if (mat.isContinuous()) {
  // array.assign((float*)mat.datastart, (float*)mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
  array.assign((float*)mat.data, (float*)mat.data + mat.total()*mat.channels());
} else {
  for (int i = 0; i < mat.rows; ++i) {
    array.insert(array.end(), mat.ptr<float>(i), mat.ptr<float>(i)+mat.cols*mat.channels());
  }
}

UPDATE2: For OpenCV Mat data continuity, it can be summarized as follows:

  • Matrices created by imread(), clone(), or a constructor will always be continuous.
  • The only time a matrix will not be continuous is when it borrows data (except the data borrowed is continuous in the big matrix, e.g. 1. single row; 2. multiple rows with full original width) from an existing matrix (i.e. created out of an ROI of a big mat).

Please check out this code snippet for demonstration.

Multiple modals overlay

I created a Bootstrap plugin that incorporates a lot of the ideas posted here.

Demo on Bootply: http://www.bootply.com/cObcYInvpq

Github: https://github.com/jhaygt/bootstrap-multimodal

It also addresses the issue with successive modals causing the backdrop to become darker and darker. This ensures that only one backdrop is visible at any given time:

if(modalIndex > 0)
    $('.modal-backdrop').not(':first').addClass('hidden');

The z-index of the visible backdrop is updated on both the show.bs.modal and hidden.bs.modal events:

$('.modal-backdrop:first').css('z-index', MultiModal.BASE_ZINDEX + (modalIndex * 20));

I can't install python-ldap

For most systems, the build requirements are now mentioned in python-ldap's documentation, in the "Installing" section.

If anything is missing for your system (or your system is missing entirely), please let maintainer know! (As of 2018, I am the maintainer, so a comment here should be enough. Or you can send a pull request or mail.)

source command not found in sh shell

/bin/sh is usually some other shell trying to mimic The Shell. Many distributions use /bin/bash for sh, it supports source. On Ubuntu, though, /bin/dash is used which does not support source. Most shells use . instead of source. If you cannot edit the script, try to change the shell which runs it.

Submit a form using jQuery

you could do it like this :

$('#myform').bind('submit', function(){ ... });

Tool for sending multipart/form-data request

The usual error is one tries to put Content-Type: {multipart/form-data} into the header of the post request. That will fail, it is best to let Postman do it for you. For example:

Suggestion To Load Via Postman Body Part

Fails If In Header Common Error

Works should remove content type from the Header

Which is best data type for phone number in MySQL and what should Java type mapping for it be?

In MySQL -> INT(10) does not mean a 10-digit number, it means an integer with a display width of 10 digits. The maximum value for an INT in MySQL is 2147483647 (or 4294967295 if unsigned).

You can use a BIGINT instead of INT to store it as a numeric. Using BIGINT will save you 3 bytes per row over VARCHAR(10).

If you want to Store "Country + area + number separately". Try using a VARCHAR(20). This allows you the ability to store international phone numbers properly, should that need arise.

ASP.NET 2.0 - How to use app_offline.htm

I have used the extremely handy app_offline.htm trick to shut down/update sites in the past without any issues.

Be sure that you are actually placing the "app_offline.htm" file in the "root" of the website that you have configured within IIS.

Also ensure that the file is named exactly as it should be: app_offline.htm

Other than that, there should be no other changes to IIS that you should need to make since the processing of this file (with this specific name) is handled by the ASP.NET runtime rather than IIS itself (for IIS v6).

Be aware, however, that although placing this file in the root of your site will force the application to "shut down" and display the content of the "app_offline.htm" file itself, any existing requests will still get the real website served up to them. Only new requests will get the app_offline.htm content.

If you're still having issues, try the following links for further info:

Scott Gu's App_Offline.htm

App_Offline.htm and working around the "IE Friendly Errors" feature

Will app_offline.htm stop current requests or just new requests?

Image, saved to sdcard, doesn't appear in Android's Gallery app

My code for MyMediaConnectorClient:

public class MyMediaConnectorClient implements MediaScannerConnectionClient {

    String _fisier;
    MediaScannerConnection MEDIA_SCANNER_CONNECTION;

    public MyMediaConnectorClient(String nume) {
        _fisier = nume;
    }

    public void setScanner(MediaScannerConnection msc){
        MEDIA_SCANNER_CONNECTION = msc;
    }

    @Override
    public void onMediaScannerConnected() {
        MEDIA_SCANNER_CONNECTION.scanFile(_fisier, null);
    }

    @Override
    public void onScanCompleted(String path, Uri uri) {
        if(path.equals(_fisier))
            MEDIA_SCANNER_CONNECTION.disconnect();
    }
}

How to make an HTTP POST web request

Simple (one-liner, no error checking, no wait for response) solution I've found so far:

(new WebClient()).UploadStringAsync(new Uri(Address), dataString);?

Use with caution!

Excel VBA Check if directory exists error

You can replace WB_parentfolder with something like "C:\". For me WB_parentfolder is grabbing the location of the current workbook. file_des_folder is the new folder i want. This goes through and creates as many folders as you need.

        folder1 = Left(file_des_folder, InStr(Len(WB_parentfolder) + 1, file_loc, "\"))
        Do While folder1 <> file_des_folder
            folder1 = Left(file_des_folder, InStr(Len(folder1) + 1, file_loc, "\"))
            If Dir(file_des_folder, vbDirectory) = "" Then      'create folder if there is not one
                MkDir folder1
            End If
        Loop

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

A better solution (mentioned by @KrisNuttycombe):

git diff fc17405...ee2de56

for the merge commit:

commit 0e1329e551a5700614a2a34d8101e92fd9f2cad6 (HEAD, master)
Merge: fc17405 ee2de56
Author: Tilman Vogel <email@email>
Date:   Tue Feb 22 00:27:17 2011 +0100

to show all of the changes on ee2de56 that are reachable from commits on fc17405. Note the order of the commit hashes - it's the same as shown in the merge info: Merge: fc17405 ee2de56

Also note the 3 dots ... instead of two!

For a list of changed files, you can use:

git diff fc17405...ee2de56 --name-only

How do you implement a re-try-catch?

A simple way to solve the issue would be to wrap the try/catch in a while loop and maintain a count. This way you could prevent an infinite loop by checking a count against some other variable while maintaining a log of your failures. It isn't the most exquisite solution, but it would work.

Logger slf4j advantages of formatting with {} instead of string concatenation

Another alternative is String.format(). We are using it in jcabi-log (static utility wrapper around slf4j).

Logger.debug(this, "some variable = %s", value);

It's much more maintainable and extendable. Besides, it's easy to translate.

Lock, mutex, semaphore... what's the difference?

Supporting ownership, maximum number of processes share lock and the maximum number of allowed processes/threads in critical section are three major factors that determine the name/type of the concurrent object with general name of lock. Since the value of these factors are binary (have two states), we can summarize them in a 3*8 truth-like table.

  • X (Supports Ownership?): no(0) / yes(1)
  • Y (#sharing processes): > 1 (8) / 1
  • Z (#processes/threads in CA): > 1 (8) / 1

  X   Y   Z          Name
 --- --- --- ------------------------
  0   8   8   Semaphore              
  0   8   1   Binary Semaphore       
  0   1   8   SemaphoreSlim          
  0   1   1   Binary SemaphoreSlim(?)
  1   8   8   Recursive-Mutex(?)     
  1   8   1   Mutex                  
  1   1   8   N/A(?)                 
  1   1   1   Lock/Monitor           

Feel free to edit or expand this table, I've posted it as an ascii table to be editable:)

Spring-boot default profile for integration tests

Another programatically way to do that:

  import static org.springframework.core.env.AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME;

  @BeforeClass
  public static void setupTest() {
    System.setProperty(DEFAULT_PROFILES_PROPERTY_NAME, "test");
  }

It works great.

Eclipse, regular expression search and replace

NomeN has answered correctly, but this answer wouldn't be of much use for beginners like me because we will have another problem to solve and we wouldn't know how to use RegEx in there. So I am adding a bit of explanation to this. The answer is

search: (\w+\\.someMethod\\(\\))

replace: ((TypeName)$1)

Here:

In search:

  • First and last (, ) depicts a group in regex

  • \w depicts words (alphanumeric + underscore)

  • + depicts one or more (ie one or more of alphanumeric + underscore)

  • . is a special character which depicts any character (ie .+ means one or more of any character). Because this is a special character to depict a . we should give an escape character with it, ie \.

  • someMethod is given as it is to be searched.

  • The two parenthesis (, ) are given along with escape character because they are special character which are used to depict a group (we will discuss about group in next point)

In replace:

  • It is given ((TypeName)$1), here $1 depicts the group. That is all the characters that are enclosed within the first and last parenthesis (, ) in the search field

  • Also make sure you have checked the 'Regular expression' option in find an replace box

How do I replace all line breaks in a string with <br /> elements?

Without regex:

str = str.split("\n").join("<br />");

CSS, Images, JS not loading in IIS

This issue occurs when IIS does not render the static contents like your JS, CSS, Image files.

To resolve this issue, you need to follow the below steps:

GO to Control Panel > Turn Windows features on or off > Internet Information Services > World Wide Web Services > Common HTTP Features > Static Content.

Ensure that static content is turned on.

Bingo. And you are done. Hard-reload the page and you will be able to see all the static contents.

Python Requests library redirect new url

the documentation has this blurb https://requests.readthedocs.io/en/master/user/quickstart/#redirection-and-history

import requests

r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for 

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

Cocoa Packet Analyzer is similar to WireShark but with a much better interface. http://www.tastycocoabytes.com/cpa/

batch file to check 64bit or 32bit OS

After much trial and error, I managed to get a few different working examples, but the kicker was when the batch was launched on a 64bit OS on a 32bit CMD. In the end this was the simplest check I could get to work, which works on Win2k-Win8 32/64. Also big thanks to Phil who helped me with this.

set bit64=n
if /I %Processor_Architecture%==AMD64 set bit64=y
if /I "%PROCESSOR_ARCHITEW6432%"=="AMD64" set bit64=y

Python convert decimal to hex

This is the best way I use it

hex(53350632996854).lstrip("0x").rstrip("L")
# lstrip helps remove "0x" from the left  
# rstrip helps remove "L" from the right 
# L represents a long number

Example:

>>> decimal = 53350632996854
>>> hexadecimal = hex(decimal).lstrip("0x")
>>> print(hexadecimal)
3085a9873ff6

if you need it Upper Case, Can use "upper function" For Example:

decimal = 53350632996854
hexadecimal = hex(decimal).lstrip("0x").upper()
print(hexadecimal)
3085A9873FF6

How to add a "open git-bash here..." context menu to the windows explorer?

I updated my git and I marked the option of "Git Bash Here"

How to update column value in laravel

I tried to update a field with

$table->update(['field' => 'val']);

But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"

Hope it will help someone :)

How to install a node.js module without using npm?

Download the code from github into the node_modules directory

var moduleName = require("<name of directory>")

that should do it.

if the module has dependancies and has a package.json, open the module and enter npm install.

Hope this helps

convert epoch time to date

Here’s the modern answer (valid from 2014 and on). The accepted answer was a very fine answer in 2011. These days I recommend no one uses the Date, DateFormat and SimpleDateFormat classes. It all goes more natural with the modern Java date and time API.

To get a date-time object from your millis:

    ZonedDateTime dateTime = Instant.ofEpochMilli(millis)
            .atZone(ZoneId.of("Australia/Sydney"));

If millis equals 1318388699000L, this gives you 2011-10-12T14:04:59+11:00[Australia/Sydney]. Should the code in some strange way end up on a JVM that doesn’t know Australia/Sydney time zone, you can be sure to be notified through an exception.

If you want the date-time in your string format for presentation:

String formatted = dateTime.format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"));

Result:

12/10/2011 14:04:59

PS I don’t know what you mean by “The above doesn't work.” On my computer your code in the question too prints 12/10/2011 14:04:59.

How do I set the icon for my application in visual studio 2008?

If you're using .NET, in the solutions explorer right click your program and select properties. Under the resource section select Icon and manifest, then browse to the location of your icon.

Unable to copy ~/.ssh/id_rsa.pub

Based on the date of this question the original poster wouldn't have been using Windows Subsystem for Linux. But if you are, and you get the same error, the following alternative works:

clip.exe < ~/.ssh/id_rsa.pub

Thanks to this page for pointing out Windows' clip.exe (and you have to type the ".exe") can be run from the bash shell.

How to select all checkboxes with jQuery?

jQuery(document).ready(function () {
        jQuery('.select-all').on('change', function () {
            if (jQuery(this).is(':checked')) {
                jQuery('input.class-name').each(function () {
                    this.checked = true;
                });
            } else {
                jQuery('input.class-name').each(function () {
                    this.checked = false;
                });
            }
        });
    });

TypeScript enum to object array

A tricky bit is that TypeScript will 'double' map the enum in the emitted object, so it can be accessed both by key and value.

enum MyEnum {
    Part1 = 0,
    Part2 = 1
}

will be emitted as

{
   Part1: 0,
   Part2: 1,
   0: 'Part1',
   1: 'Part2'
}

So you should filter the object first before mapping. So @Diullei 's solution has the right answer. Here is my implementation:

// Helper
const StringIsNumber = value => isNaN(Number(value)) === false;

// Turn enum into array
function ToArray(enumme) {
    return Object.keys(enumme)
        .filter(StringIsNumber)
        .map(key => enumme[key]);
}

Use it like this:

export enum GoalProgressMeasurements {
    Percentage,
    Numeric_Target,
    Completed_Tasks,
    Average_Milestone_Progress,
    Not_Measured
}

console.log(ToArray(GoalProgressMeasurements));

How can I find the product GUID of an installed MSI setup?

For upgrade code retrieval: How can I find the Upgrade Code for an installed MSI file?


Short Version

The information below has grown considerably over time and may have become a little too elaborate. How to get product codes quickly? (four approaches):

1 - Use the Powershell "one-liner"

Scroll down for screenshot and step-by-step. Disclaimer also below - minor or moderate risks depending on who you ask. Works OK for me. Any self-repair triggered by this option should generally be possible to cancel. The package integrity checks triggered does add some event log "noise" though. Note! IdentifyingNumber is the ProductCode (WMI peculiarity).

get-wmiobject Win32_Product | Sort-Object -Property Name |Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

Quick start of Powershell: hold Windows key, tap R, type in "powershell" and press Enter

2 - Use VBScript (script on github.com)

Described below under "Alternative Tools" (section 3). This option may be safer than Powershell for reasons explained in detail below. In essence it is (much) faster and not capable of triggering MSI self-repair since it does not go through WMI (it accesses the MSI COM API directly - at blistering speed). However, it is more involved than the Powershell option (several lines of code).

3 - Registry Lookup

Some swear by looking things up in the registry. Not my recommended approach - I like going through proper APIs (or in other words: OS function calls). There are always weird exceptions accounted for only by the internals of the API-implementation:

  • HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
  • HKLM\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall
  • HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall

4 - Original MSI File / WiX Source

You can find the Product Code in the Property table of any MSI file (and any other property as well). However, the GUID could conceivably (rarely) be overridden by a transform applied at install time and hence not match the GUID the product is registered under (approach 1 and 2 above will report the real product code - that is registered with Windows - in such rare scenarios).

You need a tool to view MSI files. See towards the bottom of the following answer for a list of free tools you can download (or see quick option below): How can I compare the content of two (or more) MSI files?

UPDATE: For convenience and need for speed :-), download SuperOrca without delay and fuss from this direct-download hotlink - the tool is good enough to get the job done - install, open MSI and go straight to the Property table and find the ProductCode row (please always virus check a direct-download hotlink - obviously - you can use virustotal.com to do so - online scan utilizing dozens of anti-virus and malware suites to scan what you upload).

Orca is Microsoft's own tool, it is installed with Visual Studio and the Windows SDK. Try searching for Orca-x86_en-us.msi - under Program Files (x86) and install the MSI if found.

  • Current path: C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x86
  • Change version numbers as appropriate

And below you will find the original answer which "organically grew" into a lot of detail.

Maybe see "Uninstall MSI Packages" section below if this is the task you need to perform.


Retrieve Product Codes

UPDATE: If you also need the upgrade code, check this answer: How can I find the Upgrade Code for an installed MSI file? (retrieves associated product codes, upgrade codes & product names in a table output - similar to the one below).

  • Can't use PowerShell? See "Alternative Tools" section below.
  • Looking to uninstall? See "Uninstall MSI packages" section below.

Fire up Powershell (hold down the Windows key, tap R, release the Windows key, type in "powershell" and press OK) and run the command below to get a list of installed MSI package product codes along with the local cache package path and the product name (maximize the PowerShell window to avoid truncated names).

Before running this command line, please read the disclaimer below (nothing dangerous, just some potential nuisances). Section 3 under "Alternative Tools" shows an alternative non-WMI way to get the same information using VBScript. If you are trying to uninstall a package there is a section below with some sample msiexec.exe command lines:

get-wmiobject Win32_Product | Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

The output should be similar to this:

enter image description here

Note! For some strange reason the "ProductCode" is referred to as "IdentifyingNumber" in WMI. So in other words - in the picture above the IdentifyingNumber is the ProductCode.

If you need to run this query remotely against lots of remote computer, see "Retrieve Product Codes From A Remote Computer" section below.

DISCLAIMER (important, please read before running the command!): Due to strange Microsoft design, any WMI call to Win32_Product (like the PowerShell command below) will trigger a validation of the package estate. Besides being quite slow, this can in rare cases trigger an MSI self-repair. This can be a small package or something huge - like Visual Studio. In most cases this does not happen - but there is a risk. Don't run this command right before an important meeting - it is not ever dangerous (it is read-only), but it might lead to a long repair in very rare cases (I think you can cancel the self-repair as well - unless actively prevented by the package in question, but it will restart if you call Win32_Product again and this will persist until you let the self-repair finish - sometimes it might continue even if you do let it finish: How can I determine what causes repeated Windows Installer self-repair?).

And just for the record: some people report their event logs filling up with MsiInstaller EventID 1035 entries (see code chief's answer) - apparently caused by WMI queries to the Win32_Product class (personally I have never seen this). This is not directly related to the Powershell command suggested above, it is in context of general use of the WIM class Win32_Product.

You can also get the output in list form (instead of table):

get-wmiobject -class Win32_Product

In this case the output is similar to this:

enter image description here


Retrieve Product Codes From A Remote Computer

In theory you should just be able to specify a remote computer name as part of the command itself. Here is the same command as above set up to run on the machine "RemoteMachine" (-ComputerName RemoteMachine section added):

get-wmiobject Win32_Product -ComputerName RemoteMachine | Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

This might work if you are running with domain admin rights on a proper domain. In a workgroup environment (small office / home network), you probably have to add user credentials directly to the WMI calls to make it work.

Additionally, remote connections in WMI are affected by (at least) the Windows Firewall, DCOM settings, and User Account Control (UAC) (plus any additional non-Microsoft factors - for instance real firewalls, third party software firewalls, security software of various kinds, etc...). Whether it will work or not depends on your exact setup.

UPDATE: An extensive section on remote WMI running can be found in this answer: How can I find the Upgrade Code for an installed MSI file?. It appears a firewall rule and suppression of the UAC prompt via a registry tweak can make things work in a workgroup network environment. Not recommended changes security-wise, but it worked for me.


Alternative Tools

PowerShell requires the .NET framework to be installed (currently in version 3.5.1 it seems? October, 2017). The actual PowerShell application itself can also be missing from the machine even if .NET is installed. Finally I believe PowerShell can be disabled or locked by various system policies and privileges.

If this is the case, you can try a few other ways to retrieve product codes. My preferred alternative is VBScript - it is fast and flexible (but can also be locked on certain machines, and scripting is always a little more involved than using tools).

  1. Let's start with a built-in Windows WMI tool: wbemtest.exe.
  • Launch wbemtest.exe (Hold down the Windows key, tap R, release the Windows key, type in "wbemtest.exe" and press OK).
  • Click connect and then OK (namespace defaults to root\cimv2), and click "connect" again.
  • Click "Query" and type in this WQL command (SQL flavor): SELECT IdentifyingNumber,Name,Version FROM Win32_Product and click "Use" (or equivalent - the tool will be localized).
  • Sample output screenshot (truncated). Not the nicest formatting, but you can get the data you need. IdentifyingNumber is the MSI product code:

wbemtest.exe

  1. Next, you can try a custom, more full featured WMI tool such as WMIExplorer.exe
  • This is not included in Windows. It is a very good tool, however. Recommended.
  • Check it out at: https://github.com/vinaypamnani/wmie2/releases
  • Launch the tool, click Connect, double click ROOT\CIMV2
  • From the "Query tab", type in the following query SELECT IdentifyingNumber,Name,Version FROM Win32_Product and press Execute.
  • Screenshot skipped, the application requires too much screen real estate.
  1. Finally you can try a VBScript to access information via the MSI automation interface (core feature of Windows - it is unrelated to WMI).
  • Copy the below script and paste into a *.vbs file on your desktop, and try to run it by double clicking. Your desktop must be writable for you, or you can use any other writable location.
  • This is not a great VBScript. Terseness has been preferred over error handling and completeness, but it should do the job with minimum complexity.
  • The output file is created in the folder where you run the script from (folder must be writable). The output file is called msiinfo.csv.
  • Double click the file to open in a spreadsheet application, select comma as delimiter on import - OR - just open the file in Notepad or any text viewer.
  • Opening in a spreadsheet will allow advanced sorting features.
  • This script can easily be adapted to show a significant amount of further details about the MSI installation. A demonstration of this can be found here: how to find out which products are installed - newer product are already installed MSI windows.
' Retrieve all ProductCodes (with ProductName and ProductVersion)
Set fso = CreateObject("Scripting.FileSystemObject")
Set output = fso.CreateTextFile("msiinfo.csv", True, True)
Set installer = CreateObject("WindowsInstaller.Installer")

On Error Resume Next ' we ignore all errors

For Each product In installer.ProductsEx("", "", 7)
   productcode = product.ProductCode
   name = product.InstallProperty("ProductName")
   version=product.InstallProperty("VersionString")
   output.writeline (productcode & ", " & name & ", " & version)
Next

output.Close

I can't think of any further general purpose options to retrieve product codes at the moment, please add if you know of any. Just edit inline rather than adding too many comments please.

You can certainly access this information from within your application by calling the MSI automation interface (COM based) OR the C++ MSI installer functions (Win32 API). Or even use WMI queries from within your application like you do in the samples above using PowerShell, wbemtest.exe or WMIExplorer.exe.


Uninstall MSI Packages

If what you want to do is to uninstall the MSI package you found the product code for, you can do this as follows using an elevated command prompt (search for cmd.exe, right click and run as admin):

Option 1: Basic, interactive uninstall without logging (quick and easy):

msiexec.exe /x {00000000-0000-0000-0000-00000000000C}

Quick Parameter Explanation:

/X = run uninstall sequence
{00000000-0000-0000-0000-00000000000C} = product code for product to uninstall

You can also enable (verbose) logging and run in silent mode if you want to, leading us to option 2:

Option 2: Silent uninstall with verbose logging (better for batch files):

msiexec.exe /x {00000000-0000-0000-0000-00000000000C} /QN /L*V "C:\My.log" REBOOT=ReallySuppress

Quick Parameter Explanation:

/X = run uninstall sequence
{00000000-0000-0000-0000-00000000000C} = product code for product to uninstall
/QN = run completely silently
/L*V "C:\My.log"= verbose logging at specified path
REBOOT=ReallySuppress = avoid unexpected, sudden reboot

There is a comprehensive reference for MSI uninstall here (various different ways to uninstall MSI packages): Uninstalling an MSI file from the command line without using msiexec. There is a plethora of different ways to uninstall.

If you are writing a batch file, please have a look at section 3 in the above, linked answer for a few common and standard uninstall command line variants.

And a quick link to msiexec.exe (command line options) (overview of the command line for msiexec.exe from MSDN). And the Technet version as well.


Retrieving other MSI Properties / Information (f.ex Upgrade Code)

UPDATE: please find a new answer on how to find the upgrade code for installed packages instead of manually looking up the code in MSI files. For installed packages this is much more reliable. If the package is not installed, you still need to look in the MSI file (or the source file used to compile the MSI) to find the upgrade code. Leaving in older section below:

If you want to get the UpgradeCode or other MSI properties, you can open the cached installation MSI for the product from the location specified by "LocalPackage" in the image show above (something like: C:\WINDOWS\Installer\50c080ae.msi - it is a hex file name, unique on each system). Then you look in the "Property table" for UpgradeCode (it is possible for the UpgradeCode to be redefined in a transform - to be sure you get the right value you need to retrieve the code programatically from the system - I will provide a script for this shortly. However, the UpgradeCode found in the cached MSI is generally correct).

To open the cached MSI files, use Orca or another packaging tool. Here is a discussion of different tools (any of them will do): What installation product to use? InstallShield, WiX, Wise, Advanced Installer, etc. If you don't have such a tool installed, your fastest bet might be to try Super Orca (it is simple to use, but not extensively tested by me).

UPDATE: here is a new answer with information on various free products you can use to view MSI files: How can I compare the content of two (or more) MSI files?

If you have Visual Studio installed, try searching for Orca-x86_en-us.msi - under Program Files (x86) - and install it (this is Microsoft's own, official MSI viewer and editor). Then find Orca in the start menu. Go time in no time :-). Technically Orca is installed as part of Windows SDK (not Visual Studio), but Windows SDK is bundled with the Visual Studio install. If you don't have Visual Studio installed, perhaps you know someone who does? Just have them search for this MSI and send you (it is a tiny half mb file) - should take them seconds. UPDATE: you need several CAB files as well as the MSI - these are found in the same folder where the MSI is found. If not, you can always download the Windows SDK (it is free, but it is big - and everything you install will slow down your PC). I am not sure which part of the SDK installs the Orca MSI. If you do, please just edit and add details here.



Similar topics (for reference and easy access - I should clean this list up):

How to embed a Google Drive folder in a website

Google Drive folders can be embedded and displayed in list and grid views:

List view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#list" style="width:100%; height:600px; border:0;"></iframe>


Grid view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>



Q: What is a folder ID (FOLDER-ID) and how can I get it?

A: Go to Google Drive >> open the folder >> look at its URL in the address bar of your browser. For example:

Folder URL: https://drive.google.com/drive/folders/0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2

Folder ID:
0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2

Caveat with folders requiring permission

This technique works best for folders with public access. Folders that are shared only with certain Google accounts will cause trouble when you embed them this way. At the time of this edit, a message "You need permission" appears, with some buttons to help you "Request access" or "Switch accounts" (or possibly sign-in to a Google account). The Javascript in these buttons doesn't work properly inside an IFRAME in Chrome.

Read more at https://productforums.google.com/forum/#!msg/drive/GpVgCobPL2Y/_Xt7sMc1WzoJ

Creating an XmlNode/XmlElement in C# without an XmlDocument?

XmlNodes come with an OwnerDocument property.

Perhaps you can just do:

//Node is an XmlNode pulled from an XmlDocument
XmlElement e = node.OwnerDocument.CreateElement("MyNewElement");
e.InnerText = "Some value";
node.AppendChild(e);

Get time of specific timezone

If you know the UTC offset then you can pass it and get the time using the following function:

function calcTime(city, offset) {
    // create Date object for current location
    var d = new Date();

    // convert to msec
    // subtract local time zone offset
    // get UTC time in msec
    var utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    var nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time for city"+ city +" is "+ nd.toLocaleString();
}

alert(calcTime('Bombay', '+5.5'));

Taken from: Convert Local Time to Another

How do I connect to a MySQL Database in Python?

Run this command in your terminal to install mysql connector:

pip install mysql-connector-python

And run this in your python editor to connect to MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="yusername",
      passwd="password",
      database="database_name"
)

Samples to execute MySQL Commands (in your python edior):

mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")    
mycursor.execute("SHOW TABLES")

mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")    
mydb.commit() # Use this command after insert or update

For more commands: https://www.w3schools.com/python/python_mysql_getstarted.asp

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

For a new build, it could be that some dependencies aren't installed. For me it was Crystal Reports.

How to enable CORS in apache tomcat

CORS support in Tomcat is provided via a filter. You need to add this filter to your web.xml file and configure it to match your requirements. Full details on the configuration options available can be found in the Tomcat Documentation.

Converting NSString to NSDictionary / JSON

Swift 3:

if let jsonString = styleDictionary as? String {
    let objectData = jsonString.data(using: String.Encoding.utf8)
    do {
        let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers) 
        print(String(describing: json)) 

    } catch {
        // Handle error
        print(error)
    }
}

Java file path in Linux

Looks like you are missing a leading slash. Perhaps try:

Scanner s = new Scanner(new File("/home/me/java/ex.txt"));

(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)

How to read a specific line using the specific line number from a file in Java?

Not that I know of, but what you could do is loop through the first 31 lines doing nothing using the readline() function of BufferedReader

FileInputStream fs= new FileInputStream("someFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
for(int i = 0; i < 31; ++i)
  br.readLine();
String lineIWant = br.readLine();

do { ... } while (0) — what is it good for?

It is a way to simplify error checking and avoid deep nested if's. For example:

do {
  // do something
  if (error) {
    break;
  }
  // do something else
  if (error) {
    break;
  }
  // etc..
} while (0);

multiple where condition codeigniter

you can try this function for multi-purpose

function ManageData($table_name='',$condition=array(),$udata=array(),$is_insert=false){
$resultArr = array();
$ci = & get_instance();
if($condition && count($condition))
    $ci->db->where($condition);
if($is_insert)
{
    $ci->db->insert($table_name,$udata);
    return 0;
}
else
{
    $ci->db->update($table_name,$udata);
    return 1;
}

}

Add numpy array as column to Pandas data frame

df = pd.DataFrame(np.arange(1,10).reshape(3,3))
df['newcol'] = pd.Series(your_2d_numpy_array)

HttpWebRequest-The remote server returned an error: (400) Bad Request

Are you sure you should be using POST not PUT?

POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do..

Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.

sqlalchemy IS NOT NULL select

Starting in version 0.7.9 you can use the filter operator .isnot instead of comparing constraints, like this:

query.filter(User.name.isnot(None))

This method is only necessary if pep8 is a concern.

source: sqlalchemy documentation

Getting list of Facebook friends with latest API

header('Content-type: text/html; charset=utf-8');

input in your page.

How do I size a UITextView to its content?

It's quite easy with Key Value Observing (KVO), just create a subclass of UITextView and do:

private func setup() { // Called from init or somewhere

    fitToContentObservations = [
        textView.observe(\.contentSize) { _, _ in
            self.invalidateIntrinsicContentSize()
        },
        // For some reason the content offset sometimes is non zero even though the frame is the same size as the content size.
        textView.observe(\.contentOffset) { _, _ in
            if self.contentOffset != .zero { // Need to check this to stop infinite loop
                self.contentOffset = .zero
            }
        }
    ]
}
public override var intrinsicContentSize: CGSize {
    return contentSize
}

If you don't want to subclass you could try doing textView.bounds = textView.contentSize in the contentSize observer.

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

Get value (String) of ArrayList<ArrayList<String>>(); in Java

A cleaner way of iterating the lists is:

// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
    for (String string : innerList) {
        // do stuff with string
    }
}

$.focus() not working

ADDITIONAL SOLUTION Had same issue where focus() didn't seem to work but eventually it turned out that what was needed was scrolling to the correct position:

JTable How to refresh table model after insert delete or update the data.

If you want to notify your JTable about changes of your data, use
tableModel.fireTableDataChanged()

From the documentation:

Notifies all listeners that all cell values in the table's rows may have changed. The number of rows may also have changed and the JTable should redraw the table from scratch. The structure of the table (as in the order of the columns) is assumed to be the same.

Python Graph Library

I would like to plug my own graph python library: graph-tool.

It is very fast, since it is implemented in C++ with the Boost Graph Library, and it contains lots of algorithms and extensive documentation.

Converting java date to Sql timestamp

I suggest using DateUtils from apache.commons library.

long millis = DateUtils.truncate(utilDate, Calendar.MILLISECOND).getTime();
java.sql.Timestamp sq = new java.sql.Timestamp(millis );

Edit: Fixed Calendar.MILISECOND to Calendar.MILLISECOND

Android Studio: Default project directory

In android studio 2.3.3 (windows) you must go to C:\User\ (Name)\ .AndroidStudio2.3\config\option open recentProjects.xml And change your directory

<option name="lastProjectLocation" value="YOUR DIRECTORY" />

newline in <td title="">

Using &#013; didn't work in my fb app. However this did, beautifully (in Chrome FF and IE):

<img src="'../images/foo.gif'" title="line 1&lt;br&gt;line 2">

Python function pointer

It's much nicer to be able to just store the function itself, since they're first-class objects in python.

import mypackage

myfunc = mypackage.mymodule.myfunction
myfunc(parameter1, parameter2)

But, if you have to import the package dynamically, then you can achieve this through:

mypackage = __import__('mypackage')
mymodule = getattr(mypackage, 'mymodule')
myfunction = getattr(mymodule, 'myfunction')

myfunction(parameter1, parameter2)

Bear in mind however, that all of that work applies to whatever scope you're currently in. If you don't persist them somehow, you can't count on them staying around if you leave the local scope.

How to change colour of blue highlight on select box dropdown

try this.. I know it's an old post but it might help somebody

select option:hover,
    select option:focus,
    select option:active {
        background: linear-gradient(#000000, #000000);
        background-color: #000000 !important; /* for IE */
        color: #ffed00 !important;
    }

    select option:checked {
        background: linear-gradient(#d6d6d6, #d6d6d6);
        background-color: #d6d6d6 !important; /* for IE */
        color: #000000 !important;
    }

How to Exit a Method without Exiting the Program?

There are two ways to exit a method early (without quitting the program):

  • Use the return keyword.
  • Throw an exception.

Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.

If your method returns void then you can write return without a value:

return;

Specifically about your code:

  • There is no need to write the same test three times. All those conditions are equivalent.
  • You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:

    if (textBox1.Text == String.Empty)
    {
        textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    }
    return; // Are you sure you want the return to be here??
    
  • If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.

  • You might want to use Environment.Newline instead of "\r\n".
  • You might want to consider another way to display invalid input other than writing messages to a text box.

How to pass parameters to $http in angularjs?

Here is a simple mathed to pass values from a route provider

//Route Provider
$routeProvider.when("/page/:val1/:val2/:val3",{controller:pageCTRL, templateUrl: 'pages.html'});


//Controller
$http.get( 'page.php?val1='+$routeParams.val1 +'&val2='+$routeParams.val2 +'&val3='+$routeParams.val3 , { cache: true})
        .then(function(res){
            //....
        })

Google Maps v3 - limit viewable area and zoom level

Here's my variant to solve the problem of viewable area's limitation.

        google.maps.event.addListener(this.map, 'idle', function() {
            var minLat = strictBounds.getSouthWest().lat();
            var minLon = strictBounds.getSouthWest().lng();
            var maxLat = strictBounds.getNorthEast().lat();
            var maxLon = strictBounds.getNorthEast().lng();
            var cBounds  = self.map.getBounds();
            var cMinLat = cBounds.getSouthWest().lat();
            var cMinLon = cBounds.getSouthWest().lng();
            var cMaxLat = cBounds.getNorthEast().lat();
            var cMaxLon = cBounds.getNorthEast().lng();
            var centerLat = self.map.getCenter().lat();
            var centerLon = self.map.getCenter().lng();

            if((cMaxLat - cMinLat > maxLat - minLat) || (cMaxLon - cMinLon > maxLon - minLon))
            {   //We can't position the canvas to strict borders with a current zoom level
                self.map.setZoomLevel(self.map.getZoomLevel()+1);
                return;
            }
            if(cMinLat < minLat)
                var newCenterLat = minLat + ((cMaxLat-cMinLat) / 2);
            else if(cMaxLat > maxLat)
                var newCenterLat = maxLat - ((cMaxLat-cMinLat) / 2);
            else
                var newCenterLat = centerLat;
            if(cMinLon < minLon)
                var newCenterLon = minLon + ((cMaxLon-cMinLon) / 2);
            else if(cMaxLon > maxLon)
                var newCenterLon = maxLon - ((cMaxLon-cMinLon) / 2);
            else
                var newCenterLon = centerLon;

            if(newCenterLat != centerLat || newCenterLon != centerLon)
                self.map.setCenter(new google.maps.LatLng(newCenterLat, newCenterLon));
        });

strictBounds is an object of new google.maps.LatLngBounds() type. self.gmap stores a Google Map object (new google.maps.Map()).

It really works but don't only forget to take into account the haemorrhoids with crossing 0th meridians and parallels if your bounds cover them.

How to decode a Base64 string?

This page shows up when you google how to convert to base64, so for completeness:

$b  = [System.Text.Encoding]::UTF8.GetBytes("blahblah")
[System.Convert]::ToBase64String($b)

What is python's site-packages directory?

When you use --user option with pip, the package gets installed in user's folder instead of global folder and you won't need to run pip command with admin privileges.

The location of user's packages folder can be found using:

python -m site --user-site

This will print something like:

C:\Users\%USERNAME%\AppData\Roaming\Python\Python35\site-packages

When you don't use --user option with pip, the package gets installed in global folder given by:

python -c "import site; print(site.getsitepackages())"

This will print something like:

['C:\\Program Files\\Anaconda3', 'C:\\Program Files\\Anaconda3\\lib\\site-packages'

Note: Above printed values are for On Windows 10 with Anaconda 4.x installed with defaults.

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

The Eclipse executable launcher was unable to locate its companion launcher jar windows

just add -vm C:\Java\JDK\1.6\bin\javaw.exe before -vmarg in eclipse.ini this works for me.Hope this will help you good luck...

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

This script logs all the file names and ids in the drive:

// Log the name and id of every file in the user's Drive
function listFiles() {
  var files = DriveApp.getFiles();
  while ( files.hasNext() ) {
    var file = files.next();
    Logger.log( file.getName() + ' ' + file.getId() );
  }
}  

Also, the "Files: list" page has a form at the end that lists the metadata of all the files in the drive, that can be used in case you need but a few ids.

PHP list of specific files in a directory

$it = new RegexIterator(new DirectoryIterator("."), "/\\.xml\$/i"));

foreach ($it as $filename) {
    //...
}

You can also use the recursive variants of the iterators to traverse an entire directory hierarchy.

Docker container will automatically stop after "docker run -d"

According to this answer, adding the -t flag will prevent the container from exiting when running in the background. You can then use docker exec -i -t <image> /bin/bash to get into a shell prompt.

docker run -t -d <image> <command>

It seems that the -t option isn't documented very well, though the help says that it "allocates a pseudo-TTY."

Populate nested array in mongoose

Remove docs reference

if (err) {
    return res.json(500);
}
Project.populate(docs, options, function (err, projects) {
    res.json(projects);
});

This worked for me.

if (err) {
    return res.json(500);
}
Project.populate(options, function (err, projects) {
    res.json(projects);
});

Java: How to check if object is null?

if (yourObject instanceof yourClassName) will evaluate to false if yourObject is null.

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

How to play an android notification sound

Intent intent = new Intent(this, MembersLocation.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra("type",type);
    intent.putExtra("sender",sender);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    String channelId = getString(R.string.default_notification_channel_id);

    Uri Emergency_sound_uri=Uri.parse("android.resource://"+getPackageName()+"/raw/emergency_sound");
   // Uri Default_Sound_uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    if(type.equals("emergency"))
    {
        playSound=Emergency_sound_uri;
    }
    else
    {
        playSound= Settings.System.DEFAULT_NOTIFICATION_URI;
    }

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, channelId)
                    .setSmallIcon(R.drawable.ic_notification)
                    .setContentTitle(title)
                    .setContentText(body)
                    .setSound(playSound, AudioManager.STREAM_NOTIFICATION)
                    .setAutoCancel(true)
                    .setColor(getColor(R.color.dark_red))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setContentIntent(pendingIntent);

   // notificationBuilder.setOngoing(true);//for Android notification swipe delete disabling...

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_HIGH);
        AudioAttributes att = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                .build();
        channel.setSound(Emergency_sound_uri, att);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(channel);
        }
    }

    if (notificationManager != null) {
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

android image button

You just use an ImageButton and make the background whatever you want and set the icon as the src.

<ImageButton
    android:id="@+id/ImageButton01"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/album_icon"
    android:background="@drawable/round_button" />

enter image description here

How to make a back-to-top button using CSS and HTML only?

<a href="#">Start of page</a>

"The link has the href value of "#", which by definition means the start of the current document. Thus there is no need to worry about the correct way of setting up the destination anchor..."

Source

Setting a PHP $_SESSION['var'] using jQuery

It works on firefox, if you change onClick() to click() in javascript part.

_x000D_
_x000D_
$("img.foo").click(function()_x000D_
{_x000D_
    // Get the src of the image_x000D_
    var src = $(this).attr("src");_x000D_
_x000D_
    // Send Ajax request to backend.php, with src set as "img" in the POST data_x000D_
    $.post("/backend.php", {"img": src});_x000D_
});
_x000D_
_x000D_
_x000D_

jQuery replace one class with another

To do this efficiently using jQuery, you can chain it like so:

$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');

For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you're targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow')):

var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');

Also (since there is a js tag), if you wanted to do it in vanilla js:

For modern browsers (See this to see which browsers I'm calling modern)

(assuming one element with class theClassThatsThereNow)

var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');

Or older browsers:

var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can find the answer here: Is there a minlength validation attribute in HTML5?

Therefore this should do the job:

<input pattern=".{6,6}">

COUNT DISTINCT with CONDITIONS

Code counts the unique/distinct combination of Tag & Entry ID when [Entry Id]>0

select count(distinct(concat(tag,entryId)))
from customers
where id>0

In the output it will display the count of unique values Hope this helps

T-SQL stored procedure that accepts multiple Id values

Erland Sommarskog has maintained the authoritative answer to this question for the last 16 years: Arrays and Lists in SQL Server.

There are at least a dozen ways to pass an array or list to a query; each has their own unique pros and cons.

I really can't recommend enough to read the article to learn about the tradeoffs among all these options.

load external URL into modal jquery ui dialog

The following will work out of the box on any site:

_x000D_
_x000D_
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>_x000D_
 _x000D_
    <div class="dialogBox" style="border:1px solid gray;">_x000D_
        <a href="/" class="exampleLink">Test</a>_x000D_
        <!-- TODO: Change above href -->_x000D_
        <!-- NOTE: Must be a local url, not cross domain -->_x000D_
    </div>_x000D_
    _x000D_
    <script type="text/javascript">_x000D_
         _x000D_
_x000D_
        var $modalDialog = $('<div/>', { _x000D_
          'class': 'exampleModal', _x000D_
          'id': 'exampleModal1' _x000D_
        })_x000D_
        .appendTo('body')_x000D_
        .dialog({_x000D_
            resizable: false,_x000D_
            autoOpen: false,_x000D_
            height: 300,_x000D_
            width: 350,_x000D_
            show: 'fold',_x000D_
            buttons: {_x000D_
                "Close": function () {_x000D_
                    $modalDialog.dialog("close");_x000D_
                }_x000D_
            },_x000D_
            modal: true_x000D_
        });_x000D_
_x000D_
        $(function () {_x000D_
            $('a.exampleLink').on('click', function (e) {_x000D_
                e.preventDefault();_x000D_
                // TODO: Undo comments, below_x000D_
                //var url = $('a.exampleLink:first').attr('href');_x000D_
                //$modalDialog.load(url);_x000D_
                $modalDialog.dialog("open");_x000D_
            });_x000D_
        });_x000D_
_x000D_
    </script>
_x000D_
_x000D_
_x000D_

HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h