Programs & Examples On #Onchange

The onChange event gets triggered when the state of an element is changed. Many languages which work with a GUI support some form of a change-event. For example JavaScript and the JavsScript library jQuery (with the .change() function).

Counting Chars in EditText Changed Listener

TextWatcher maritalStatusTextWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        try {
            if (charSequence.length()==0){
                topMaritalStatus.setVisibility(View.GONE);
            }else{
                topMaritalStatus.setVisibility(View.VISIBLE);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
};

jQuery change method on input type="file"

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). Refer: http://api.jquery.com/on/

$('#imageFile').on("change", function(){ uploadFile(); });

React Checkbox not sending onChange

In material ui, state of checkbox can be fetched as

this.refs.complete.state.switched

Trigger change() event when setting <select>'s value with val() function

One thing that I found out (the hard way), is that you should have

$('#selectField').change(function(){
  // some content ...
});

defined BEFORE you are using

$('#selectField').val(10).trigger('change');

or

 $('#selectField').val(10).change();

onChange and onSelect in DropDownList

I'd do it like this jsFiddle example.

JavaScript:

function check(elem) {
    document.getElementById('mySelect1').disabled = !elem.selectedIndex;
}

HTML:

<form>
<select id="mySelect" onChange="check(this);">
<option>No</option>
<option>Yes</option>
</select>

<select id="mySelect1" disabled="disabled" >
<option>Dep1</option>
<option>Dep2</option>
<option>Dep3</option>
<option>Dep4</option>
</select>
</form>

How do I implement onchange of <input type="text"> with jQuery?

<input id="item123" class="firstName" type="text" value="Hello there" data-someattr="CoolExample" />

$(".firstName").on('change keyup paste', function () {
   var element = $(this);
   console.log(element);
   var dataAttribute = $(element).attr("data-someattr");
   console.log("someattr: " + dataAttribute );
});

I recommend use this keyword in order to get access to the entire element so your are able do everything you need with this element.

jQuery - on change input text

This worked for me

var change_temp = "";
$('#url_key').bind('keydown keyup',function(e){
    if(e.type == "keydown"){
        change_temp = $(this).val();
        return;
    }
    if($(this).val() != change_temp){
        // add the code to on change here 
    }

});

select2 onchange event only works once

This is what I am using:

$("#search_code").live('change', function(){
  alert(this.value)
});

For latest jQuery users, this one should work:

$(document.body).on("change","#search_code",function(){
 alert(this.value);
});

android on Text Change Listener

In Kotlin simply use KTX extension function: (It uses TextWatcher)

yourEditText.doOnTextChanged { text, start, count, after -> 
        // action which will be invoked when the text is changing
    }


import core-KTX:

implementation "androidx.core:core-ktx:1.2.0"

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.

Set Label Text with JQuery

I would just query for the for attribute instead of repetitively recursing the DOM tree.

$("input:checkbox").on("change", function() {
    $("label[for='"+this.id+"']").text("TESTTTT");
});

Why can't I change my input value in React even with the onChange listener

If you would like to handle multiple inputs with one handler take a look at my approach where I'm using computed property to get value of the input based on it's name.

import React, { useState } from "react";
import "./style.css";

export default function App() {
  const [state, setState] = useState({
    name: "John Doe",
    email: "[email protected]"
  });

  const handleChange = e => {
    setState({
      [e.target.name]: e.target.value
    });
  };

  return (
    <div>
      <input
        type="text"
        className="name"
        name="name"
        value={state.name}
        onChange={handleChange}
      />

      <input
        type="text"
        className="email"
        name="email"
        value={state.email}
        onChange={handleChange}
      />
    </div>
  );
}

Call Javascript onchange event by programmatically changing textbox value

Onchange is only fired when user enters something by keyboard. A possible workarround could be to first focus the textfield and then change it.

But why not fetch the event when the user clicks on a date? There already must be some javascript.

Can jQuery check whether input content has changed?

I don't think there's a 'simple' solution. You'll probably need to use both the events onKeyUp and onChange so that you also catch when changes are made with the mouse. Every time your code is called you can store the value you've 'seen' on this.seenValue attached right to the field. This should make a little easier.

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

JavaScript code:

  • on mousedown event: set selectedIndex property value to -1
  • on change event: handle event

The only drawback is that when the user clicks on the dropdown list, the currently selected item does not appear selected

Dropdown using javascript onchange

It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).

One way around this is to bind your event handler in javascript (where it should be):

document.getElementById('optionID').onchange = function () {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:

window.changeMessage() {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

?

Redirect on select option in select box

    {{-- dynamic select/dropdown --}}
    <select class="form-control m-bot15" name="district_id" 
        onchange ="location = this.options[this.selectedIndex].value;"
        >
          <option value="">--Select--</option>
          <option value="?">All</option>

            @foreach($location as $district)
                <option  value="?district_id={{ $district->district_id }}" >
                  {{ $district->district }}
                </option> 
            @endforeach   

    </select>

jQuery - Detect value change on hidden input field

So this is way late, but I've discovered an answer, in case it becomes useful to anyone who comes across this thread.

Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.

function setUserID(myValue) {
     $('#userid').val(myValue)
                 .trigger('change');
}

Once that's the case,

$('#userid').change(function(){
      //fire your ajax call  
})

should work as expected.

onchange event on input type=range is not triggering in firefox while dragging

SUMMARY:

I provide here a no-jQuery cross-browser desktop-and-mobile ability to consistently respond to range/slider interactions, something not possible in current browsers. It essentially forces all browsers to emulate IE11's on("change"... event for either their on("change"... or on("input"... events. The new function is...

function onRangeChange(r,f) {
  var n,c,m;
  r.addEventListener("input",function(e){n=1;c=e.target.value;if(c!=m)f(e);m=c;});
  r.addEventListener("change",function(e){if(!n)f(e);});
}

...where r is your range input element and f is your listener. The listener will be called after any interaction that changes the range/slider value but not after interactions that do not change that value, including initial mouse or touch interactions at the current slider position or upon moving off either end of the slider.

Problem:

As of early June 2016, different browsers differ in terms of how they respond to range/slider usage. Five scenarios are relevant:

  1. initial mouse-down (or touch-start) at the current slider position
  2. initial mouse-down (or touch-start) at a new slider position
  3. any subsequent mouse (or touch) movement after 1 or 2 along the slider
  4. any subsequent mouse (or touch) movement after 1 or 2 past either end of the slider
  5. final mouse-up (or touch-end)

The following table shows how at least three different desktop browsers differ in their behaviour with respect to which of the above scenarios they respond to:

table showing browser differences with respect to which events they respond to and when

Solution:

The onRangeChange function provides a consistent and predictable cross-browser response to range/slider interactions. It forces all browsers to behave according to the following table:

table showing behaviour of all browsers using the proposed solution

In IE11, the code essentially allows everything to operate as per the status quo, i.e. it allows the "change" event to function in its standard way and the "input" event is irrelevant as it never fires anyway. In other browsers, the "change" event is effectively silenced (to prevent extra and sometimes not-readily-apparent events from firing). In addition, the "input" event fires its listener only when the range/slider's value changes. For some browsers (e.g. Firefox) this occurs because the listener is effectively silenced in scenarios 1, 4 and 5 from the above list.

(If you truly require a listener to be activated in either scenario 1, 4 and/or 5 you could try incorporating "mousedown"/"touchstart", "mousemove"/"touchmove" and/or "mouseup"/"touchend" events. Such a solution is beyond the scope of this answer.)

Functionality in Mobile Browsers:

I have tested this code in desktop browsers but not in any mobile browsers. However, in another answer on this page MBourne has shown that my solution here "...appears to work in every browser I could find (Win desktop: IE, Chrome, Opera, FF; Android Chrome, Opera and FF, iOS Safari)". (Thanks MBourne.)

Usage:

To use this solution, include the onRangeChange function from the summary above (simplified/minified) or the demo code snippet below (functionally identical but more self-explanatory) in your own code. Invoke it as follows:

onRangeChange(myRangeInputElmt, myListener);

where myRangeInputElmt is your desired <input type="range"> DOM element and myListener is the listener/handler function you want invoked upon "change"-like events.

Your listener may be parameter-less if desired or may use the event parameter, i.e. either of the following would work, depending on your needs:

var myListener = function() {...

or

var myListener = function(evt) {...

(Removing the event listener from the input element (e.g. using removeEventListener) is not addressed in this answer.)

Demo Description:

In the code snippet below, the function onRangeChange provides the universal solution. The rest of the code is simply an example to demonstrate its use. Any variable that begins with my... is irrelevant to the universal solution and is only present for the sake of the demo.

The demo shows the range/slider value as well as the number of times the standard "change", "input" and custom "onRangeChange" events have fired (rows A, B and C respectively). When running this snippet in different browsers, note the following as you interact with the range/slider:

  • In IE11, the values in rows A and C both change in scenarios 2 and 3 above while row B never changes.
  • In Chrome and Safari, the values in rows B and C both change in scenarios 2 and 3 while row A changes only for scenario 5.
  • In Firefox, the value in row A changes only for scenario 5, row B changes for all five scenarios, and row C changes only for scenarios 2 and 3.
  • In all of the above browsers, the changes in row C (the proposed solution) are identical, i.e. only for scenarios 2 and 3.

Demo Code:

_x000D_
_x000D_
// main function for emulating IE11's "change" event:_x000D_
_x000D_
function onRangeChange(rangeInputElmt, listener) {_x000D_
_x000D_
  var inputEvtHasNeverFired = true;_x000D_
_x000D_
  var rangeValue = {current: undefined, mostRecent: undefined};_x000D_
  _x000D_
  rangeInputElmt.addEventListener("input", function(evt) {_x000D_
    inputEvtHasNeverFired = false;_x000D_
    rangeValue.current = evt.target.value;_x000D_
    if (rangeValue.current !== rangeValue.mostRecent) {_x000D_
      listener(evt);_x000D_
    }_x000D_
    rangeValue.mostRecent = rangeValue.current;_x000D_
  });_x000D_
_x000D_
  rangeInputElmt.addEventListener("change", function(evt) {_x000D_
    if (inputEvtHasNeverFired) {_x000D_
      listener(evt);_x000D_
    }_x000D_
  }); _x000D_
_x000D_
}_x000D_
_x000D_
// example usage:_x000D_
_x000D_
var myRangeInputElmt = document.querySelector("input"          );_x000D_
var myRangeValPar    = document.querySelector("#rangeValPar"   );_x000D_
var myNumChgEvtsCell = document.querySelector("#numChgEvtsCell");_x000D_
var myNumInpEvtsCell = document.querySelector("#numInpEvtsCell");_x000D_
var myNumCusEvtsCell = document.querySelector("#numCusEvtsCell");_x000D_
_x000D_
var myNumEvts = {input: 0, change: 0, custom: 0};_x000D_
_x000D_
var myUpdate = function() {_x000D_
  myNumChgEvtsCell.innerHTML = myNumEvts["change"];_x000D_
  myNumInpEvtsCell.innerHTML = myNumEvts["input" ];_x000D_
  myNumCusEvtsCell.innerHTML = myNumEvts["custom"];_x000D_
};_x000D_
_x000D_
["input", "change"].forEach(function(myEvtType) {_x000D_
  myRangeInputElmt.addEventListener(myEvtType,  function() {_x000D_
    myNumEvts[myEvtType] += 1;_x000D_
    myUpdate();_x000D_
  });_x000D_
});_x000D_
_x000D_
var myListener = function(myEvt) {_x000D_
  myNumEvts["custom"] += 1;_x000D_
  myRangeValPar.innerHTML = "range value: " + myEvt.target.value;_x000D_
  myUpdate();_x000D_
};_x000D_
_x000D_
onRangeChange(myRangeInputElmt, myListener);
_x000D_
table {_x000D_
  border-collapse: collapse;  _x000D_
}_x000D_
th, td {_x000D_
  text-align: left;_x000D_
  border: solid black 1px;_x000D_
  padding: 5px 15px;_x000D_
}
_x000D_
<input type="range"/>_x000D_
<p id="rangeValPar">range value: 50</p>_x000D_
<table>_x000D_
  <tr><th>row</th><th>event type                     </th><th>number of events    </th><tr>_x000D_
  <tr><td>A</td><td>standard "change" events         </td><td id="numChgEvtsCell">0</td></tr>_x000D_
  <tr><td>B</td><td>standard "input" events          </td><td id="numInpEvtsCell">0</td></tr>_x000D_
  <tr><td>C</td><td>new custom "onRangeChange" events</td><td id="numCusEvtsCell">0</td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Credit:

While the implementation here is largely my own, it was inspired by MBourne's answer. That other answer suggested that the "input" and "change" events could be merged and that the resulting code would work in both desktop and mobile browsers. However, the code in that answer results in hidden "extra" events being fired, which in and of itself is problematic, and the events fired differ between browsers, a further problem. My implementation here solves those problems.

Keywords:

JavaScript input type range slider events change input browser compatability cross-browser desktop mobile no-jQuery

Onchange open URL via select - jQuery

Here's how i'd do it

<select id="urlSelect" onchange="window.location = jQuery('#urlSelect option:selected').val();">
 <option value="http://www.yadayadayada.com">Great Site</option>
 <option value="http://www.stackoverflow.com">Better Site</option>
</select>

Jquery select change not firing

This works for me!

$('#<%= ddlstuff.ClientID %>').change(function () {
    alert('Change Happened');
     $('#<%= txtBoxToClear.ClientID %>').val('');
});

How do I make curl ignore the proxy?

I have http_proxy and https_proxy are defined. I don't want to unset and set again those environments but --noproxy '*' works perfectly for me.

curl --noproxy '*' -XGET 172.17.0.2:9200
{
  "status" : 200,
  "name" : "Medusa",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "1.5.0",
    "build_hash" : "544816042d40151d3ce4ba4f95399d7860dc2e92",
    "build_timestamp" : "2015-03-23T14:30:58Z",
    "build_snapshot" : false,
    "lucene_version" : "4.10.4"
  },
  "tagline" : "You Know, for Search"
}

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

As for #2, in my case it magically came to life after replacing

<body>

tag with

<h:body>

After having done several (simpler, to be honest) JSF projects, I couldn't remember of doing anything different setting it up now, and I got this kind of error for the first time. I was making a very basic login page (username, password, user Bean...) and set up everything like usual. The only difference I spotted is tags aforementioned. Maybe someone finds this useful.

tomcat - CATALINA_BASE and CATALINA_HOME variables

That is the parent folder of bin which contains tomcat.exe file:

CATALINA_HOME='C:\Program Files\Apache Software Foundation\Tomcat 6.0'

CATALINA_BASE is the same as CATALINA_HOME.

Make column fixed position in bootstrap

in Bootstrap 3 class="affix" works, but in Bootstrap 4 it does not. I solved this problem in Bootstrap 4 with class="sticky-top" (using position: fixed in CSS has its own problems)

code will be something like this:

<div class="row">
    <div class="col-lg-3">
        <div class="sticky-top">
            Fixed content
        </div>
    </div>
    <div class="col-lg-9">
        Normal scrollable content
    </div>
</div>

jQuery map vs. each

The each method is meant to be an immutable iterator, where as the map method can be used as an iterator, but is really meant to manipulate the supplied array and return a new array.

Another important thing to note is that the each function returns the original array while the map function returns a new array. If you overuse the return value of the map function you can potentially waste a lot of memory.

For example:

var items = [1,2,3,4];

$.each(items, function() {
  alert('this is ' + this);
});

var newItems = $.map(items, function(i) {
  return i + 1;
});
// newItems is [2,3,4,5]

You can also use the map function to remove an item from an array. For example:

var items = [0,1,2,3,4,5,6,7,8,9];

var itemsLessThanEqualFive = $.map(items, function(i) {
  // removes all items > 5
  if (i > 5) 
    return null;
  return i;
});
// itemsLessThanEqualFive = [0,1,2,3,4,5]

You'll also note that the this is not mapped in the map function. You will have to supply the first parameter in the callback (eg we used i above). Ironically, the callback arguments used in the each method are the reverse of the callback arguments in the map function so be careful.

map(arr, function(elem, index) {});
// versus 
each(arr, function(index, elem) {});

Created Button Click Event c#

    public MainWindow()
    {
        // This button needs to exist on your form.
        myButton.Click += myButton_Click;
    }

    void myButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Message here");
        this.Close();
    }

In Python, what happens when you import inside of a function?

Does it re-import every time the function is run?

No; or rather, Python modules are essentially cached every time they are imported, so importing a second (or third, or fourth...) time doesn't actually force them to go through the whole import process again. 1

Does it import once at the beginning whether or not the function is run?

No, it is only imported if and when the function is executed. 2, 3

As for the benefits: it depends, I guess. If you may only run a function very rarely and don't need the module imported anywhere else, it may be beneficial to only import it in that function. Or if there is a name clash or other reason you don't want the module or symbols from the module available everywhere, you may only want to import it in a specific function. (Of course, there's always from my_module import my_function as f for those cases.)

In general practice, it's probably not that beneficial. In fact, most Python style guides encourage programmers to place all imports at the beginning of the module file.

What is SELF JOIN and when would you use it?

SQL self-join simply is a normal join which is used to join a table to itself.

Example:

Select *
FROM Table t1, Table t2
WHERE t1.Id = t2.ID

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

Try going to IIS and checking to make sure the App Pool you are using is started. A lot of times, you will produce an error that shuts down the app pool. You just need to right click and Start and you should be good to go.

Java Array Sort descending?

Another solution is that if you're making use of the Comparable interface you can switch the output values which you had specified in your compareTo(Object bCompared).

For Example :

public int compareTo(freq arg0) 
{
    int ret=0;
    if(this.magnitude>arg0.magnitude)
        ret= 1;
    else if (this.magnitude==arg0.magnitude)
        ret= 0;
    else if (this.magnitude<arg0.magnitude)
        ret= -1;
    return ret;
}

Where magnitude is an attribute with datatype double in my program. This was sorting my defined class freq in reverse order by it's magnitude. So in order to correct that, you switch the values returned by the < and >. This gives you the following :

public int compareTo(freq arg0) 
{
    int ret=0;
    if(this.magnitude>arg0.magnitude)
        ret= -1;
    else if (this.magnitude==arg0.magnitude)
        ret= 0;
    else if (this.magnitude<arg0.magnitude)
        ret= 1;
    return ret;
}

To make use of this compareTo, we simply call Arrays.sort(mFreq) which will give you the sorted array freq [] mFreq.

The beauty (in my opinion) of this solution is that it can be used to sort user defined classes, and even more than that sort them by a specific attribute. If implementation of a Comparable interface sounds daunting to you, I'd encourage you not to think that way, it actually isn't. This link on how to implement comparable made things much easier for me. Hoping persons can make use of this solution, and that your joy will even be comparable to mine.

How to detect when keyboard is shown and hidden

There is a CocoaPods to facilitate the observation on NSNotificationCentr for the keyboard's visibility here: https://github.com/levantAJ/Keyhi

pod 'Keyhi'

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

How can I set the request header for curl?

To pass multiple headers in a curl request you simply add additional -H or --header to your curl command.

Example

//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL

//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json'  https://www.example.com

Going Further

For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:

  • -A (or --user-agent): set "User-Agent" field.
  • -b (or --cookie): set "Cookie" field.
  • -e (or --referer): set "Referer" field.
  • -H (or --header): set "Header" field

For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.

    $ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
    $ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com

How to fast get Hardware-ID in C#?

We use a combination of the processor id number (ProcessorID) from Win32_processor and the universally unique identifier (UUID) from Win32_ComputerSystemProduct:

ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    processorId = mo["ProcessorID"] as string;
}

mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    systemId = mo["UUID"] as string;
}

var compIdStr = $"{processorId}{systemId}";

Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor") and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:

  • To be filled by O.E.M.
  • None
  • Default string

Therefore, it is worth considering this situation.

Also keep in mind that the ProcessorID number may be the same on different computers.

How to determine CPU and memory consumption from inside a process?

Linux

In Linux, this information is available in the /proc file system. I'm not a big fan of the text file format used, as each Linux distribution seems to customize at least one important file. A quick look as the source to 'ps' reveals the mess.

But here is where to find the information you seek:

/proc/meminfo contains the majority of the system-wide information you seek. Here it looks like on my system; I think you are interested in MemTotal, MemFree, SwapTotal, and SwapFree:

Anderson cxc # more /proc/meminfo
MemTotal:      4083948 kB
MemFree:       2198520 kB
Buffers:         82080 kB
Cached:        1141460 kB
SwapCached:          0 kB
Active:        1137960 kB
Inactive:       608588 kB
HighTotal:     3276672 kB
HighFree:      1607744 kB
LowTotal:       807276 kB
LowFree:        590776 kB
SwapTotal:     2096440 kB
SwapFree:      2096440 kB
Dirty:              32 kB
Writeback:           0 kB
AnonPages:      523252 kB
Mapped:          93560 kB
Slab:            52880 kB
SReclaimable:    24652 kB
SUnreclaim:      28228 kB
PageTables:       2284 kB
NFS_Unstable:        0 kB
Bounce:              0 kB
CommitLimit:   4138412 kB
Committed_AS:  1845072 kB
VmallocTotal:   118776 kB
VmallocUsed:      3964 kB
VmallocChunk:   112860 kB
HugePages_Total:     0
HugePages_Free:      0
HugePages_Rsvd:      0
Hugepagesize:     2048 kB

For CPU utilization, you have to do a little work. Linux makes available overall CPU utilization since system start; this probably isn't what you are interested in. If you want to know what the CPU utilization was for the last second, or 10 seconds, then you need to query the information and calculate it yourself.

The information is available in /proc/stat, which is documented pretty well at http://www.linuxhowtos.org/System/procstat.htm; here is what it looks like on my 4-core box:

Anderson cxc #  more /proc/stat
cpu  2329889 0 2364567 1063530460 9034 9463 96111 0
cpu0 572526 0 636532 265864398 2928 1621 6899 0
cpu1 590441 0 531079 265949732 4763 351 8522 0
cpu2 562983 0 645163 265796890 682 7490 71650 0
cpu3 603938 0 551790 265919440 660 0 9040 0
intr 37124247
ctxt 50795173133
btime 1218807985
processes 116889
procs_running 1
procs_blocked 0

First, you need to determine how many CPUs (or processors, or processing cores) are available in the system. To do this, count the number of 'cpuN' entries, where N starts at 0 and increments. Don't count the 'cpu' line, which is a combination of the cpuN lines. In my example, you can see cpu0 through cpu3, for a total of 4 processors. From now on, you can ignore cpu0..cpu3, and focus only on the 'cpu' line.

Next, you need to know that the fourth number in these lines is a measure of idle time, and thus the fourth number on the 'cpu' line is the total idle time for all processors since boot time. This time is measured in Linux "jiffies", which are 1/100 of a second each.

But you don't care about the total idle time; you care about the idle time in a given period, e.g., the last second. Do calculate that, you need to read this file twice, 1 second apart.Then you can do a diff of the fourth value of the line. For example, if you take a sample and get:

cpu  2330047 0 2365006 1063853632 9035 9463 96114 0

Then one second later you get this sample:

cpu  2330047 0 2365007 1063854028 9035 9463 96114 0

Subtract the two numbers, and you get a diff of 396, which means that your CPU had been idle for 3.96 seconds out of the last 1.00 second. The trick, of course, is that you need to divide by the number of processors. 3.96 / 4 = 0.99, and there is your idle percentage; 99% idle, and 1% busy.

In my code, I have a ring buffer of 360 entries, and I read this file every second. That lets me quickly calculate the CPU utilization for 1 second, 10 seconds, etc., all the way up to 1 hour.

For the process-specific information, you have to look in /proc/pid; if you don't care abut your pid, you can look in /proc/self.

CPU used by your process is available in /proc/self/stat. This is an odd-looking file consisting of a single line; for example:

19340 (whatever) S 19115 19115 3084 34816 19115 4202752 118200 607 0 0 770 384 2
 7 20 0 77 0 266764385 692477952 105074 4294967295 134512640 146462952 321468364
8 3214683328 4294960144 0 2147221247 268439552 1276 4294967295 0 0 17 0 0 0 0

The important data here are the 13th and 14th tokens (0 and 770 here). The 13th token is the number of jiffies that the process has executed in user mode, and the 14th is the number of jiffies that the process has executed in kernel mode. Add the two together, and you have its total CPU utilization.

Again, you will have to sample this file periodically, and calculate the diff, in order to determine the process's CPU usage over time.

Edit: remember that when you calculate your process's CPU utilization, you have to take into account 1) the number of threads in your process, and 2) the number of processors in the system. For example, if your single-threaded process is using only 25% of the CPU, that could be good or bad. Good on a single-processor system, but bad on a 4-processor system; this means that your process is running constantly, and using 100% of the CPU cycles available to it.

For the process-specific memory information, you ahve to look at /proc/self/status, which looks like this:

Name:   whatever
State:  S (sleeping)
Tgid:   19340
Pid:    19340
PPid:   19115
TracerPid:      0
Uid:    0       0       0       0
Gid:    0       0       0       0
FDSize: 256
Groups: 0 1 2 3 4 6 10 11 20 26 27
VmPeak:   676252 kB
VmSize:   651352 kB
VmLck:         0 kB
VmHWM:    420300 kB
VmRSS:    420296 kB
VmData:   581028 kB
VmStk:       112 kB
VmExe:     11672 kB
VmLib:     76608 kB
VmPTE:      1244 kB
Threads:        77
SigQ:   0/36864
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: fffffffe7ffbfeff
SigIgn: 0000000010001000
SigCgt: 20000001800004fc
CapInh: 0000000000000000
CapPrm: 00000000ffffffff
CapEff: 00000000fffffeff
Cpus_allowed:   0f
Mems_allowed:   1
voluntary_ctxt_switches:        6518
nonvoluntary_ctxt_switches:     6598

The entries that start with 'Vm' are the interesting ones:

  • VmPeak is the maximum virtual memory space used by the process, in kB (1024 bytes).
  • VmSize is the current virtual memory space used by the process, in kB. In my example, it's pretty large: 651,352 kB, or about 636 megabytes.
  • VmRss is the amount of memory that have been mapped into the process' address space, or its resident set size. This is substantially smaller (420,296 kB, or about 410 megabytes). The difference: my program has mapped 636 MB via mmap(), but has only accessed 410 MB of it, and thus only 410 MB of pages have been assigned to it.

The only item I'm not sure about is Swapspace currently used by my process. I don't know if this is available.

Difference between int32, int, int32_t, int8 and int8_t

Always keep in mind that 'size' is variable if not explicitly specified so if you declare

 int i = 10;

On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).

In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across

 typedef short INT16;
 typedef int INT32;
 typedef long INT64; 

Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.

On a windows based system, you may see entries in stdin.h header file as

 typedef signed char       int8_t;
 typedef signed short      int16_t;
 typedef signed int        int32_t;
 typedef unsigned char     uint8_t;

There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.

Get a Div Value in JQuery

You can do get id value by using

_x000D_
_x000D_
test_alert = $('#myDiv').val();_x000D_
alert(test_alert);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"><p>Some Text</p></div>
_x000D_
_x000D_
_x000D_

"insufficient memory for the Java Runtime Environment " message in eclipse

I know the question talking about eclipse but i got the similar issue many times with Intellij as well and the solution for it was easy .. Just run the 64 bit exe not the 32 one which is always the default one.

Converting milliseconds to minutes and seconds with Javascript

this code will do a better job if you want to show hours, and centiseconds or miliseconds after seconds like 1:02:32.21 and if used in a cell phone the timer will show correct timing even after screen lock.

_x000D_
_x000D_
<div id="timer" style="font-family:monospace;">00:00<small>.00</small></div>_x000D_
_x000D_
<script>_x000D_
var d = new Date();_x000D_
var n = d.getTime();_x000D_
var startTime = n;_x000D_
_x000D_
var tm=0;_x000D_
function updateTimer(){_x000D_
  d = new Date();_x000D_
  n = d.getTime();_x000D_
  var currentTime = n;  _x000D_
  tm = (currentTime-startTime);_x000D_
  _x000D_
  //tm +=1; _x000D_
  // si el timer cuenta en centesimas de segundo_x000D_
  //tm = tm*10;_x000D_
  _x000D_
  var hours = Math.floor(tm / 1000 / 60 / 60);_x000D_
  var minutes = Math.floor(tm / 60000) % 60;_x000D_
  var seconds =  ((tm / 1000) % 60);_x000D_
  // saca los decimales ej 2 d{0,2}_x000D_
  var seconds = seconds.toString().match(/^-?\d+(?:\.\d{0,-1})?/)[0];_x000D_
  var miliseconds = ("00" + tm).slice(-3);_x000D_
  var centiseconds;_x000D_
_x000D_
  _x000D_
  // si el timer cuenta en centesimas de segundo_x000D_
  //tm = tm/10;_x000D_
_x000D_
_x000D_
  centiseconds = miliseconds/10;_x000D_
  centiseconds = (centiseconds).toString().match(/^-?\d+(?:\.\d{0,-1})?/)[0];_x000D_
_x000D_
  minutes = (minutes < 10 ? '0' : '') + minutes;_x000D_
  seconds = (seconds < 10 ? '0' : '') + seconds;_x000D_
  centiseconds = (centiseconds < 10 ? '0' : '') + centiseconds;_x000D_
  hours = hours + (hours > 0 ? ':' : '');_x000D_
  if (hours==0){_x000D_
    hours='';_x000D_
  }_x000D_
_x000D_
  document.getElementById("timer").innerHTML = hours + minutes + ':' + seconds + '<small>.' + centiseconds + '</small>';_x000D_
}_x000D_
_x000D_
var timerInterval = setInterval(updateTimer, 10);_x000D_
// clearInterval(timerInterval);_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to make PopUp window in java

Hmm it has been a little while but from what I remember...
If you want a custom window you can just make a new frame and make it show up just like you would with the main window. Java also has a great dialog library that you can check out here:

How to Make Dialogs

That may be able to give you the functionality you are looking for with a whole lot less effort.

Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
                    frame,
                    "Complete the sentence:\n"
                    + "\"Green eggs and...\"",
                    "Customized Dialog",
                    JOptionPane.PLAIN_MESSAGE,
                    icon,
                    possibilities,
                    "ham");

//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
    setLabel("Green eggs and... " + s + "!");
    return;
}

//If you're here, the return value was null/empty.
setLabel("Come on, finish the sentence!");

If you do not care to limit the user's choices, you can either use a form of the showInputDialog method that takes fewer arguments or specify null for the array of objects. In the Java look and feel, substituting null for possibilities results in a dialog that has a text field and looks like this:

Send data from activity to fragment in Android

the better approach for sending data from activity class to fragment is passing via setter methods. Like

FragmentClass fragmentClass = new FragmentClass();
fragmentClass.setMyList(mylist);
fragmentClass.setMyString(myString);
fragmentClass.setMyMap(myMap);

and get these data from the class easily.

How can I copy the output of a command directly into my clipboard?

Add this to to your ~/.bashrc:

# Now `cclip' copies and `clipp' pastes'
alias cclip='xclip -selection clipboard'
alias clipp='xclip -selection clipboard -o'

Now clipp pastes and cclip copies — but you can also do fancier stuff:

clipp | sed 's/^/    /' | cclip

↑ indents your clipboard; good for sites without stack overflow's { } button

You can add it by running this:

printf "\nalias clipp=\'xclip -selection c -o\'\n" >> ~/.bashrc
printf "\nalias cclip=\'xclip -selection c -i\'\n" >> ~/.bashrc

Python: How to create a unique file name?

I didn't think your question was very clear, but if all you need is a unique file name...

import uuid

unique_filename = str(uuid.uuid4())

.datepicker('setdate') issues, in jQuery

If you would like to support really old browsers you should parse the date string, since using the ISO8601 date format with the Date constructor is not supported pre IE9:

var queryDate = '2009-11-01',
    dateParts = queryDate.match(/(\d+)/g)
    realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);  
                                    // months are 0-based!
// For >= IE9
var realDate = new Date('2009-11-01');  

$('#datePicker').datepicker({ dateFormat: 'yy-mm-dd' }); // format to show
$('#datePicker').datepicker('setDate', realDate);

Check the above example here.

JSON Naming Convention (snake_case, camelCase or PascalCase)

Seems that there's enough variation that people go out of their way to allow conversion from all conventions to others: http://www.cowtowncoder.com/blog/archives/cat_json.html

Notably, the mentioned Jackson JSON parser prefers bean_naming.

.m2 , settings.xml in Ubuntu

.m2 directory on linux box usually would be $HOME/.m2

you could get the $HOME :

echo $HOME

or simply:

cd <enter>

to go to your home directory.

other information from maven site: http://maven.apache.org/download.html#Installation

Visual Studio replace tab with 4 spaces?

If you don't see the formatting option, you can do Tools->Import and Export settings to import the missing one.

ORA-01438: value larger than specified precision allows for this column

Further to previous answers, you should note that a column defined as VARCHARS(10) will store 10 bytes, not 10 characters unless you define it as VARCHAR2(10 CHAR)

[The OP's question seems to be number related... this is just in case anyone else has a similar issue]

What's a simple way to get a text input popup dialog box on an iPhone

Add views to a UIAlertView like this. In iOS 5 there are some "magic" things that do it for you (but that's all under NDA).

How to sort by Date with DataTables jquery plugin?

I Have 10 Columns in my table and there is 2 columns of dates, 2nd column and 4th column is of US Date, so this is worked for me fine. Just paste this code at last in your script section in same sequence.

   jQuery.fn.dataTableExt.oSort['us_date-asc'] = function (a, b) {
        var x = new Date(a),
            y = new Date(b);
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    };


    jQuery.fn.dataTableExt.oSort['us_date-desc'] = function (a, b) {
        var x = new Date(a),
            y = new Date(b);
        return ((x < y) ? 1 : ((x > y) ? -1 : 0));
    };


    $('#tblPoSetupGrid').dataTable({
        columnDefs: [
            { type: 'us_date', targets: 3 },
            { type: 'us_date', targets: 1 }
        ]

    });

Selecting multiple columns with linq query and lambda expression

Not sure what you table structure is like but see below.

public NamePriceModel[] AllProducts()
{
    try
    {
        using (UserDataDataContext db = new UserDataDataContext())
        {
            return db.mrobProducts
                .Where(x => x.Status == 1)
                .Select(x => new NamePriceModel { 
                    Name = x.Name, 
                    Id = x.Id, 
                    Price = x.Price
                })
                .OrderBy(x => x.Id)
                .ToArray();
         }
     }
     catch
     {
         return null;
     }
 }

This would return an array of type anonymous with the members you require.

Update:

Create a new class.

public class NamePriceModel 
{
    public string Name {get; set;}
    public decimal? Price {get; set;}
    public int Id {get; set;}
}

I've modified the query above to return this as well and you should change your method from returning string[] to returning NamePriceModel[].

CSS Inset Borders

You can do this:

.thing {
  border: 2px solid transparent;
}
.thing:hover {
  border: 2px solid green;
}

Check which element has been clicked with jQuery

Another option can be to utilize the tagName property of the e.target. It doesn't apply exactly here, but let's say I have a class of something that's applied to either a DIV or an A tag, and I want to see if that class was clicked, and determine whether it was the DIV or the A that was clicked. I can do something like:

$('.example-class').click(function(e){
  if ((e.target.tagName.toLowerCase()) == 'a') {
    console.log('You clicked an A element.');
  } else { // DIV, we assume in this example
    console.log('You clicked a DIV element.');
  }
});

Warning :-Presenting view controllers on detached view controllers is discouraged

Make sure you have a root view controller to start with. You can set it in didFinishLaunchingWithOptions.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    [window setRootViewController:viewController];
}

Converting a String to Object

String extends Object, which means an Object. Object o = a; If you really want to get as Object, you may do like below.

String s = "Hi";

Object a =s;

how to use sqltransaction in c#

Well, I don't understand why are you used transaction in case when you make a select.

Transaction is useful when you make changes (add, edit or delete) data from database.

Remove transaction unless you use insert, update or delete statements

How to delete a workspace in Perforce (using p4v)?

If you have successfully deleted from workspace tab but still it is showing in drop down menu. Then also you can successfully remove that by following these steps:

  1. Go to C:/Users/user_name/.p4qt

user_name will be your username of your computer

  1. Inside 001Clients folder WorkspaceSettings.xml file will be there.

There will be two tag

  1. varName = "RecentlyUsedWorkspaces" remove the deleted workspace tag

  2. A propertyList tag will be there with varName=deleted_workspace_name delete that tag.

from drop down menu workspace name will be deleted

Removing Java 8 JDK from Mac

I nuked everything Java, JDK, and oracle. I was running Java 8 on OSX El Capitan

Other answers were missing tons of stuff. This answer covers a lot more bases.

Good bye, shovelware.

sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.Helper-Tool.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist
sudo rm -rf /System/Library/Frameworks/JavaVM.framework
sudo rm -rf /var/db/receipts/com.oracle.jdk8u65.bom
sudo rm -rf /var/db/receipts/com.oracle.jdk8u65.plist
sudo rm -rf /var/db/receipts/com.oracle.jre.bom
sudo rm -rf /var/db/receipts/com.oracle.jre.plist
sudo rm -rf /var/root/Library/Preferences/com.oracle.javadeployment.plist
sudo rm -rf ~/Library/Preferences/com.oracle.java.JavaAppletPlugin.plist
sudo rm -rf ~/Library/Preferences/com.oracle.javadeployment.plist
sudo rm -rf ~/.oracle_jre_usage

In which conda environment is Jupyter executing?

Because none of the answers above worked for me, I write here the solution that finally solved my problem on Ubuntu. My problem was:
I did the following steps:

  1. Activate my environment: conda activate MyEnv
  2. Start jupyter notebook:jupyter notebook

Although MyEnv was active in the terminal and had an asterix when writing conda env list, but jupyter notebook was started with the base environment. Installing nb_conda and ipykernel didn't solve the problem for me either. Additionally, the conda tab wasn't appearing in jupyter notebook and also clicking on the kernels or going to the menu Kernel->Change Kernel didn't show the kernel MyEnv.
Solution was: install the jupyter_environment_kernel in MyEnv environment:

pip install environment_kernels

After that when starting jupyter notebook, it is started with the right environment. You can also switch between environments without stopping the kernel, by going to the menu Kernel->Change Kernel and selecting the desired kernel.

Why is my JavaScript function sometimes "not defined"?

Solved by removing a "async" load:

  <script type="text/javascript" src="{% static 'js/my_js_file.js' %}" async></script>

changed for:

  <script type="text/javascript" src="{% static 'js/my_js_file.js' %}"></script>

Why is printing "B" dramatically slower than printing "#"?

Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.

  1. First Matrix: O and # = 6.03 seconds
  2. Second Matrix: O and B = 50.97 seconds

Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("B");
        }
        if(j%100==0){               //Adding a line break in second loop      
            System.out.println();
        }                    
    }
    System.out.println("");                
}

Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

NetBeans Editor Settings

Python PDF library

There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.

How to reset Jenkins security settings from the command line?

I had a similar issue, and following reply from ArtB,

I found that my user didn't have the proper configurations. so what I did:

Note: manually modifying such XML files is risky. Do it at your own risk. Since I was already locked out, I didn't have much to lose. AFAIK Worst case I would have deleted the ~/.jenkins/config.xml file as prev post mentioned.

**> 1. ssh to the jenkins machine

  1. cd ~/.jenkins (I guess that some installations put it under /var/lib/jenkins/config.xml, but not in my case )
  2. vi config.xml, and under authorizationStrategy xml tag, add the below section (just used my username instead of "put-your-username")
  3. restart jenkins. in my case as root service tomcat7 stop; ; service tomcat7 start
  4. Try to login again. (worked for me)**

under

add:

<permission>hudson.model.Computer.Build:put-your-username</permission>
<permission>hudson.model.Computer.Configure:put-your-username</permission>
<permission>hudson.model.Computer.Connect:put-your-username</permission>
<permission>hudson.model.Computer.Create:put-your-username</permission>
<permission>hudson.model.Computer.Delete:put-your-username</permission>
<permission>hudson.model.Computer.Disconnect:put-your-username</permission>
<permission>hudson.model.Hudson.Administer:put-your-username</permission>
<permission>hudson.model.Hudson.ConfigureUpdateCenter:put-your-username</permission>
<permission>hudson.model.Hudson.Read:put-your-username</permission>
<permission>hudson.model.Hudson.RunScripts:put-your-username</permission>
<permission>hudson.model.Hudson.UploadPlugins:put-your-username</permission>
<permission>hudson.model.Item.Build:put-your-username</permission>
<permission>hudson.model.Item.Cancel:put-your-username</permission>
<permission>hudson.model.Item.Configure:put-your-username</permission>
<permission>hudson.model.Item.Create:put-your-username</permission>
<permission>hudson.model.Item.Delete:put-your-username</permission>
<permission>hudson.model.Item.Discover:put-your-username</permission>
<permission>hudson.model.Item.Read:put-your-username</permission>
<permission>hudson.model.Item.Workspace:put-your-username</permission>
<permission>hudson.model.Run.Delete:put-your-username</permission>
<permission>hudson.model.Run.Update:put-your-username</permission>
<permission>hudson.model.View.Configure:put-your-username</permission>
<permission>hudson.model.View.Create:put-your-username</permission>
<permission>hudson.model.View.Delete:put-your-username</permission>
<permission>hudson.model.View.Read:put-your-username</permission>
<permission>hudson.scm.SCM.Tag:put-your-username</permission>

Now, you can go to different directions. For example I had github oauth integration, so I could have tried to replace the authorizationStrategy with something like below:

Note:, It worked in my case because I had a specific github oauth plugin that was already configured. So it is more risky than the previous solution.

  <authorizationStrategy class="org.jenkinsci.plugins.GithubAuthorizationStrategy" plugin="[email protected]">
    <rootACL>
      <organizationNameList class="linked-list">
        <string></string>
      </organizationNameList>
      <adminUserNameList class="linked-list">
        <string>put-your-username</string>
        <string>username2</string>
        <string>username3</string>
        <string>username_4_etc_put_username_that_will_become_administrator</string>
      </adminUserNameList>
      <authenticatedUserReadPermission>true</authenticatedUserReadPermission>
      <allowGithubWebHookPermission>false</allowGithubWebHookPermission>
      <allowCcTrayPermission>false</allowCcTrayPermission>
      <allowAnonymousReadPermission>false</allowAnonymousReadPermission>
    </rootACL>
  </authorizationStrategy>

C# Help reading foreign characters using StreamReader

File.OpenText() always uses an UTF-8 StreamReader implicitly. Create your own StreamReader instance instead and specify the desired encoding. like

using (StreamReader reader =  new StreamReader(@"C:\test.txt", Encoding.Default)
 {
 // ...
 }

Search and replace part of string in database

You can do it with an UPDATE statement setting the value with a REPLACE

UPDATE
    Table
SET
    Column = Replace(Column, 'find value', 'replacement value')
WHERE
    xxx

You will want to be extremely careful when doing this! I highly recommend doing a backup first.

PHP if not statements

You're saying "if it's not set or it's different from add or it's different from delete". You realize that a != x && a != y, with x != y is necessarily false since a cannot be simultaneously two different values.

How to get and set the current web page scroll position?

You're looking for the document.documentElement.scrollTop property.

Group By Eloquent ORM

Laravel 5

This is working for me (i use laravel 5.6).

$collection = MyModel::all()->groupBy('column');

If you want to convert the collection to plain php array, you can use toArray()

$array = MyModel::all()->groupBy('column')->toArray();

What's the most concise way to read query parameters in AngularJS?

Just a precision to Ellis Whitehead's answer. $locationProvider.html5Mode(true); won't work with new version of angularjs without specifying the base URL for the application with a <base href=""> tag or setting the parameter requireBase to false

From the doc :

If you configure $location to use html5Mode (history.pushState), you need to specify the base URL for the application with a tag or configure $locationProvider to not require a base tag by passing a definition object with requireBase:false to $locationProvider.html5Mode():

$locationProvider.html5Mode({
  enabled: true,
  requireBase: false
});

Stock ticker symbol lookup API

Google Finance does let you retrieve up to 100 stock quotes at once using the following URL:

www.google.com/finance/info?infotype=infoquoteall&q=[ticker1],[ticker2],...,[tickern]

For example:

www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG

Someone has deciphered the available fields here:

http://qsb-mac.googlecode.com/svn/trunk/Vermilion/Modules/StockQuoter/StockQuoter.py

The current price ("l") is real-time and the delay is on par with Yahoo Finance. There are a few quirks you should be aware of. A handful of stocks require an exchange prefix. For example, if you query "BTIM", you'll get a "Bad Request" error but "AMEX:BTIM" works. A few stocks don't work even with the exchange prefix. For example, querying "FTWRD" and "NASDAQ:FTWRD" both generate "Bad Request" errors even though Google Finance does have information for this NASDAQ stock.

The "el" field, if present, tells you the current pre-market or after-hours price.

Return from a promise then()

I prefer to use "await" command and async functions to get rid of confusions of promises,

In this case I would write an asynchronous function first, this will be used instead of the anonymous function called under "promise.then" part of this question :

async function SubFunction(output){

   // Call to database , returns a promise, like an Ajax call etc :

   const response = await axios.get( GetApiHost() + '/api/some_endpoint')

   // Return :
   return response;

}

and then I would call this function from main function :

async function justTesting() {
   const lv_result = await SubFunction(output);

   return lv_result + 1;
}

Noting that I returned both main function and sub function to async functions here.

How to check if a specified key exists in a given S3 bucket using Java

The other answers are for AWS SDK v1. Here is a method for AWS SDK v2 (currently 2.3.9).

Note that getObjectMetadata and doesObjectExist methods are not currently in the v2 SDK! So those are no longer options. We are forced to use either getObject or listObjects.

listObjects calls are currently 12.5 times more expensive to make than getObject. But AWS also charges for any data downloaded, which raises the price of getObject if the file exists. As long as the file is very unlikely to exist (for example, you have generated a new UUID key randomly and just need to double-check that it isn't taken) then calling getObject is significantly cheaper by my calculation.

Just to be on the safe side though, I added a range() specification to ask AWS to only send a few bytes of the file. As far as I know the SDK will always respect this and not charge you for downloading the whole file. But I haven't verified that so rely on that behavior at your own risk! (Also, I'm not sure what how range behaves if the S3 object is 0 bytes long.)

    private boolean sanityCheckNewS3Key(String bucket, String key) {

        ResponseInputStream<GetObjectResponse> resp = null;
        try {
            resp = s3client.getObject(GetObjectRequest.builder()
                .bucket(bucket)
                .key(key)
                .range("bytes=0-3")
                .build());
        }
        catch (NoSuchKeyException e) {
            return false;
        }
        catch (AwsServiceException se) {
            throw se;
        }
        finally {
            if (resp != null) {
                try {
                    resp.close();
                } catch (IOException e) {
                    log.warn("Exception while attempting to close S3 input stream", e);
                }
            }
        }
        return true;
    }
}

Note: this code assumes s3Client and log are declared and initialized elsewhere. Method returns a boolean, but can throw exceptions.

Regular expression to extract text between square brackets

If someone wants to match and select a string containing one or more dots inside square brackets like "[fu.bar]" use the following:

(?<=\[)(\w+\.\w+.*?)(?=\])

Regex Tester

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

I'm assuming that is just part of the new UITableViewStyleGrouped styling. It is in all grouped table views and there doesn't seem to be any direct way to control that space.

If that space is being represented by a UIView, it would be possible to search through all the subviews of the UITableView to find that specific view and edit it directly. However, there is also the possibility that that space is just a hardcoded offset before headers and cells start and there won't be any way to edit it.

To search through all subviews (I would run this code when the table has no cells, to make it a little easier to read the output):

- (void)listSubviewsOfView:(UIView *)view {

    // Get the subviews of the view
    NSArray *subviews = [view subviews];

    // Return if there are no subviews
    if ([subviews count] == 0) return;

    for (UIView *subview in subviews) {

        NSLog(@"%@", subview);

        // List the subviews of subview
        [self listSubviewsOfView:subview];
    }
}

Python class returning value

You are describing a function, not a class.

def Myclass():
    return []

Using jQuery to test if an input has focus

if anyone cares there is a much better way to capture focus now, $(foo).focus(...)

http://api.jquery.com/focus/

Send POST data using XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
    // do something to response
    console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');

Or if you can count on browser support you could use FormData:

var data = new FormData();
data.append('user', 'person');
data.append('pwd', 'password');
data.append('organization', 'place');
data.append('requiredkey', 'key');

var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.onload = function () {
    // do something to response
    console.log(this.responseText);
};
xhr.send(data);

Alter column, add default constraint

I use the stored procedure below to update the defaults on a column.

It automatically removes any prior defaults on the column, before adding the new default.

Examples of usage:

-- Update default to be a date.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','getdate()';
-- Update default to be a number.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
-- Update default to be a string. Note extra quotes, as this is not a function.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';

Stored procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Sample function calls:
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','ColumnName','getdate()';
--exec [dbol].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';
create PROCEDURE [dbo].[ColumnDefaultUpdate]
    (
        -- Table name, including schema, e.g. '[dbo].[TableName]'
        @TABLE_NAME VARCHAR(100), 
        -- Column name, e.g. 'ColumnName'.
        @COLUMN_NAME VARCHAR(100),
        -- New default, e.g. '''MyDefault''' or 'getdate()'
        -- Note that if you want to set it to a string constant, the contents
        -- must be surrounded by extra quotes, e.g. '''MyConstant''' not 'MyConstant'
        @NEW_DEFAULT VARCHAR(100)
    )
AS 
BEGIN       
    -- Trim angle brackets so things work even if they are included.
    set @COLUMN_NAME = REPLACE(@COLUMN_NAME, '[', '')
    set @COLUMN_NAME = REPLACE(@COLUMN_NAME, ']', '')

    print 'Table name: ' + @TABLE_NAME;
    print 'Column name: ' + @COLUMN_NAME;
    DECLARE @ObjectName NVARCHAR(100)
    SELECT @ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
    WHERE [object_id] = OBJECT_ID(@TABLE_NAME) AND [name] = @COLUMN_NAME;

    IF @ObjectName <> '' 
    begin
        print 'Removed default: ' + @ObjectName;
        --print('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
        EXEC('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
    end

    EXEC('ALTER TABLE ' + @TABLE_NAME + ' ADD  DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
    --print('ALTER TABLE ' + @TABLE_NAME + ' ADD  DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
    print 'Added default of: ' + @NEW_DEFAULT;
END

Errors this stored procedure eliminates

If you attempt to add a default to a column when one already exists, you will get the following error (something you will never see if using this stored proc):

-- Using the stored procedure eliminates this error:
Msg 1781, Level 16, State 1, Line 1
Column already has a DEFAULT bound to it.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

MySQL - Replace Character in Columns

Replace below characters

~ ! @ # $ % ^ & * ( ) _ +
` - = 
{ } |
[ ] \
: " 
; '

< > ?
, . 

with this SQL

SELECT note as note_original, 

    REPLACE(
        REPLACE(
            REPLACE(
                REPLACE(
                    REPLACE(
                        REPLACE(
                            REPLACE(
                                REPLACE(
                                    REPLACE(
                                        REPLACE(
                                            REPLACE(
                                                REPLACE(
                                                    REPLACE(
                                                        REPLACE(
                                                            REPLACE(
                                                                REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(
                                                                                                REPLACE(
                                                                                                    REPLACE(
                                                                                                        REPLACE(
                                                                    REPLACE(
                                                                        REPLACE(
                                                                            REPLACE(
                                                                                REPLACE(
                                                                                    REPLACE(
                                                                                        REPLACE(
                                                                                            REPLACE(note, '\"', ''),
                                                                                        '.', ''),
                                                                                    '?', ''),
                                                                                '`', ''),
                                                                            '<', ''),
                                                                        '=', ''),
                                                                    '{', ''),
                                                                                                        '}', ''),
                                                                                                    '[', ''),
                                                                                                ']', ''),
                                                                                            '|', ''),
                                                                                        '\'', ''),
                                                                                    ':', ''),
                                                                                ';', ''),
                                                                            '~', ''),
                                                                        '!', ''),
                                                                    '@', ''),
                                                                '#', ''),
                                                            '$', ''),
                                                        '%', ''),
                                                    '^', ''),
                                                '&', ''),
                                            '*', ''),
                                        '_', ''),
                                    '+', ''),
                                ',', ''),
                            '/', ''),
                        '(', ''),
                    ')', ''),
                '-', ''),
            '>', ''),
        ' ', '-'),
    '--', '-') as note_changed FROM invheader

capture div into image using html2canvas

If you just want to have screenshot of a div, you can do it like this

html2canvas($('#div'), {
  onrendered: function(canvas) {
    var img = canvas.toDataURL()
    window.open(img);
  }
});

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

Set line spacing

You can also use a unit-less value, which is the number of lines: line-height: 2; is double spaced, line-height: 1.5; is one and a half, etc.

fileReader.readAsBinaryString to upload files

(Following is a late but complete answer)

FileReader methods support


FileReader.readAsBinaryString() is deprecated. Don't use it! It's no longer in the W3C File API working draft:

void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);

NB: Note that File is a kind of extended Blob structure.

Mozilla still implements readAsBinaryString() and describes it in MDN FileApi documentation:

void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);

The reason behind readAsBinaryString() deprecation is in my opinion the following: the standard for JavaScript strings are DOMString which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.

We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob and typed arrays (ArrayBuffer and the not-yet-implemented but not necessary StringView) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.

XMLHttpRequest upload support


XMLHttpRequest.send() has the following invocations options:

void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);

XMLHttpRequest.sendAsBinary() has the following invocations options:

void sendAsBinary(   in DOMString body );

sendAsBinary() is NOT a standard and may not be supported in Chrome.

Solutions


So you have several options:

  1. send() the FileReader.result of FileReader.readAsArrayBuffer ( fileObject ). It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.
  2. send() the FileReader.result of FileReader.readAsDataURL( fileObject ). It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.
  3. Being non-standard and sendAsBinary() the FileReader.result of FileReader.readAsBinaryString( fileObject )

MDN states that:

The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.

Pressed <button> selector

You can do this if you use an <a> tag instead of a button. I know it's not exactly what you asked for, but it might give you some other options if you cannot find a solution to this:

Borrowing from a demo from another answer here I produced this:

_x000D_
_x000D_
a {_x000D_
  display: block;_x000D_
  font-size: 18px;_x000D_
  border: 2px solid gray;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  text-align: center;_x000D_
  line-height: 100px;_x000D_
}_x000D_
_x000D_
a:active {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid green;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
a:target {_x000D_
  font-size: 18px;_x000D_
  border: 2px solid red;_x000D_
  border-radius: 100px;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<a id="btn" href="#btn">Demo</a>
_x000D_
_x000D_
_x000D_

Notice the use of :target; this will be the style applied when the element is targeted via the hash. Which also means your HTML will need to be this: <a id="btn" href="#btn">Demo</a> a link targeting itself. and the demo http://jsfiddle.net/rlemon/Awdq5/4/

Thanks to @BenjaminGruenbaum here is a better demo: http://jsfiddle.net/agzVt/

Also, as a footnote: this should really be done with JavaScript and applying / removing CSS classes from the element. It would be much less convoluted.

How to properly seed random number generator

I don't understand why people are seeding with a time value. This has in my experience never been a good idea. For example, while the system clock is maybe represented in nanoseconds, the system's clock precision isn't nanoseconds.

This program should not be run on the Go playground but if you run it on your machine you get a rough estimate on what type of precision you can expect. I see increments of about 1000000 ns, so 1 ms increments. That's 20 bits of entropy that are not used. All the while the high bits are mostly constant!? Roughly ~24 bits of entropy over a day which is very brute forceable (which can create vulnerabilities).

The degree that this matters to you will vary but you can avoid pitfalls of clock based seed values by simply using the crypto/rand.Read as source for your seed. It will give you that non-deterministic quality that you are probably looking for in your random numbers (even if the actual implementation itself is limited to a set of distinct and deterministic random sequences).

import (
    crypto_rand "crypto/rand"
    "encoding/binary"
    math_rand "math/rand"
)

func init() {
    var b [8]byte
    _, err := crypto_rand.Read(b[:])
    if err != nil {
        panic("cannot seed math/rand package with cryptographically secure random number generator")
    }
    math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}

As a side note but in relation to your question. You can create your own rand.Source using this method to avoid the cost of having locks protecting the source. The rand package utility functions are convenient but they also use locks under the hood to prevent the source from being used concurrently. If you don't need that you can avoid it by creating your own Source and use that in a non-concurrent way. Regardless, you should NOT be reseeding your random number generator between iterations, it was never designed to be used that way.

CodeIgniter : Unable to load the requested file:

File names are case sensitive - please check your file name. it should be in same case in view folder

Begin, Rescue and Ensure in Ruby?

Yes, ensure ENSURES it is run every time, so you don't need the file.close in the begin block.

By the way, a good way to test is to do:

begin
  # Raise an error here
  raise "Error!!"
rescue
  #handle the error here
ensure
  p "=========inside ensure block"
end

You can test to see if "=========inside ensure block" will be printed out when there is an exception. Then you can comment out the statement that raises the error and see if the ensure statement is executed by seeing if anything gets printed out.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

How to check if a column exists in a SQL Server table?

Below query can be used to check whether searched column exists or not in the table. We can take decision based on the searched result also as shown below.

IF EXISTS (SELECT 'Y' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = <YourTableName> AND COLUMN_NAME = <YourColumnName>)
  BEGIN
    SELECT 'Column Already Exists.'
  END
  ELSE
  BEGIN
    ALTER TABLE <YourTableName> ADD <YourColumnName> <DataType>[Size]
  END

Returning value from called function in a shell script

If it's just a true/false test, have your function return 0 for success, and return 1 for failure. The test would then be:

if function_name; then
  do something
else
  error condition
fi

What is the difference between "SMS Push" and "WAP Push"?

An SMS Push is a message to tell the terminal to initiate the session. This happens because you can't initiate an IP session simply because you don't know the IP Adress of the mobile terminal. Mostly used to send a few lines of data to end recipient, to the effect of sending information, or reminding of events.

WAP Push is an SMS within the header of which is included a link to a WAP address. On receiving a WAP Push, the compatible mobile handset automatically gives the user the option to access the WAP content on his handset. The WAP Push directs the end-user to a WAP address where content is stored ready for viewing or downloading onto the handset. This wap address may be a page or a WAP site.

The user may “take action” by using a developer-defined soft-key to immediately activate an application to accomplish a specific task, such as downloading a picture, making a purchase, or responding to a marketing offer.

ERROR 1049 (42000): Unknown database

blog_development doesn't exist

You can see this in sql by the 0 rows affected message

create it in mysql with

mysql> create database blog_development

However as you are using rails you should get used to using

$ rake db:create

to do the same task. It will use your database.yml file settings, which should include something like:

development:
  adapter: mysql2
  database: blog_development
  pool: 5

Also become familiar with:

$ rake db:migrate  # Run the database migration
$ rake db:seed     # Run thew seeds file create statements
$ rake db:drop     # Drop the database

git status shows modifications, git checkout -- <file> doesn't remove them

I had a .bat file with the same problem (couldn't get rid it it in untracked files). git checkout -- didn't work, neither did any of the suggestions on this page. The only thing that worked for me was to do:

git stash save --keep-index

And then to delete the stash:

git stash drop

How to Set the Background Color of a JButton on the Mac OS

I own a mac too! here is the code that will work:

myButton.setBackground(Color.RED);
myButton.setOpaque(true); //Sets Button Opaque so it works

before doing anything or adding any components set the look and feel so it looks better:

try{
   UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
 }catch(Exception e){
  e.printStackTrace(); 
 }

That is Supposed to change the look and feel to the cross platform look and feel, hope i helped! :)

Format date as dd/MM/yyyy using pipes

In my case, I use in component file:

import {formatDate} from '@angular/common';

// Use your preferred locale
import localeFr from '@angular/common/locales/fr';
import { registerLocaleData } from '@angular/common';

// ....

displayDate: string;
registerLocaleData(localeFr, 'fr');
this.displayDate = formatDate(new Date(), 'EEEE d MMMM yyyy', 'fr');

And in the component HTML file

<h1> {{ displayDate }} </h1>

It works fine for me ;-)

How do you create a daemon in Python?

Though you may prefer the pure Python solution provided by the python-daemon module, there is a daemon(3) function in libc -- at least, on BSD and Linux -- which will do the right thing.

Calling it from python is easy:

import ctypes

ctypes.CDLL(None).daemon(0, 0) # Read the man-page for the arguments' meanings

The only remaining thing to do is creation (and locking) of the PID-file. But that you can handle yourself...

LINQ select in C# dictionary

var res = exitDictionary
            .Select(p => p.Value).Cast<Dictionary<string, object>>()
            .SelectMany(d => d)
            .Where(p => p.Key == "fieldname1")
            .Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
            .SelectMany(l => l)
            .SelectMany(d=> d)
            .Where(p => p.Key == "valueTitle")
            .Select(p => p.Value)
            .ToList();

This also works, and easy to understand.

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

The best way to remove duplicate values from NSMutableArray in Objective-C?

Here is the code of removing duplicates values from NSMutable Array..it will work for you. myArray is your Mutable Array that you want to remove duplicates values..

for(int j = 0; j < [myMutableArray count]; j++){
    for( k = j+1;k < [myMutableArray count];k++){
    NSString *str1 = [myMutableArray objectAtIndex:j];
    NSString *str2 = [myMutableArray objectAtIndex:k];
    if([str1 isEqualToString:str2])
        [myMutableArray removeObjectAtIndex:k];
    }
 } // Now print your array and will see there is no repeated value

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

With version 2018.1 the keyboard short cuts for navigation are Shift+Alt+Left or Right

What is the equivalent of "!=" in Excel VBA?

In VBA, the != operator is the Not operator, like this:

If Not strTest = "" Then ...

What is git tag, How to create tags & How to checkout git remote tag(s)

In order to checkout a git tag , you would execute the following command

git checkout tags/tag-name -b branch-name

eg as mentioned below.

 git checkout tags/v1.0 -b v1.0-branch

To fetch the all tags use the command

git fetch --all --tags

Laravel view not found exception

Use this on your cmd then run your project.

php artisan config:cache php artisan route:cache php artisan controller:cache php artisan optimize:clear

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

Most certainly, export JAVA_HOME=/usr/bin/java is the culprit. This env var should point to the JDK or JRE installation directory. Googling shows that the best option for MacOS X seems to be export JAVA_HOME=/Library/Java/Home.

How can I beautify JSON programmatically?

Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.

You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.

I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.

Batch script: how to check for admin rights

net user %username% >nul 2>&1 && echo admin || echo not admin

The term 'Get-ADUser' is not recognized as the name of a cmdlet

Check here for how to add the activedirectory module if not there by default. This can be done on any machine and then it will allow you to access your active directory "domain control" server.

EDIT

To prevent problems with stale links (I have found MSDN blogs to disappear for no reason in the past), in essence for Windows 7 you need to download and install Remote Server Administration Tools (KB958830). After installing do the following steps:

  • Open Control Panel -> Programs and Features -> Turn On/Off Windows Features
  • Find "Remote Server Administration Tools" and expand it
  • Find "Role Administration Tools" and expand it
  • Find "AD DS And AD LDS Tools" and expand it
  • Check the box next to "Active Directory Module For Windows PowerShell".
  • Click OK and allow Windows to install the feature

Windows server editions should already be OK but if not you need to download and install the Active Directory Management Gateway Service. If any of these links should stop working, you should still be able search for the KB article or download names and find them.

Appending output of a Batch file To log file

Instead of using ">" to redirect like this:

java Foo > log

use ">>" to append normal "stdout" output to a new or existing file:

java Foo >> log

However, if you also want to capture "stderr" errors (such as why the Java program couldn't be started), you should also use the "2>&1" tag which redirects "stderr" (the "2") to "stdout" (the "1"). For example:

java Foo >> log 2>&1 

Add querystring parameters to link_to

If you want to keep existing params and not expose yourself to XSS attacks, be sure to clean the params hash, leaving only the params that your app can be sending:

# inline
<%= link_to 'Link', params.slice(:sort).merge(per_page: 20) %>

 

If you use it in multiple places, clean the params in the controller:

# your_controller.rb
@params = params.slice(:sort, :per_page)

# view
<%= link_to 'Link', @params.merge(per_page: 20) %>

How to use and style new AlertDialog from appCompat 22.1 and above

Follow @reVerse answer but in my case, I already had some property in my AppTheme like

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    ...
    <item name="android:textColor">#111</item>
    <item name="android:textSize">13sp</item>
</style>

So my dialog will look like
enter image description here

I solved it by

1) Change the import from android.app.AlertDialog to android.support.v7.app.AlertDialog
2) I override 2 property in AppTheme with null value

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!-- Used for the buttons -->
    <item name="colorAccent">#FFC107</item>
    <!-- Used for the title and text -->
    <item name="android:textColorPrimary">#FFFFFF</item>
    <!-- Used for the background -->
    <item name="android:background">#4CAF50</item>


    <item name="android:textColor">@null</item>
    <item name="android:textSize">@null</item>
</style>

.

AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.MyAlertDialogStyle);

Hope it help another people

enter image description here

Where does Git store files?

To be a bit more complete, Git works with:

  • the working tree (the root of which being where you made a git init)
  • "path to the Git repository" (where there is a .git, which will store the revisions of all your files)

GIT_DIR is an environment variable, which can be an absolute path or relative path to current working directory.

If it is not defined, the "path to the git repository" is by default at the root directory of your working tree (again, where you made a git init).

You can actually execute any Git command from anywhere from your disk, provided you specify the working tree path and the Git repository path:

git command --git-dir=<path> --work-tree=<path>

But if you execute them in one of the subdirectories of a Git repository (with no GIT-DIR or working tree path specified), Git will simply look in the current and parent directories until it find a .git, assume this it also the root directory of your working tree, and use that .git as the only container for all the revisions of your files.

Note: .git is also hidden in Windows (msysgit).
You would have to do a dir /AH to see it.
git 2.9 (June 2016) allows to configure that.


Note that Git 2.18 (Q2 2018) is starting the process to evolve how Git is storing objects, by refactoring the internal global data structure to make it possible to open multiple repositories, work with and then close them.

See commit 4a7c05f, commit 1fea63e (23 Mar 2018) by Jonathan Nieder (artagnon).
See commit bd27f50, commit ec7283e, commit d2607fa, commit a68377b, commit e977fc7, commit e35454f, commit 332295d, commit 2ba0bfd, commit fbe33e2, commit cf78ae4, commit 13068bf, commit 77f012e, commit 0b20903, commit 93d8d1e, commit ca5e6d2, commit cfc62fc, commit 13313fc, commit 9a00580 (23 Mar 2018) by Stefan Beller (stefanbeller).
(Merged by Junio C Hamano -- gitster -- in commit cf0b179, 11 Apr 2018)

repository: introduce raw object store field

The raw object store field will contain any objects needed for access to objects in a given repository.

This patch introduces the raw object store and populates it with the objectdir, which used to be part of the repository struct.

As the struct gains members, we'll also populate the function to clear the memory for these members.

In a later step, we'll introduce a struct object_parser, that will complement the object parsing in a repository struct:

  • The raw object parser is the layer that will provide access to raw object content,
  • while the higher level object parser code will parse raw objects and keeps track of parenthood and other object relationships using 'struct object'.

    For now only add the lower level to the repository struct.

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

The existing answers already cover the "how", but I just wanted to elaborate on the "what" and "why" for others who might be wondering.

What a compiler (gcc) does: The term "compile" is a bit of an overloaded term because it is used at a high-level to mean "convert source code to a program", but more technically means to "convert source code to object code". A compiler like gcc actually performs two related, but arguably distinct functions to turn your source code into a program: compiling (as in the latter definition of turning source to object code) and linking (the process of combining the necessary object code files together into one complete executable).

The original error that you saw is technically a "linking error", and is thrown by "ld", the linker. Unlike (strict) compile-time errors, there is no reference to source code lines, as the linker is already in object space.

By default, when gcc is given source code as input, it attempts to compile each and then link them all together. As noted in the other responses, it's possible to use flags to instruct gcc to just compile first, then use the object files later to link in a separate step. This two-step process may seem unnecessary (and probably is for very small programs) but it is very important when managing a very large program, where compiling the entire project each time you make a small change would waste a considerable amount of time.

What does the Visual Studio "Any CPU" target mean?

Here's a quick overview that explains the different build targets.

From my own experience, if you're looking to build a project that will run on both x86 and x64 platforms, and you don't have any specific x64 optimizations, I'd change the build to specifically say "x86."

The reason for this is sometimes you can get some DLL files that collide or some code that winds up crashing WoW in the x64 environment. By specifically specifying x86, the x64 OS will treat the application as a pure x86 application and make sure everything runs smoothly.

Bootstrap: Position of dropdown menu relative to navbar item

This is the effect that we're trying to achieve:

A right-aligned menu

The classes that need to be applied changed with the release of Bootstrap 3.1.0 and again with the release of Bootstrap 4. If one of the below solutions doesn't seem to be working double check the version number of Bootstrap that you're importing and try a different one.

Bootstrap 3

Before v3.1.0

You can use the pull-right class to line the right hand side of the menu up with the caret:

<li class="dropdown">
  <a class="dropdown-toggle" href="#">Link</a>
  <ul class="dropdown-menu pull-right">
     <li>...</li>
  </ul>
</li>

Fiddle: http://jsfiddle.net/joeczucha/ewzafdju/

After v3.1.0

As of v3.1.0, we've deprecated .pull-right on dropdown menus. To right-align a menu, use .dropdown-menu-right. Right-aligned nav components in the navbar use a mixin version of this class to automatically align the menu. To override it, use .dropdown-menu-left.

You can use the dropdown-right class to line the right hand side of the menu up with the caret:

<li class="dropdown">
  <a class="dropdown-toggle" href="#">Link</a>
  <ul class="dropdown-menu dropdown-menu-right">
     <li>...</li>
  </ul>
</li>

Fiddle: http://jsfiddle.net/joeczucha/1nrLafxc/

Bootstrap 4

The class for Bootstrap 4 are the same as Bootstrap > 3.1.0, just watch out as the rest of the surrounding markup has changed a little:

<li class="nav-item dropdown">
  <a class="nav-link dropdown-toggle" href="#">
    Link
  </a>
  <div class="dropdown-menu dropdown-menu-right">
    <a class="dropdown-item" href="#">...</a>
  </div>
</li>

Fiddle: https://jsfiddle.net/joeczucha/f8h2tLoc/

Rendering HTML inside textarea

This is possible with <textarea> the only thing you need to do is use Summernote WYSIWYG editor

it interprets HTML tags inside a textarea (namely <strong>, <i>, <u>, <a>)

T-SQL Format integer to 2-digit string

You can use T-SQL's built in format function:

declare @number int  = 1
select format (@number, '0#')

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

A common practice is to put a @Transactional above your service class.

@Service
@Transactional
public class MyServiceImpl implements MyService{
...
}

How to change the background-color of jumbrotron?

You don't necessarily have to use custom CSS (or even worse inline CSS), in Bootstrap 4 you can use the utility classes for colors, like:

<div class="jumbotron bg-dark text-white">
...

And if you need other colors than the default ones, just add additional bg-classes using the same naming convention. This keeps the code neat and understandable.

You might also need to set text-white on child-elements inside the jumbotron, like headings.

Multi-dimensional arrays in Bash

I do this using associative arrays since bash 4 and setting IFS to a value that can be defined manually.

The purpose of this approach is to have arrays as values of associative array keys.

In order to set IFS back to default just unset it.

  • unset IFS

This is an example:

#!/bin/bash

set -euo pipefail

# used as value in asscciative array
test=(
  "x3:x4:x5"
)
# associative array
declare -A wow=(
  ["1"]=$test
  ["2"]=$test
)
echo "default IFS"
for w in ${wow[@]}; do
  echo "  $w"
done

IFS=:
echo "IFS=:"
for w in ${wow[@]}; do
  for t in $w; do
    echo "  $t"
  done
done
echo -e "\n or\n"
for w in ${!wow[@]}
do
  echo "  $w"
  for t in ${wow[$w]}
  do
    echo "    $t"
  done
done

unset IFS
unset w
unset t
unset wow
unset test

The output of the script below is:

default IFS
  x3:x4:x5
  x3:x4:x5
IFS=:
  x3
  x4
  x5
  x3
  x4
  x5

 or

  1
    x3
    x4
    x5
  2
    x3
    x4
    x5

Submit form using <a> tag

If jquery is allowed then you can use following code to implement it in the easiest way as :

<a href="javascript:$('#form_id').submit();">Login</a>

or

<a href="javascript:$('form').submit()">Login</a>

You can use following line in your head tag () to import jquery into your code

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

PadLeft function in T-SQL

-- Please look into these.

select FORMAT(1, 'd4');
select FORMAT(2, 'd4');
select FORMAT(12, 'd4');
select FORMAT(123, 'd4');
select FORMAT(1234, 'd4');

-- I hope these would help you

removing table border

Try giving your table an ID and then using !important to set border to none in CSS. If JavaScript is tampering with your table then that should get around it.

<table id="mytable"
...

table#mytable,
table#mytable td
{
    border: none !important;
}

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

In my case I refactored code and put the creation of the Dialog in a separate class. I only handed over the clicked View because a View contains a context object already. This led to the same error message although all ran on the MainThread.

I then switched to handing over the Activity as well and used its context in the dialog creation -> Everything works now.

    fun showDialogToDeletePhoto(baseActivity: BaseActivity, clickedParent: View, deletePhotoClickedListener: DeletePhotoClickedListener) {
        val dialog = AlertDialog.Builder(baseActivity) // <-- here
   .setTitle(baseActivity.getString(R.string.alert_delete_picture_dialog_title))
...
}

I , can't format the code snippet properly, sorry :(

What is the meaning of {...this.props} in Reactjs

It's called spread attributes and its aim is to make the passing of props easier.

Let us imagine that you have a component that accepts N number of properties. Passing these down can be tedious and unwieldy if the number grows.

<Component x={} y={} z={} />

Thus instead you do this, wrap them up in an object and use the spread notation

var props = { x: 1, y: 1, z:1 };
<Component {...props} />

which will unpack it into the props on your component, i.e., you "never" use {... props} inside your render() function, only when you pass the props down to another component. Use your unpacked props as normal this.props.x.

Using ALTER to drop a column if it exists in MySQL

For MySQL, there is none: MySQL Feature Request.

Allowing this is arguably a really bad idea, anyway: IF EXISTS indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.

But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.

MariaDB also supports the following starting with 10.0.2:

DROP [COLUMN] [IF EXISTS] col_name 

i. e.

ALTER TABLE my_table DROP IF EXISTS my_column;

But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.

How to delete a record by id in Flask-SQLAlchemy

You can do this,

User.query.filter_by(id=123).delete()

or

User.query.filter(User.id == 123).delete()

Make sure to commit for delete() to take effect.

Jquery DatePicker Set default date

Code to display current date in element input or datepicker with ID="mydate"

Don't forget add reference to jquery-ui-*.js

    $(document).ready(function () {
        var dateNewFormat, onlyDate, today = new Date();

        dateNewFormat = today.getFullYear() + '-' + (today.getMonth() + 1);

        onlyDate = today.getDate();

        if (onlyDate.toString().length == 2) {
            dateNewFormat += '-' + onlyDate;
        }
        else {
            dateNewFormat += '-0' + onlyDate;
        }
        $('#mydate').val(dateNewFormat);
    });

Is there a bash command which counts files?

Here's what I always do:

ls log* | awk 'END{print NR}'

How to do a background for a label will be without color?

this.label1.BackColor = System.Drawing.Color.Transparent;

Toggle visibility property of div

According to the jQuery docs, calling toggle() without parameters will toggle visibility.

$('#play-pause').click(function(){
   $('#video-over').toggle();
});

http://jsfiddle.net/Q47ya/

How to cut an entire line in vim and paste it?

  1. Go to the line, and first press esc, and then Shift + v.

(This would have highlighted the line)

  1. press d

(The line is now deleted)

  1. Go to the location, where you wanted to paste the line, and hit p.

In a nutshell,

Esc -> Shift + v -> d -> p

IIS7 Cache-Control

If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.

You can however drop this web.config in the root of the folder or site where you want to set it:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
    </staticContent>
  </system.webServer>
</configuration>

That will inform the client to cache content for 7 days in that folder and all subfolders.

You can also do this by editing the IIS7 metabase via appcmd.exe, like so:

\Windows\system32\inetsrv\appcmd.exe 
  set config "Default Web Site/folder" 
  -section:system.webServer/staticContent 
  -clientCache.cacheControlMode:UseMaxAge

\Windows\system32\inetsrv\appcmd.exe 
  set config "Default Web Site/folder" 
  -section:system.webServer/staticContent 
  -clientCache.cacheControlMaxAge:"7.00:00:00"

Alter table add multiple columns ms sql

Alter table Hotels 
Add  
{ 
 HasPhotoInReadyStorage  bit, 
 HasPhotoInWorkStorage  bit, 
 HasPhotoInMaterialStorage bit, 
 HasHotelPhotoInReadyStorage  bit, 
 HasHotelPhotoInWorkStorage  bit, 
 HasHotelPhotoInMaterialStorage bit, 
 HasReporterData  bit, 
 HasMovieInReadyStorage  bit, 
 HasMovieInWorkStorage  bit, 
 HasMovieInMaterialStorage bit 
}; 

Above you are using {, }.

Also, you are missing commas:

ALTER TABLE Regions 
ADD ( HasPhotoInReadyStorage  bit, 
 HasPhotoInWorkStorage  bit, 
 HasPhotoInMaterialStorage bit <**** comma needed here
 HasText  bit); 

You need to remove the brackets and make sure all columns have a comma where necessary.

Automated Python to Java translation

It may not be an easy problem. Determining how to map classes defined in Python into types in Java will be a big challange because of differences in each of type binding time. (duck typing vs. compile time binding).

Brackets.io: Is there a way to auto indent / format <html>

Beautify does a good job. It provides a "Beautify on save" option, so that you may use ctrl+s to reformate html, less, css, etc

Eclipse Java Missing required source folder: 'src'

In eclipse, you must be careful to create a "source folder" (File->New->Source Folder). This way, it's automatically on your classpath, and, more importantly, Eclipse knows that these are compilable files. It's picky that way.

Adding a collaborator to my free GitHub account?

Yes the set of instructions above are outdated. For the new GitHub the Settings button must be clicked.

Also the person you try to add as a collaborator must have an existing GitHub account. In other words he should have signed up on GitHub first because it is not possible to send collaboration requests merely by typing in the email address of the collaborator.

Swapping pointers in C (char, int)

If you have the luxury of working in C++, use this:

template<typename T>
void swapPrimitives(T& a, T& b)
{
    T c = a;
    a = b;
    b = c;
}

Granted, in the case of char*, it would only swap the pointers themselves, not the data they point to, but in most cases, that is OK, right?

Get url without querystring

Request.RawUrl.Split('?')[0]

Just for url name only !!

How to store a large (10 digits) integer?

A wrapper class java.lang.Long can store 10 digit easily.

   Long phoneNumber = 1234567890;

It can store more than that also.

Documentation:

public final class Long extends Number implements Comparable<Long> {
    /**
     * A constant holding the minimum value a {@code long} can
     * have, -2<sup>63</sup>.
     */
    @Native public static final long MIN_VALUE = 0x8000000000000000L;

    /**
     * A constant holding the maximum value a {@code long} can
     * have, 2<sup>63</sup>-1.
     */
    @Native public static final long MAX_VALUE = 0x7fffffffffffffffL;
}

This means it can store values of range 9,223,372,036,854,775,807 to -9,223,372,036,854,775,808.

How can I decrypt a password hash in PHP?

Bcrypt is a one-way hashing algorithm, you can't decrypt hashes. Use password_verify to check whether a password matches the stored hash:

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

In your case, run the SQL query using only the username:

$sql_script = 'SELECT * FROM USERS WHERE username=?';

And do the password validation in PHP using a code that is similar to the example above.

The way you are constructing the query is very dangerous. If you don't parameterize the input properly, the code will be vulnerable to SQL injection attacks. See this Stack Overflow answer on how to prevent SQL injection.

How to run a Runnable thread in Android at defined intervals?

Kotlin with Coroutines

In Kotlin, using coroutines you can do the following:

CoroutineScope(Dispatchers.Main).launch { // Main, because UI is changed
    ticker(delayMillis = 1000, initialDelayMillis = 1000).consumeEach {
        tv.append("Hello World")
    }
}

Try it out here!

What's "this" in JavaScript onclick?

keyword this in addEventListener event

_x000D_
_x000D_
function getValue(o) {_x000D_
  alert(o.innerHTML);_x000D_
}_x000D_
_x000D_
function hide(current) {_x000D_
  current.setAttribute("style", "display: none");_x000D_
}_x000D_
_x000D_
var bullet = document.querySelectorAll(".bullet");_x000D_
_x000D_
for (var x in bullet) { _x000D_
  bullet[x].onclick = function() {_x000D_
    hide(this);_x000D_
  };_x000D_
};_x000D_
 _x000D_
/* Using dynamic DOM Event */_x000D_
document.querySelector("#li").addEventListener("click", function() {_x000D_
  getValue(this); /* this = document.querySelector("#li") Object */_x000D_
});
_x000D_
li {_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<ul>_x000D_
  <li onclick="getValue(this);">A</li>_x000D_
  <li id="li" >B</li>_x000D_
  <hr />_x000D_
  <li class="bullet" >1</li>_x000D_
  <li class="bullet" >2</li>_x000D_
  <li class="bullet" >3</li>_x000D_
  <li class="bullet" >4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How does the ARM architecture differ from x86?

ARM is a RISC (Reduced Instruction Set Computing) architecture while x86 is a CISC (Complex Instruction Set Computing) one.

The core difference between those in this aspect is that ARM instructions operate only on registers with a few instructions for loading and saving data from / to memory while x86 can operate directly on memory as well. Up until v8 ARM was a native 32 bit architecture, favoring four byte operations over others.

So ARM is a simpler architecture, leading to small silicon area and lots of power save features while x86 becoming a power beast in terms of both power consumption and production.

About question on "Is the x86 Architecture specially designed to work with a keyboard while ARM expects to be mobile?". x86 isn't specially designed to work with a keyboard neither ARM for mobile. However again because of the core architectural choices actually x86 also has instructions to work directly with IO while ARM has not. However with specialized IO buses like USBs, need for such features are also disappearing.

If you need a document to quote, this is what Cortex-A Series Programmers Guide (4.0) tells about differences between RISC and CISC architectures:

An ARM processor is a Reduced Instruction Set Computer (RISC) processor.

Complex Instruction Set Computer (CISC) processors, like the x86, have a rich instruction set capable of doing complex things with a single instruction. Such processors often have significant amounts of internal logic that decode machine instructions to sequences of internal operations (microcode).

RISC architectures, in contrast, have a smaller number of more general purpose instructions, that might be executed with significantly fewer transistors, making the silicon cheaper and more power efficient. Like other RISC architectures, ARM cores have a large number of general-purpose registers and many instructions execute in a single cycle. It has simple addressing modes, where all load/store addresses can be determined from register contents and instruction fields.

ARM company also provides a paper titled Architectures, Processors, and Devices Development Article describing how those terms apply to their bussiness.

An example comparing instruction set architecture:

For example if you would need some sort of bytewise memory comparison block in your application (generated by compiler, skipping details), this is how it might look like on x86

repe cmpsb         /* repeat while equal compare string bytewise */

while on ARM shortest form might look like (without error checking etc.)

top:
ldrb r2, [r0, #1]! /* load a byte from address in r0 into r2, increment r0 after */
ldrb r3, [r1, #1]! /* load a byte from address in r1 into r3, increment r1 after */
subs r2, r3, r2    /* subtract r2 from r3 and put result into r2      */
beq  top           /* branch(/jump) if result is zero                 */

which should give you a hint on how RISC and CISC instruction sets differ in complexity.

python mpl_toolkits installation issue

I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap:

pacman -S python-basemap

Escaping Double Quotes in Batch Script

As an addition to mklement0's excellent answer:

Almost all executables accept \" as an escaped ". Safe usage in cmd however is almost only possible using DELAYEDEXPANSION.
To explicitely send a literal " to some process, assign \" to an environment variable, and then use that variable, whenever you need to pass a quote. Example:

SETLOCAL ENABLEDELAYEDEXPANSION
set q=\"
child "malicious argument!q!&whoami"

Note SETLOCAL ENABLEDELAYEDEXPANSION seems to work only within batch files. To get DELAYEDEXPANSION in an interactive session, start cmd /V:ON.

If your batchfile does't work with DELAYEDEXPANSION, you can enable it temporarily:

::region without DELAYEDEXPANSION

SETLOCAL ENABLEDELAYEDEXPANSION
::region with DELAYEDEXPANSION
set q=\"
echoarg.exe "ab !q! & echo danger"
ENDLOCAL

::region without DELAYEDEXPANSION

If you want to pass dynamic content from a variable that contains quotes that are escaped as "" you can replace "" with \" on expansion:

SETLOCAL ENABLEDELAYEDEXPANSION
foo.exe "danger & bar=region with !dynamic_content:""=\"! & danger"
ENDLOCAL

This replacement is not safe with %...% style expansion!

In case of OP bash -c "g++-linux-4.1 !v_params:"=\"!" is the safe version.


If for some reason even temporarily enabling DELAYEDEXPANSION is not an option, read on:

Using \" from within cmd is a little bit safer if one always needs to escape special characters, instead of just sometimes. (It's less likely to forget a caret, if it's consistent...)

To achieve this, one precedes any quote with a caret (^"), quotes that should reach the child process as literals must additionally be escaped with a backlash (\^"). ALL shell meta characters must be escaped with ^ as well, e.g. & => ^&; | => ^|; > => ^>; etc.

Example:

child ^"malicious argument\^"^&whoami^"

Source: Everyone quotes command line arguments the wrong way, see "A better method of quoting"


To pass dynamic content, one needs to ensure the following:
The part of the command that contains the variable must be considered "quoted" by cmd.exe (This is impossible if the variable can contain quotes - don't write %var:""=\"%). To achieve this, the last " before the variable and the first " after the variable are not ^-escaped. cmd-metacharacters between those two " must not be escaped. Example:

foo.exe ^"danger ^& bar=\"region with %dynamic_content% & danger\"^"

This isn't safe, if %dynamic_content% can contain unmatched quotes.

How can I align two divs horizontally?

Wrap them both in a container like so:

_x000D_
_x000D_
.container{ _x000D_
    float:left; _x000D_
    width:100%; _x000D_
}_x000D_
.container div{ _x000D_
    float:left;_x000D_
}
_x000D_
<div class='container'>_x000D_
    <div>_x000D_
        <span>source list</span>_x000D_
        <select size="10">_x000D_
            <option />_x000D_
            <option />_x000D_
            <option />_x000D_
        </select>_x000D_
    </div>_x000D_
    <div>_x000D_
        <span>destination list</span>_x000D_
        <select size="10">_x000D_
            <option />_x000D_
            <option />_x000D_
            <option />_x000D_
        </select>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if a variable is an integer in JavaScript?

Lodash https://lodash.com/docs#isInteger (since 4.0.0) has function to check if variable is an integer:

_.isInteger(3);
// ? true

_.isInteger(Number.MIN_VALUE);
// ? false

_.isInteger(Infinity);
// ? false

_.isInteger('3');
// ? false

How to get substring of NSString?

Option 1:

NSString *haystack = @"value:hello World:value";
NSString *haystackPrefix = @"value:";
NSString *haystackSuffix = @":value";
NSRange needleRange = NSMakeRange(haystackPrefix.length,
                                  haystack.length - haystackPrefix.length - haystackSuffix.length);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(@"needle: %@", needle); // -> "hello World"

Option 2:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^value:(.+?):value$" options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)];
NSRange needleRange = [match rangeAtIndex: 1];
NSString *needle = [haystack substringWithRange:needleRange];

This one might be a bit over the top for your rather trivial case though.

Option 3:

NSString *needle = [haystack componentsSeparatedByString:@":"][1];

This one creates three temporary strings and an array while splitting.


All snippets assume that what's searched for is actually contained in the string.

How can I print to the same line?

First, I'd like to apologize for bringing this question back up, but I felt that it could use another answer.

Derek Schultz is kind of correct. The '\b' character moves the printing cursor one character backwards, allowing you to overwrite the character that was printed there (it does not delete the entire line or even the character that was there unless you print new information on top). The following is an example of a progress bar using Java though it does not follow your format, it shows how to solve the core problem of overwriting characters (this has only been tested in Ubuntu 12.04 with Oracle's Java 7 on a 32-bit machine, but it should work on all Java systems):

public class BackSpaceCharacterTest
{
    // the exception comes from the use of accessing the main thread
    public static void main(String[] args) throws InterruptedException
    {
        /*
            Notice the user of print as opposed to println:
            the '\b' char cannot go over the new line char.
        */
        System.out.print("Start[          ]");
        System.out.flush(); // the flush method prints it to the screen

        // 11 '\b' chars: 1 for the ']', the rest are for the spaces
        System.out.print("\b\b\b\b\b\b\b\b\b\b\b");
        System.out.flush();
        Thread.sleep(500); // just to make it easy to see the changes

        for(int i = 0; i < 10; i++)
        {
            System.out.print("."); //overwrites a space
            System.out.flush();
            Thread.sleep(100);
        }

        System.out.print("] Done\n"); //overwrites the ']' + adds chars
        System.out.flush();
    }
}

Getter and Setter?

Validating + Formatting/Deriving Values

Setters let you to validate data and getters let you format or derive data. Objects allow you to encapsulate data and its validation and formatting code into a neat package that encourages DRY.

For example, consider the following simple class that contains a birth date.

class BirthDate {

    private $birth_date;

    public function getBirthDate($format='Y-m-d') {
        //format $birth_date ...
        //$birth_date = ...
        return $birth_date;
    }

    public function setBirthDate($birth_date) {                   
        //if($birth_date is not valid) throw an exception ...          
        $this->birth_date = $birth_date;
    }

    public function getAge() {
        //calculate age ...
        return $age;
    }

    public function getDaysUntilBirthday() {
        //calculate days until birth days
        return $days;
    }
}

You'll want to validate that the value being set is

  • A valid date
  • Not in the future

And you don't want to do this validation all over your application (or over multiple applications for that matter). Instead, it's easier to make the member variable protected or private (in order to make the setter the only access point) and to validate in the setter because then you'll know that the object contains a valid birth date no matter which part of the application the object came from and if you want to add more validation then you can add it in a single place.

You might want to add multiple formatters that operate on the same member variable i.e. getAge() and getDaysUntilBirthday() and you might want to enforce a configurable format in getBirthDate() depending on locale. Therefore I prefer consistently accessing values via getters as opposed to mixing $date->getAge() with $date->birth_date.

getters and setters are also useful when you extend objects. For example, suppose your application needed to allow 150+ year birth dates in some places but not in others. One way to solve the problem without repeating any code would be to extend the BirthDate object and put the additional validation in the setter.

class LivingBirthDate extends BirthDate {

    public function setBirthDate($birth_date) {
        //if $birth_date is greater than 150 years throw an exception
        //else pass to parent's setter
        return parent::setBirthDate($birth_date);
    }
}

Failed to load the JNI shared Library (JDK)

Simple, I have a 64-bit OS, 32-bit Eclipse and both JDK 32 & 64 installed... I just uninstalled the 64-bit JDK and Eclipse is working fine..

How do I create a readable diff of two spreadsheets using git diff?

Convert to cvs then upload to a version control system then diff with an advanced version control diff tool. When I used perforce it had a great diff tool, but I forget the name of it.

How to get highcharts dates in the x axis?

You write like this-:

xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
           day: '%d %b %Y'    //ex- 01 Jan 2016
        }
}

also check for other datetime format

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

How can I stop .gitignore from appearing in the list of untracked files?

If you want to store the list of ignored files outside of your Git tree, you can use the .git/info/exclude file. It is applied only to your checkout of the repo.

How to configure welcome file list in web.xml

I guess what you want is your index servlet to act as the welcome page, so change to:

<welcome-file-list>
   <welcome-file>index</welcome-file>
</welcome-file-list>

So that the index servlet will be used. Note, you'll need a servlet spec 2.4 container to be able to do this.

Note also, @BalusC gets my vote, for your index servlet on its own is superfluous.

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

Here's a small library I created you can use to make a viewport that Just Works(TM)

https://github.com/adamjgrant/a-viewport-that-works

Enabling HTTPS on express.js

I ran into a similar issue with getting SSL to work on a port other than port 443. In my case I had a bundle certificate as well as a certificate and a key. The bundle certificate is a file that holds multiple certificates, node requires that you break those certificates into separate elements of an array.

    var express = require('express');
    var https = require('https');
    var fs = require('fs');

    var options = {
      ca: [fs.readFileSync(PATH_TO_BUNDLE_CERT_1), fs.readFileSync(PATH_TO_BUNDLE_CERT_2)],
      cert: fs.readFileSync(PATH_TO_CERT),
      key: fs.readFileSync(PATH_TO_KEY)
    };

    app = express()

    app.get('/', function(req,res) {
        res.send('hello');
    });

    var server = https.createServer(options, app);

    server.listen(8001, function(){
        console.log("server running at https://IP_ADDRESS:8001/")
    });

In app.js you need to specify https and create the server accordingly. Also, make sure that the port you're trying to use is actually allowing inbound traffic.

SQL Server - inner join when updating

This should do it:

UPDATE ProductReviews
SET    ProductReviews.status = '0'
FROM   ProductReviews
       INNER JOIN products
         ON ProductReviews.pid = products.id
WHERE  ProductReviews.id = '17190'
       AND products.shopkeeper = '89137'

Getting value of HTML Checkbox from onclick/onchange events

For React.js, you can do this with more readable code. Hope it helps.

handleCheckboxChange(e) {
  console.log('value of checkbox : ', e.target.checked);
}
render() {
  return <input type="checkbox" onChange={this.handleCheckboxChange.bind(this)} />
}

How to remove item from array by value?

let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);

if (index > -1) {
   arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]

How to keep an iPhone app running on background fully operational

For running on stock iOS devices, make your app an audio player/recorder or a VOIP app, a legitimate one for submitting to the App store, or a fake one if only for your own use.

Even this won't make an app "fully operational" whatever that is, but restricted to limited APIs.

How do I initialize a byte array in Java?

private static final int[] CDRIVES = new int[] {0xe0, 0xf4, ...};

and after access convert to byte.

How to fetch all Git branches

We can put all branch or tag names in a temporary file, then do git pull for each name/tag:

git branch -r | grep origin | grep -v HEAD| awk -F/ '{print $NF}' > /tmp/all.txt
git tag -l >> /tmp/all.txt
for tag_or_branch in `cat /tmp/all.txt`; do git checkout $tag_or_branch; git pull origin $tag_or_branch; done

Get next element in foreach loop

You could get the keys of the array before the foreach, then use a counter to check the next element, something like:

//$arr is the array you wish to cycle through
$keys = array_keys($arr);
$num_keys = count($keys);
$i = 1;
foreach ($arr as $a)
{
    if ($i < $num_keys && $arr[$keys[$i]] == $a)
    {
        // we have a match
    }
    $i++;
}

This will work for both simple arrays, such as array(1,2,3), and keyed arrays such as array('first'=>1, 'second'=>2, 'thrid'=>3).

Save ArrayList to SharedPreferences

You can convert it to JSON String and store the string in the SharedPreferences.

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>
      <TileColor>#009900</TileColor>
    </tile>
  </msapplication>
</browserconfig>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...
  </div>
</div>

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

<script>
function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;
}
</script>

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

About the INT, TINYINT... These are different data types, INT is 4-byte number, TINYINT is 1-byte number. More information here - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT.

The syntax of TINYINT data type is TINYINT(M), where M indicates the maximum display width (used only if your MySQL client supports it).

Numeric Type Attributes.

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

Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

I encountered the same problem and I was able to resolve it with two solutions: First, I used the MMC snap-in "Certificates" for the "Computer account" and dragged the self-signed certificate into the "Trusted Root Certification Authorities" folder. This means the local computer (the one that generated the certificate) will now trust that certificate. Secondly I noticed that the certificate was generated for some internal computer name, but the web service was being accessed using another name. This caused a mismatch when validating the certificate. We generated the certificate for computer.operations.local, but accessed the web service using https://computer.internaldomain.companydomain.com. When we switched the URL to the one used to generate the certificate we got no more errors.

Maybe just switching URLs would have worked, but by making the certificate trusted you also avoid the red screen in Internet Explorer where it tells you it doesn't trust the certificate.

CSS rule to apply only if element has BOTH classes

If you need a progmatic solution this should work in jQuery:

$(".abc.xyz").css("width", 200);

Invalid hook call. Hooks can only be called inside of the body of a function component

In my case, I was trying to use mdbreact on windows. Though it installed, But i was getting the above error. I had to reinstall it and everything was ok. It happened to me once two with antd Library

Passing an Object from an Activity to a Fragment

If the data should survive throughout the application lifecycle and shared among multiple fragments or activities, a Model class might come into consideration, which has got less serialization overhead.

Check this design example

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

I had the same kind of error, right after a warning like the following:

java: You aren't using a compiler supported by lombok, so lombok will not work and has been disabled.
  Your processor is: com.sun.proxy.$Proxy27
  Lombok supports: OpenJDK javac, ECJ

In my case, it was an unfortunate combination of lombok < 1.18.16 and IDEA 2020.3.

How to change max_allowed_packet size

One of my junior developers was having a problem modifying this for me so I thought I would expand this in greater detail for linux users:

1) open terminal

2) ssh root@YOURIP

3) enter root password

4) nano /etc/mysql/my.cnf (if command is not recognized do this first or try vi then repeat: yum install nano )

5) add the line: max_allowed_packet=256M (obviously adjust size for whatever you need) under the [MYSQLD] section. He made a mistake of putting it at the bottom of the file first so it did not work.

enter image description here

6) Control + O (save) then ENTER (confirm) then Control + X (exit file)

7) service mysqld restart

8) You can check the change in the variables section on phpmyadmin

How to access JSON decoded array in PHP

As you're passing true as the second parameter to json_decode, in the above example you can retrieve data doing something similar to:

$myArray = json_decode($data, true);
echo $myArray[0]['id']; // Fetches the first ID
echo $myArray[0]['c_name']; // Fetches the first c_name
// ...
echo $myArray[2]['id']; // Fetches the third ID
// etc..

If you do NOT pass true as the second parameter to json_decode it would instead return it as an object:

echo $myArray[0]->id;

Do copyright dates need to be updated?

I don't think they are reprinting paper books each year. The copyright of the year when the book was printed is valid in all next years.

The same principle should apply to web pages, too. However "the year when website was created" is a bit different. So, if you make changes to your web site - you are not done yet. Hence, when updating the site, you may want to update the copyright year.

In Python, how to display current time in readable format

Take a look at the facilities provided by the time module

You have several conversion functions there.

Edit: see the datetime module for more OOP-like solutions. The time library linked above is kinda imperative.

Android Eclipse - Could not find *.apk

the problem for me was I was trying to use IBM RAD which appears to not work properly for this, I installed Eclipse and now have a different error but I should be able to get past it

WordPress path url in js script file

If the javascript file is loaded from the admin dashboard, this javascript function will give you the root of your WordPress installation. I use this a lot when I'm building plugins that need to make ajax requests from the admin dashboard.

function getHomeUrl() {
  var href = window.location.href;
  var index = href.indexOf('/wp-admin');
  var homeUrl = href.substring(0, index);
  return homeUrl;
}

UTF-8: General? Bin? Unicode?

Really, I tested saving values like 'é' and 'e' in column with unique index and they cause duplicate error on both 'utf8_unicode_ci' and 'utf8_general_ci'. You can save them only in 'utf8_bin' collated column.

And mysql docs (in http://dev.mysql.com/doc/refman/5.7/en/charset-applications.html) suggest into its examples set 'utf8_general_ci' collation.

[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

Git Checkout warning: unable to unlink files, permission denied

I was having the issue with a default-settings.php file in drupal 7. In this case I wasn't able to delete it or revert it just like @rtconner said. I didn't have an application or anything using this file, and it ended up being a permissions error.

I added chmod 777 * to the folder and then I was able to revert it no problem.

Convert International String to \u Codes in java

there is a JDK tools executed via command line as following :

native2ascii -encoding utf8 src.txt output.txt

Example :

src.txt

??? ???? ?????? ??????

output.txt

\u0628\u0633\u0645 \u0627\u0644\u0644\u0647 \u0627\u0644\u0631\u062d\u0645\u0646 \u0627\u0644\u0631\u062d\u064a\u0645

If you want to use it in your Java application, you can wrap this command line by :

String pathSrc = "./tmp/src.txt";
String pathOut = "./tmp/output.txt";
String cmdLine = "native2ascii -encoding utf8 " + new File(pathSrc).getAbsolutePath() + " " + new File(pathOut).getAbsolutePath();
Runtime.getRuntime().exec(cmdLine);
System.out.println("THE END");

Then read content of the new file.

Xcode 9 Swift Language Version (SWIFT_VERSION)

This can happen when you added Core Data to an existing project.
Check the:
<Name>/<Name>.xcdatamodeld/<Name>.xcdatamodel/contents
file.
This file contains an entry "sourceLanguage" that (by default) might have been set to "Swift". Change it to "Objective-C".

How do I kill all the processes in Mysql "show processlist"?

If you don't have information_schema:

mysql -e "show full processlist" | cut -f1 | sed -e 's/^/kill /' | sed -e 's/$/;/' ;  > /tmp/kill.txt
mysql> . /tmp/kill.txt

MySQL - Rows to Columns

Another option,especially useful if you have many items you need to pivot is to let mysql build the query for you:

SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when itemname = ''',
      itemname,
      ''' then itemvalue end),0) AS `',
      itemname, '`'
    )
  ) INTO @sql
FROM
  history;
SET @sql = CONCAT('SELECT hostid, ', @sql, ' 
                  FROM history 
                   GROUP BY hostid');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

FIDDLE Added some extra values to see it working

GROUP_CONCAT has a default value of 1000 so if you have a really big query change this parameter before running it

SET SESSION group_concat_max_len = 1000000;

Test:

DROP TABLE IF EXISTS history;
CREATE TABLE history
(hostid INT,
itemname VARCHAR(5),
itemvalue INT);

INSERT INTO history VALUES(1,'A',10),(1,'B',3),(2,'A',9),
(2,'C',40),(2,'D',5),
(3,'A',14),(3,'B',67),(3,'D',8);

  hostid    A     B     C      D
    1     10      3     0      0
    2     9       0    40      5
    3     14     67     0      8

Javascript: output current datetime in YYYY/mm/dd hh:m:sec format

With jQuery date format :

$.format.date(new Date(), 'yyyy/MM/dd HH:mm:ss');

https://github.com/phstc/jquery-dateFormat

Enjoy

OS X Terminal UTF-8 issues

The following is a summary of what you need to do under OS X Mavericks (10.9). This is all summarized in

http://hints.macworld.com/article.php?story=20060825071728278

  1. Go to Terminal->Preferences->Settings->Advanced.

    Under International, make sure the character encoding is set to Unicode (UTF-8).

    Also, and this is key: under Emulation, make sure that Escape non-ASCII input with Control-V is unchecked (i.e. is not set).

    These two settings fix things for Terminal.

  2. Make sure your locale is set to something that ends in .UTF-8. Type locale and look at the LC_CTYPE line. If it doesn't say something like en_US.UTF-8 (the stuff before the dot might change if you are using a non-US-English locale), then in your Bash .profile or .bashrc in your home directory, add a line like this:

    export LC_CTYPE=en_US.UTF-8
    

    This will fix things for command-line programs in general.

  3. Add the following lines to .inputrc in your home directory (create it if necessary):

    set meta-flag on
    set input-meta on
    set output-meta on
    set convert-meta off
    

    This makes Bash be eight-bit clean, so it will pass UTF-8 characters in and out without messing with them.

Keep in mind you will have to restart Bash (e.g. close and reopen the Terminal window) to get it to pay attention to all the settings you make in 2 and 3 above.

Text file with 0D 0D 0A line breaks

The CRCRLF is known as result of a Windows XP notepad word wrap bug.

For future reference, here's an extract of relevance from the linked blog:

When you press the Enter key on Windows computers, two characters are actually stored: a carriage return (CR) and a line feed (LF). The operating system always interprets the character sequence CR LF the same way as the Enter key: it moves to the next line. However when there are extra CR or LF characters on their own, this can sometimes cause problems.

There is a bug in the Windows XP version of Notepad that can cause extra CR characters to be stored in the display window. The bug happens in the following situation:

If you have the word wrap option turned on and the display window contains long lines that wrap around, then saving the file causes Notepad to insert the characters CR CR LF at each wrap point in the display window, but not in the saved file.

The CR CR LF characters can cause oddities if you copy and paste them into other programs. They also prevent Notepad from properly re-wrapping the lines if you resize the Notepad window.

You can remove the CR CR LF characters by turning off the word wrap feature, then turning it back on if desired. However, the cursor is repositioned at the beginning of the display window when you do this.

How do I seed a random class to avoid getting duplicate random values

In case you can't for some reason use the same Random again and again, try initializing it with something that changes all the time, like the time itself.

new Random(new System.DateTime().Millisecond).Next();

Remember this is bad practice though.

EDIT: The default constructor already takes its seed from the clock, and probably better than we would. Quoting from MSDN:

Random() : Initializes a new instance of the Random class, using a time-dependent default seed value.

The code below is probably your best option:

new Random().Next();

Stopping an Android app from console

adb shell killall -9 com.your.package.name

according to MAC "mandatory access control" you probably have the permission to kill process which is not started by root

have fun!

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

How to execute my SQL query in CodeIgniter

    $sql="Select * from my_table where 1";    
    $query = $this->db->query($SQL);
    return $query->result_array();

How do I create dynamic properties in C#?

I have done exactly this with an ICustomTypeDescriptor interface and a Dictionary.

Implementing ICustomTypeDescriptor for dynamic properties:

I have recently had a requirement to bind a grid view to a record object that could have any number of properties that can be added and removed at runtime. This was to allow a user to add a new column to a result set to enter an additional set of data.

This can be achieved by having each data 'row' as a dictionary with the key being the property name and the value being a string or a class that can store the value of the property for the specified row. Of course having a List of Dictionary objects will not be able to be bound to a grid. This is where the ICustomTypeDescriptor comes in.

By creating a wrapper class for the Dictionary and making it adhere to the ICustomTypeDescriptor interface the behaviour for returning properties for an object can be overridden.

Take a look at the implementation of the data 'row' class below:

/// <summary>
/// Class to manage test result row data functions
/// </summary>
public class TestResultRowWrapper : Dictionary<string, TestResultValue>, ICustomTypeDescriptor
{
    //- METHODS -----------------------------------------------------------------------------------------------------------------

    #region Methods

    /// <summary>
    /// Gets the Attributes for the object
    /// </summary>
    AttributeCollection ICustomTypeDescriptor.GetAttributes()
    {
        return new AttributeCollection(null);
    }

    /// <summary>
    /// Gets the Class name
    /// </summary>
    string ICustomTypeDescriptor.GetClassName()
    {
        return null;
    }

    /// <summary>
    /// Gets the component Name
    /// </summary>
    string ICustomTypeDescriptor.GetComponentName()
    {
        return null;
    }

    /// <summary>
    /// Gets the Type Converter
    /// </summary>
    TypeConverter ICustomTypeDescriptor.GetConverter()
    {
        return null;
    }

    /// <summary>
    /// Gets the Default Event
    /// </summary>
    /// <returns></returns>
    EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
    {
        return null;
    }

    /// <summary>
    /// Gets the Default Property
    /// </summary>
    PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
    {
        return null;
    }

    /// <summary>
    /// Gets the Editor
    /// </summary>
    object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
    {
        return null;
    }

    /// <summary>
    /// Gets the Events
    /// </summary>
    EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
    {
        return new EventDescriptorCollection(null);
    }

    /// <summary>
    /// Gets the events
    /// </summary>
    EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
    {
        return new EventDescriptorCollection(null);
    }

    /// <summary>
    /// Gets the properties
    /// </summary>
    PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
    {
        List<propertydescriptor> properties = new List<propertydescriptor>();

        //Add property descriptors for each entry in the dictionary
        foreach (string key in this.Keys)
        {
            properties.Add(new TestResultPropertyDescriptor(key));
        }

        //Get properties also belonging to this class also
        PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(this.GetType(), attributes);

        foreach (PropertyDescriptor oPropertyDescriptor in pdc)
        {
            properties.Add(oPropertyDescriptor);
        }

        return new PropertyDescriptorCollection(properties.ToArray());
    }

    /// <summary>
    /// gets the Properties
    /// </summary>
    PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
    {
        return ((ICustomTypeDescriptor)this).GetProperties(null);
    }

    /// <summary>
    /// Gets the property owner
    /// </summary>
    object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
    {
        return this;
    }

    #endregion Methods

    //---------------------------------------------------------------------------------------------------------------------------
}

Note: In the GetProperties method I Could Cache the PropertyDescriptors once read for performance but as I'm adding and removing columns at runtime I always want them rebuilt

You will also notice in the GetProperties method that the Property Descriptors added for the dictionary entries are of type TestResultPropertyDescriptor. This is a custom Property Descriptor class that manages how properties are set and retrieved. Take a look at the implementation below:

/// <summary>
/// Property Descriptor for Test Result Row Wrapper
/// </summary>
public class TestResultPropertyDescriptor : PropertyDescriptor
{
    //- PROPERTIES --------------------------------------------------------------------------------------------------------------

    #region Properties

    /// <summary>
    /// Component Type
    /// </summary>
    public override Type ComponentType
    {
        get { return typeof(Dictionary<string, TestResultValue>); }
    }

    /// <summary>
    /// Gets whether its read only
    /// </summary>
    public override bool IsReadOnly
    {
        get { return false; }
    }

    /// <summary>
    /// Gets the Property Type
    /// </summary>
    public override Type PropertyType
    {
        get { return typeof(string); }
    }

    #endregion Properties

    //- CONSTRUCTOR -------------------------------------------------------------------------------------------------------------

    #region Constructor

    /// <summary>
    /// Constructor
    /// </summary>
    public TestResultPropertyDescriptor(string key)
        : base(key, null)
    {

    }

    #endregion Constructor

    //- METHODS -----------------------------------------------------------------------------------------------------------------

    #region Methods

    /// <summary>
    /// Can Reset Value
    /// </summary>
    public override bool CanResetValue(object component)
    {
        return true;
    }

    /// <summary>
    /// Gets the Value
    /// </summary>
    public override object GetValue(object component)
    {
          return ((Dictionary<string, TestResultValue>)component)[base.Name].Value;
    }

    /// <summary>
    /// Resets the Value
    /// </summary>
    public override void ResetValue(object component)
    {
        ((Dictionary<string, TestResultValue>)component)[base.Name].Value = string.Empty;
    }

    /// <summary>
    /// Sets the value
    /// </summary>
    public override void SetValue(object component, object value)
    {
        ((Dictionary<string, TestResultValue>)component)[base.Name].Value = value.ToString();
    }

    /// <summary>
    /// Gets whether the value should be serialized
    /// </summary>
    public override bool ShouldSerializeValue(object component)
    {
        return false;
    }

    #endregion Methods

    //---------------------------------------------------------------------------------------------------------------------------
}

The main properties to look at on this class are GetValue and SetValue. Here you can see the component being casted as a dictionary and the value of the key inside it being Set or retrieved. Its important that the dictionary in this class is the same type in the Row wrapper class otherwise the cast will fail. When the descriptor is created the key (property name) is passed in and is used to query the dictionary to get the correct value.

Taken from my blog at:

ICustomTypeDescriptor Implementation for dynamic properties

How can I format the output of a bash command in neat columns

Try

xargs -n2  printf "%-20s%s\n"

or even

xargs printf "%-20s%s\n"

if input is not very large.

symfony2 : failed to write cache directory

I move the whole directory from my Windows installation to a unix production server and I got the same error. To fix it, I just ran these two lines in unix and everything started to run fine

rm -rf app/cache/*
rm -rf app/logs/*

Run task only if host does not belong to a group

You can set a control variable in vars files located in group_vars/ or directly in hosts file like this:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

And run tasks like this:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

For me I put my dependencies in the wrong spot.

buildscript {
  dependencies {
    //Don't put dependencies here.
  }
}

dependencies {
 //Put them here
}

Python + Django page redirect

It's simple:

from django.http import HttpResponseRedirect

def myview(request):
    ...
    return HttpResponseRedirect("/path/")

More info in the official Django docs

Update: Django 1.0

There is apparently a better way of doing this in Django now using generic views.

Example -

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',   
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

There is more in the generic views documentation. Credit - Carles Barrobés.

Update #2: Django 1.3+

In Django 1.5 redirect_to no longer exists and has been replaced by RedirectView. Credit to Yonatan

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

How to restart counting from 1 after erasing table in MS Access?

I always use below approach. I've created one table in database as Table1 with only one column i.e. Row_Id Number (Long Integer) and its value is 0

enter image description here

INSERT INTO <TABLE_NAME_TO_RESET>
SELECT Row_Id AS <COLUMN_NAME_TO_RESET>
FROM Table1;

This will insert one row with 0 value in AutoNumber column, later delete that row.

document.createElement("script") synchronously

This works for modern 'evergreen' browsers that support async/await and fetch.

This example is simplified, without error handling, to show the basic principals at work.

// This is a modern JS dependency fetcher - a "webpack" for the browser
const addDependentScripts = async function( scriptsToAdd ) {

  // Create an empty script element
  const s=document.createElement('script')

  // Fetch each script in turn, waiting until the source has arrived
  // before continuing to fetch the next.
  for ( var i = 0; i < scriptsToAdd.length; i++ ) {
    let r = await fetch( scriptsToAdd[i] )

    // Here we append the incoming javascript text to our script element.
    s.text += await r.text()
  }

  // Finally, add our new script element to the page. It's
  // during this operation that the new bundle of JS code 'goes live'.
  document.querySelector('body').appendChild(s)
}

// call our browser "webpack" bundler
addDependentScripts( [
  'https://code.jquery.com/jquery-3.5.1.slim.min.js',
  'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js'
] )

replace NULL with Blank value or Zero in sql server

You should always return the same type on all case condition:

In the first one you have an character and on the else you have an int.

You can use:

Select convert(varchar(11),isnull(totalamount,0))

or if you want with your solution:

Case when total_amount = 0 then '0'   
else convert(varchar(11),isnull(total_amount, 0))  
end as total_amount  

Exiting out of a FOR loop in a batch file?

Did a little research on this, it appears that you are looping from 1 to 2147483647, in increments of 1.

(1, 1, 2147483647): The firs number is the starting number, the next number is the step, and the last number is the end number.

Edited To Add

It appears that the loop runs to completion regardless of any test conditions. I tested

FOR /L %%F IN (1, 1, 5) DO SET %%F=6

And it ran very quickly.

Second Edit

Since this is the only line in the batch file, you might try the EXIT command:

FOR /L %%F IN (1, 1, 2147483647) DO @IF NOT EXIST %%F EXIT

However, this will also close the DOS prompt window.

Javascript decoding html entities

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);

This sets the innerHTML of a new element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Live demo.

SQL Developer with JDK (64 bit) cannot find JVM

Create directory "bin" in

D:\sqldeveloper\jdk\ Copy

msvcr100.dll from

D:\sqldeveloper\jdk\jre\bin to

D:\sqldeveloper\jdk\bin

CSS: How to align vertically a "label" and "input" inside a "div"?

a more modern approach would be to use css flex-box.

_x000D_
_x000D_
div {_x000D_
  height: 50px;_x000D_
  background: grey;_x000D_
  display: flex;_x000D_
  align-items: center_x000D_
}
_x000D_
<div>_x000D_
  <label for='name'>Name:</label>_x000D_
  <input type='text' id='name' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

a more complex example... if you have multible elements in the flex flow, you can use align-self to align single elements differently to the specified align...

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  align-items: center_x000D_
}_x000D_
_x000D_
* {_x000D_
  margin: 10px_x000D_
}_x000D_
_x000D_
label {_x000D_
  align-self: flex-start_x000D_
}
_x000D_
<div>_x000D_
  <img src="https://de.gravatar.com/userimage/95932142/195b7f5651ad2d4662c3c0e0dccd003b.png?size=50" />_x000D_
  <label>Text</label>_x000D_
  <input placeholder="Text" type="text" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

its also super easy to center horizontally and vertically:

_x000D_
_x000D_
div {_x000D_
  position:absolute;_x000D_
  top:0;left:0;right:0;bottom:0;_x000D_
  background: grey;_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content:center_x000D_
}
_x000D_
<div>_x000D_
  <label for='name'>Name:</label>_x000D_
  <input type='text' id='name' />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert a Python int into a big-endian string of bytes

Using the bitstring module:

>>> bitstring.BitArray(uint=1245427, length=24).bytes
'\x13\x00\xf3'

Note though that for this method you need to specify the length in bits of the bitstring you are creating.

Internally this is pretty much the same as Alex's answer, but the module has a lot of extra functionality available if you want to do more with your data.

How to get a string after a specific substring?

It's an old question but i faced a very same scenario, i need to split a string using as demiliter the word "low" the problem for me was that i have in the same string the word below and lower.

I solved it using the re module this way

import re

string = '...below...as higher prices mean lower demand to be expected. Generally, a high reading is seen as negative (or bearish), while a low reading is seen as positive (or bullish) for the Korean Won.'

use re.split with regex to match the exact word

stringafterword = re.split('\\blow\\b',string)[-1]
print(stringafterword)
' reading is seen as positive (or bullish) for the Korean Won.'

the generic code is:

re.split('\\bTHE_WORD_YOU_WANT\\b',string)[-1]

Hope this can help someone!

Set TextView text from html-formatted string resource in XML

Android does not have a specification to indicate the type of resource string (e.g. text/plain or text/html). There is a workaround, however, that will allow the developer to specify this within the XML file.

  1. Define a custom attribute to specify that the android:text attribute is html.
  2. Use a subclassed TextView.

Once you define these, you can express yourself with HTML in xml files without ever having to call setText(Html.fromHtml(...)) again. I'm rather surprised that this approach is not part of the API.

This solution works to the degree that the Android studio simulator will display the text as rendered HTML.

enter image description here

res/values/strings.xml (the string resource as HTML)

<resources>
<string name="app_name">TextViewEx</string>
<string name="string_with_html"><![CDATA[
       <em>Hello</em> <strong>World</strong>!
 ]]></string>
</resources>

layout.xml (only the relevant parts)

Declare the custom attribute namespace, and add the android_ex:isHtml attribute. Also use the subclass of TextView.

<RelativeLayout
...
xmlns:android_ex="http://schemas.android.com/apk/res-auto"
...>

<tv.twelvetone.samples.textviewex.TextViewEx
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/string_with_html"
    android_ex:isHtml="true"
    />
 </RelativeLayout>

res/values/attrs.xml (define the custom attributes for the subclass)

 <resources>
<declare-styleable name="TextViewEx">
    <attr name="isHtml" format="boolean"/>
    <attr name="android:text" />
</declare-styleable>
</resources>

TextViewEx.java (the subclass of TextView)

 package tv.twelvetone.samples.textviewex;

 import android.content.Context;
 import android.content.res.TypedArray;
 import android.support.annotation.Nullable;
 import android.text.Html;
 import android.util.AttributeSet;
 import android.widget.TextView;

public TextViewEx(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextViewEx, 0, 0);
    try {
        boolean isHtml = a.getBoolean(R.styleable.TextViewEx_isHtml, false);
        if (isHtml) {
            String text = a.getString(R.styleable.TextViewEx_android_text);
            if (text != null) {
                setText(Html.fromHtml(text));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        a.recycle();
    }
}
}

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

Important note on using the synchronized block: careful what you use as lock object!

The code snippet from user2277816 above illustrates this point in that a reference to a string literal is used as locking object. Realize that string literals are automatically interned in Java and you should begin to see the problem: every piece of code that synchronizes on the literal "lock", shares the same lock! This can easily lead to deadlocks with completely unrelated pieces of code.

It is not just String objects that you need to be careful with. Boxed primitives are also a danger, since autoboxing and the valueOf methods can reuse the same objects, depending on the value.

For more information see: https://www.securecoding.cert.org/confluence/display/java/LCK01-J.+Do+not+synchronize+on+objects+that+may+be+reused

How to pass an array into a function, and return the results with an array

Another way is:

$NAME = "John";
$EMAIL = "[email protected]";
$USERNAME = "John123";
$PASSWORD = "1234";
$array = Array ("$NAME","$EMAIL","$USERNAME","$PASSWORD");
function getAndReturn (Array $array){
    return $array;
}
print_r(getAndReturn($array));

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

I have got the same error as :

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/

As, said by @Agaline, i download the outside wheel from this Christoph Gohlke.

If your is Python 3.7 then try to PyAudio-0.2.11-cp37-cp37m-win_amd64.whl and use command as, go to the download directroy and:

pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl and it works.

cartesian product in pandas

As an alternative, one can rely on the cartesian product provided by itertools: itertools.product, which avoids creating a temporary key or modifying the index:

import numpy as np 
import pandas as pd 
import itertools

def cartesian(df1, df2):
    rows = itertools.product(df1.iterrows(), df2.iterrows())

    df = pd.DataFrame(left.append(right) for (_, left), (_, right) in rows)
    return df.reset_index(drop=True)

Quick test:

In [46]: a = pd.DataFrame(np.random.rand(5, 3), columns=["a", "b", "c"])

In [47]: b = pd.DataFrame(np.random.rand(5, 3), columns=["d", "e", "f"])    

In [48]: cartesian(a,b)
Out[48]:
           a         b         c         d         e         f
0   0.436480  0.068491  0.260292  0.991311  0.064167  0.715142
1   0.436480  0.068491  0.260292  0.101777  0.840464  0.760616
2   0.436480  0.068491  0.260292  0.655391  0.289537  0.391893
3   0.436480  0.068491  0.260292  0.383729  0.061811  0.773627
4   0.436480  0.068491  0.260292  0.575711  0.995151  0.804567
5   0.469578  0.052932  0.633394  0.991311  0.064167  0.715142
6   0.469578  0.052932  0.633394  0.101777  0.840464  0.760616
7   0.469578  0.052932  0.633394  0.655391  0.289537  0.391893
8   0.469578  0.052932  0.633394  0.383729  0.061811  0.773627
9   0.469578  0.052932  0.633394  0.575711  0.995151  0.804567
10  0.466813  0.224062  0.218994  0.991311  0.064167  0.715142
11  0.466813  0.224062  0.218994  0.101777  0.840464  0.760616
12  0.466813  0.224062  0.218994  0.655391  0.289537  0.391893
13  0.466813  0.224062  0.218994  0.383729  0.061811  0.773627
14  0.466813  0.224062  0.218994  0.575711  0.995151  0.804567
15  0.831365  0.273890  0.130410  0.991311  0.064167  0.715142
16  0.831365  0.273890  0.130410  0.101777  0.840464  0.760616
17  0.831365  0.273890  0.130410  0.655391  0.289537  0.391893
18  0.831365  0.273890  0.130410  0.383729  0.061811  0.773627
19  0.831365  0.273890  0.130410  0.575711  0.995151  0.804567
20  0.447640  0.848283  0.627224  0.991311  0.064167  0.715142
21  0.447640  0.848283  0.627224  0.101777  0.840464  0.760616
22  0.447640  0.848283  0.627224  0.655391  0.289537  0.391893
23  0.447640  0.848283  0.627224  0.383729  0.061811  0.773627
24  0.447640  0.848283  0.627224  0.575711  0.995151  0.804567

PHP: How to get current time in hour:minute:second?

You can combine both in the same date function call

date("d-m-Y H:i:s");  

Convert a number to 2 decimal places in Java

DecimalFormat df=new DecimalFormat("0.00");

Use this code to get exact two decimal points. Even if the value is 0.0 it will give u 0.00 as output.

Instead if you use:

DecimalFormat df=new DecimalFormat("#.00");  

It wont convert 0.2659 into 0.27. You will get an answer like .27.

How to put a link on a button with bootstrap?

Another trick to get the link color working correctly inside the <button> markup

<button type="button" class="btn btn-outline-success and-all-other-classes"> 
  <a href="#" style="color:inherit"> Button text with correct colors </a>
</button>

Please keep in mind that in bs4 beta e.g. btn-primary-outline changed to btn-outline-primary