Programs & Examples On #Hl7

The HL7 (Health Level Seven) messaging standard is a communication standard for exchanging electronic information in the domain of health care.

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Check Inside the Following Directory for the jar file el-api.jar :C:\apache-tomcat-7.0.39\lib\el-api.jar if it exists then in this directory of your web application WEB-INF\lib\el-api.jar the jar should be removed

SelectSingleNode returning null for known good xml node path using XPath

Just to build upon solving the namespace issues, in my case I've been running into documents with multiple namespaces and needed to handle namespaces properly. I wrote the function below to get a namespace manager to deal with any namespace in the document:

private XmlNamespaceManager GetNameSpaceManager(XmlDocument xDoc)
        XmlNamespaceManager nsm = new XmlNamespaceManager(xDoc.NameTable);
        XPathNavigator RootNode = xDoc.CreateNavigator();
        IDictionary<string, string> NameSpaces = RootNode.GetNamespacesInScope(XmlNamespaceScope.All);

        foreach (KeyValuePair<string, string> kvp in NameSpaces)
            nsm.AddNamespace(kvp.Key, kvp.Value);

        return nsm;

How to filter an array/object by checking multiple values

You can use .filter() method of the Array object:

var filtered = workItems.filter(function(element) {
   // Create an array using `.split()` method
   var cats = element.category.split(' ');

   // Filter the returned array based on specified filters
   // If the length of the returned filtered array is equal to
   // length of the filters array the element should be returned  
   return cats.filter(function(cat) {
       return filtersArray.indexOf(cat) > -1;
   }).length === filtersArray.length;

Some old browsers like IE8 doesn't support .filter() method of the Array object, if you are using jQuery you can use .filter() method of jQuery object.

jQuery version:

var filtered = $(workItems).filter(function(i, element) {
   var cats = element.category.split(' ');

    return $(cats).filter(function(_, cat) {
       return $.inArray(cat, filtersArray) > -1;
    }).length === filtersArray.length;

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

I got this issue on a Web API project. Finally figured out that it was in my "///" method comments. I have these comments set to auto-generate documentation for the API methods. Something in my comments made it go crazy. I deleted all the carriage returns, special characters, etc. Not really sure which thing it didn't like, but it worked.

What are the differences between the BLOB and TEXT datatypes in MySQL?

BLOB stores binary data which are more than 2 GB. Max size for BLOB is 4 GB. Binary data means unstructured data i.e images audio files vedio files digital signature

Text is used to store large string.

How to get a shell environment variable in a makefile?

If you've exported the environment variable:

export demoPath=/usr/local/demo

you can simply refer to it by name in the makefile (make imports all the environment variables you have set):

DEMOPATH = ${demoPath}    # Or $(demoPath) if you prefer.

If you've not exported the environment variable, it is not accessible until you do export it, or unless you pass it explicitly on the command line:

make DEMOPATH="${demoPath}" …

If you are using a C shell derivative, substitute setenv demoPath /usr/local/demo for the export command.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

I was in the same situation as you, the half answers scattered throughout the Internet were quite annoying, since it seemed that many people had the same issue, but no one could be bothered to fully explain how they solved it.

The Sonar docs refer to a GitHub project with examples that are helpful. What I did to solve this was to apply the integration tests logic to regular unit tests (although proper unit tests should be submodule specific, this isn't always the case).

In the parent pom.xml, add these properties:

    <!-- Sonar -->

This will make Sonar pick up unit testing reports for all submodules in the same place (a target folder in the parent project). It also tells Sonar to reuse reports ran manually instead of rolling its own. We just need to make jacoco-maven-plugin run for all submodules by placing this in the parent pom, inside build/plugins:


destFile places the report file in the place where Sonar will look for it and append makes it append to the file rather than overwriting it. This will combine all JaCoCo reports for all submodules in the same file.

Sonar will look at that file for each submodule, since that's what we pointed him at above, giving us combined unit testing results for multi module files in Sonar.

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....


CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 


Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  


╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

How do I give text or an image a transparent background using CSS?

You can use pure CSS 3: rgba(red, green, blue, alpha), where alpha is the level of transparency you want. There is no need for JavaScript or jQuery.

Here is an example:

    background:rgba(192.233, 33, 0.5)

Parsing string as JSON with single quotes?

var str =  "{'a':1}";
str = str.replace(/'/g, '"')
obj = JSON.parse(str);

This solved the problem for me.

What is log4j's default log file dumping path

To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your file. Here is a sample properties file for the same:

# Root logger option
log4j.rootLogger=INFO, file

# Direct log messages to a log file
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Follow this tutorial to learn more about log4j usage:

CSS: Background image and padding

You can just add the padding to tour block element and add background-origin style like so:

.block {
  position: relative;
  display: inline-block;
  padding: 10px 12px;
  border:1px solid #e5e5e5;
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  background-origin: content-box;
  background-image: url(_your_image_);
  height: 14rem;
  width: 10rem;

You can check several

NOW() function in PHP

Use this function:

function getDatetimeNow() {
    $tz_object = new DateTimeZone('Brazil/East');

    $datetime = new DateTime();
    return $datetime->format('Y\-m\-d\ h:i:s');

HTML5: Slider with two inputs possible?

I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying @Wildhoney's code a bit and really like it.

function getVals(){_x000D_
  // Get slider values_x000D_
  var parent = this.parentNode;_x000D_
  var slides = parent.getElementsByTagName("input");_x000D_
    var slide1 = parseFloat( slides[0].value );_x000D_
    var slide2 = parseFloat( slides[1].value );_x000D_
  // Neither slider will clip the other, so make sure we determine which is larger_x000D_
  if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }_x000D_
  var displayElement = parent.getElementsByClassName("rangeValues")[0];_x000D_
      displayElement.innerHTML = slide1 + " - " + slide2;_x000D_
window.onload = function(){_x000D_
  // Initialize Sliders_x000D_
  var sliderSections = document.getElementsByClassName("range-slider");_x000D_
      for( var x = 0; x < sliderSections.length; x++ ){_x000D_
        var sliders = sliderSections[x].getElementsByTagName("input");_x000D_
        for( var y = 0; y < sliders.length; y++ ){_x000D_
          if( sliders[y].type ==="range" ){_x000D_
            sliders[y].oninput = getVals;_x000D_
            // Manually trigger event first time to display values_x000D_
  section.range-slider {_x000D_
    position: relative;_x000D_
    width: 200px;_x000D_
    height: 35px;_x000D_
    text-align: center;_x000D_
section.range-slider input {_x000D_
    pointer-events: none;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    left: 0;_x000D_
    top: 15px;_x000D_
    width: 200px;_x000D_
    outline: none;_x000D_
    height: 18px;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
section.range-slider input::-webkit-slider-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    outline: 0;_x000D_
section.range-slider input::-moz-range-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 10;_x000D_
    -moz-appearance: none;_x000D_
    width: 9px;_x000D_
section.range-slider input::-moz-range-track {_x000D_
    position: relative;_x000D_
    z-index: -1;_x000D_
    background-color: rgba(0, 0, 0, 1);_x000D_
    border: 0;_x000D_
section.range-slider input:last-of-type::-moz-range-track {_x000D_
    -moz-appearance: none;_x000D_
    background: none transparent;_x000D_
    border: 0;_x000D_
  section.range-slider input[type=range]::-moz-focus-outer {_x000D_
  border: 0;_x000D_
<!-- This block can be reused as many times as needed -->_x000D_
<section class="range-slider">_x000D_
  <span class="rangeValues"></span>_x000D_
  <input value="5" min="0" max="15" step="0.5" type="range">_x000D_
  <input value="10" min="0" max="15" step="0.5" type="range">_x000D_

How to represent multiple conditions in a shell if statement?

In Bash:

if [[ ( $g == 1 && $c == 123 ) || ( $g == 2 && $c == 456 ) ]]

Download the Android SDK components for offline install

I work behind a firewall on windows and I have the Same problem. But I managed to fix it:

  • Close all your internet applications (browsers, downloading tools etc...)
  • Start -> Execute -> type cmd then hit Enter (displays the command prompt)
  • Type netstat
  • In the results returned, find your Proxy address :

  • Your proxy address is one of the DISTANTMACHINEx

  • Your proxy port is the port following the ":"
  • Retype this proxy address and the proxy port in the "setting" page of android SDK manager
  • Tick "force https...http://"
  • Retry

How to clear the cache of nginx?

I was experiencing a kind of similar issue:

System setup and Problem: (On a virtualbox I'm web hosting using ubuntu and nginx - PHP webpage refreshes did not reflect changes to external css file). I'm developing website on windows machine and transferring files to nginx via shared folder. It seems nginx does not pick up changes to css file (refreshing in any fashion does not help. Changing css file name is only thing that worked)

Solution: On VM find shared file (css file in my case). Open with nano and compare to file in windows share (they appear identical). On VM save shared file with nano. All changes are now reflected in browser. Not sure why this works but it did in my case.

UPDATE: After rebooting the VM server the problem returned. Following the instructions under Solution made the css responsive to updates again

file_get_contents() how to fix error "Failed to open stream", "No such file"

I hope below solution will work for you all as I was having the same problem with my websites...

For : $json = json_decode(file_get_contents('http://...'));

Replace with below query

$Details= unserialize(file_get_contents('http://......'));

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I think the docs explain the difference and usage of these two functions pretty well:


Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.


Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.

In terms of resources, the newFixedThreadPool will keep all the threads running until they are explicitly terminated. In the newCachedThreadPool Threads that have not been used for sixty seconds are terminated and removed from the cache.

Given this, the resource consumption will depend very much in the situation. For instance, If you have a huge number of long running tasks I would suggest the FixedThreadPool. As for the CachedThreadPool, the docs say that "These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks".

What does <a href="#" class="view"> mean?

The href is probably generated in a javascript function. For example with jQuery:

$(function() {
    $('a.view').attr('href', '');

How does GPS in a mobile phone work exactly?

There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing. Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.

If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.

Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.

Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.

What does "export" do in shell programming?

Well, it generally depends on the shell. For bash, it marks the variable as "exportable" meaning that it will show up in the environment for any child processes you run.

Non-exported variables are only visible from the current process (the shell).

From the bash man page:

export [-fn] [name[=word]] ...
export -p

The supplied names are marked for automatic export to the environment of subsequently executed commands.

If the -f option is given, the names refer to functions. If no names are given, or if the -p option is supplied, a list of all names that are exported in this shell is printed.

The -n option causes the export property to be removed from each name.

If a variable name is followed by =word, the value of the variable is set to word.

export returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or -f is supplied with a name that is not a function.

You can also set variables as exportable with the typeset command and automatically mark all future variable creations or modifications as such, with set -a.

How to use http.client in Node.js if there is basic authorization

This code works in my case, after a lot of research. You will require to install the request npm package.

var url = "";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.checkApi = function (req, res) {
    // do the GET request
        url: url,
        headers: {
            "Authorization": auth
    }, function (error, response, body) {
       { console.error("Error while communication with api and ERROR is :  " + error);
        console.log('body : ', body);


Merging two images in C#/.NET

basically i use this in one of our apps: we want to overlay a playicon over a frame of a video:

Image playbutton;
    playbutton = Image.FromFile(/*somekindofpath*/);
catch (Exception ex)

Image frame;
    frame = Image.FromFile(/*somekindofpath*/);
catch (Exception ex)

using (frame)
    using (var bitmap = new Bitmap(width, height))
        using (var canvas = Graphics.FromImage(bitmap))
            canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
                             new Rectangle(0,
                             new Rectangle(0,
                             (bitmap.Width / 2) - (playbutton.Width / 2),
                             (bitmap.Height / 2) - (playbutton.Height / 2));
        catch (Exception ex) { }

Check if boolean is true?

i personally would prefer

if(true == foo)

there is no chance for the ==/= mistype and i find it more expressive in terms of foo's type. But it is a very subjective question.

Can jQuery get all CSS styles associated with an element?

@marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations:

for (var i = 0; i < css.length; i += 1) {
    s[css[i]] = css.getPropertyValue(css[i]);

Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase().

Execute method on startup in Spring

You can use @EventListener on your component, which will be invoked after the server is started and all beans initialized.

public void onApplicationEvent(ContextClosedEvent event) {


How to redirect verbose garbage collection output to a file?

Java 9 & Unified JVM Logging

JEP 158 introduces a common logging system for all components of the JVM which will change (and IMO simplify) how logging works with GC. JEP 158 added a new command-line option to control logging from all components of the JVM:


For example, the following option:


will log messages tagged with gc tag using info level to stdout. Or this one:


would log messages tagged with gc tag using debug level to a file called gc.txt with no decorations. For more detailed discussion, you can checkout the examples in the JEP page.

How to store the hostname in a variable in a .bat file?

I'm using the environment variable COMPUTERNAME:

copy "C:\Program Files\Windows Resource Kits\Tools\" %SYSTEMROOT%\system32
srvcheck \\%COMPUTERNAME% > c:\shares.txt

JavaScript DOM: Find Element Index In Container

Another example just using a basic loop and index check


<ul id="foo">

JavaScript runs onload/ready or after ul is rendered

var list = document.getElementById("foo"),
    items = list.getElementsByTagName("li");

list.onclick = function(e) {
    var evt = e || window.event,
    src = || evt.srcElement;
    var myIndex = findIndex(src);

function findIndex( elem ) {
    var i, len = items.length;
    for(i=0; i<len; i++) {
        if (items[i]===elem) {
            return i;
    return -1;

Running Example


How to identify server IP address in PHP

This is what you could use as an adaptation of the above examples without worrying about curl installed on your server.

      // create a new cURL resource
      $ch = curl_init ();

      // set URL and other appropriate options
      curl_setopt ($ch, CURLOPT_URL, "");
      curl_setopt ($ch, CURLOPT_HEADER, 0);
      curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

      // grab URL and pass it to the browser

      $ip = curl_exec ($ch);
      echo "The public ip for this server is: $ip";
      // close cURL resource, and free up system resources
      curl_close ($ch);

must declare a named package eclipse because this compilation unit is associated to the named module

The "delete at your Project Explorer tab" answer is the easiest and most straightforward answer, but

for those who would want a little more understanding or control of what's happening, the following alternate methods may be desirable;

  • make an ever so slightly more realistic application; com.YourCompany.etc or just com.HelloWorld (Project name: com.HelloWorld and class name: HelloWorld)


  • when creating the java project; when in the Create Java Project dialog, don't choose Finish but Next, and deselect Create file

How to calculate time elapsed in bash script?

Here is a solution using only the date commands capabilities using "ago", and not using a second variable to store the finish time:


# save the current time
start_time=$( date +%s.%N )

# tested program
sleep 1

# the current time after the program has finished
# minus the time when we started, in seconds.nanoseconds
elapsed_time=$( date +%s.%N --date="$start_time seconds ago" )

echo elapsed_time: $elapsed_time

this gives:

$ ./ 
elapsed_time: 1.002257120

'console' is undefined error for Internet Explorer

I am only using console.log in my code. So I include a very short 2 liner

var console = console || {};
console.log = console.log || function(){};

YouTube Autoplay not working

This code allows you to autoplay iframe video

<iframe src=""  width="560" height="315"  frameborder="0" allowfullscreen></iframe>

Here Is working fiddle

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.

You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       N(N), R(R)
       for (int c = 1; c <= R; ++c)

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;

       return ret;


   int N, R;
   combination_t curr;

int main(int argc, char **argv)
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
        combinations::combination_t c =;
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    return cs.generated;

test output:


Does Spring Data JPA have any way to count entites using method name resolving?

As long as you do not use 1.4 version, you can use explicit annotation:


@Query("select count(e) from Product e where e.area.code = ?1")
long countByAreaCode(String code);

Difference between dict.clear() and assigning {} in Python

As an illustration for the things already mentioned before:

>>> a = {1:2}
>>> id(a)
>>> a.clear()
>>> id(a)
>>> a = {}
>>> id(a)

Using 'starts with' selector on individual class names

Classes that start with "apple-" plus classes that contain " apple-"

$("div[class^='apple-'],div[class*=' apple-']")

Top 5 time-consuming SQL queries in Oracle

While searching I got the following query which does the job with one assumption(query execution time >6 seconds)

SELECT username, sql_text, sofar, totalwork, units

FROM v$sql,v$session_longops

WHERE sql_address = address AND sql_hash_value = hash_value

ORDER BY address, hash_value, child_number;

I think above query will list the details for current user.

Comments are welcome!!

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

Additionally to Bruno's answer I ended up registering the same port for localhost. Otherwise VS2015 was giving me Access Denied error on server start.

netsh http add urlacl url=http://localhost:{port}/ user=everyone

May be it's because I have binding for localhost in aplicationhost.config also.

How to find unused/dead code in java projects

Code coverage tools, such as Emma, Cobertura, and Clover, will instrument your code and record which parts of it gets invoked by running a suite of tests. This is very useful, and should be an integral part of your development process. It will help you identify how well your test suite covers your code.

However, this is not the same as identifying real dead code. It only identifies code that is covered (or not covered) by tests. This can give you false positives (if your tests do not cover all scenarios) as well as false negatives (if your tests access code that is actually never used in a real world scenario).

I imagine the best way to really identify dead code would be to instrument your code with a coverage tool in a live running environment and to analyse code coverage over an extended period of time.

If you are runnning in a load balanced redundant environment (and if not, why not?) then I suppose it would make sense to only instrument one instance of your application and to configure your load balancer such that a random, but small, portion of your users run on your instrumented instance. If you do this over an extended period of time (to make sure that you have covered all real world usage scenarios - such seasonal variations), you should be able to see exactly which areas of your code are accessed under real world usage and which parts are really never accessed and hence dead code.

I have never personally seen this done, and do not know how the aforementioned tools can be used to instrument and analyse code that is not being invoked through a test suite - but I am sure they can be.

Building a fat jar using maven

An alternative is to use the maven shade plugin to build an uber-jar.

    <version> Your Version Here </version>
            <!-- put your configurations here -->

matrix multiplication algorithm time complexity

The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).

There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.

See this wikipedia article on Matrix Multiplication for more information.

PHP float with 2 decimal places: .00

You can show float numbers

  • with a certain number of decimals
  • with a certain format (localised)


$myNonFormatedFloat = 5678.9

$myGermanNumber = number_format($myNonFormatedFloat, 2, ',', '.'); // -> 5.678,90

$myAngloSaxonianNumber = number_format($myNonFormatedFloat, 2, '.', ','); // -> 5,678.90 

Note that, the

1st argument is the float number you would like to format

2nd argument is the number of decimals

3rd argument is the character used to visually separate the decimals

4th argument is the character used to visually separate thousands

Display more Text in fullcalendar

as a possible solution: Add some extra more content to the title. Overwrite this css style:

 .fc-day-grid-event .fc-content {
   white-space: normal; 


Yes it stops execution so this is generally preferable to HAVING COUNT(*) > 0 which often won't.

With EXISTS if you look at the execution plan you will see that the actual number of rows coming out of table1 will not be more than 1 irrespective of number of matching records.

In some circumstances SQL Server can convert the tree for the COUNT query to the same as the one for EXISTS during the simplification phase (with a semi join and no aggregate operator in sight) an example of that is discussed in the comments here.

For more complicated sub trees than shown in the question you may occasionally find the COUNT performs better than EXISTS however. Because the semi join needs only retrieve one row from the sub tree this can encourage a plan with nested loops for that part of the tree - which may not work out optimal in practice.

Make a directory and copy a file

You can use the shell for this purpose.

Set shl = CreateObject("WScript.Shell") 
shl.Run "cmd mkdir YourDir" & copy "

How do I resize a Google Map with JavaScript after it has loaded?

for Google Maps v3, you need to trigger the resize event differently:

google.maps.event.trigger(map, "resize");

See the documentation for the resize event (you'll need to search for the word 'resize'):


This answer has been here a long time, so a little demo might be worthwhile & although it uses jQuery, there's no real need to do so.

$(function() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  var map = new google.maps.Map($("#map-canvas")[0], mapOptions);

  // listen for the window resize event & trigger Google Maps to update too
  $(window).resize(function() {
    // (the 'map' here is the result of the created 'var map = ...' above)
    google.maps.event.trigger(map, "resize");
body {
  height: 100%;
#map-canvas {
  min-width: 200px;
  width: 50%;
  min-height: 200px;
  height: 80%;
  border: 1px solid blue;
<script src=""></script>
<script src=""></script>
Google Maps resize demo
<div id="map-canvas"></div>

UPDATE 2018-05-22

With a new renderer release in version 3.32 of Maps JavaScript API the resize event is no longer a part of Map class.

The documentation states

When the map is resized, the map center is fixed

  • The full-screen control now preserves center.

  • There is no longer any need to trigger the resize event manually.


google.maps.event.trigger(map, "resize"); doesn't have any effect starting from version 3.32

Call one constructor from another

Error handling and making your code reusable is key. I added string to int validation and it is possible to add other types if needed. Solving this problem with a more reusable solution could be this:

public class Sample
    public Sample(object inputToInt)
        _intField = objectToInt(inputToInt);

    public int IntProperty => _intField;

    private readonly int _intField;

public static int objectToInt(object inputToInt)
    switch (inputToInt)
            case int inputInt:
                return inputInt;
            case string inputString:
            if (!int.TryParse(inputString, out int parsedInt))
                throw new InvalidParameterException($"The input {inputString} could not be parsed to int");
            return parsedInt;

                throw new InvalidParameterException($"Constructor do not support {inputToInt.GetType().Name}");

How to disable mouse scroll wheel scaling with Google Maps API

For someone that wondering how to disable the Javascript Google Map API

It will enable the zooming scroll if you click the map once. And disable after your mouse exit the div.

Here is some example

var map;_x000D_
var element = document.getElementById('map-canvas');_x000D_
function initMaps() {_x000D_
  map = new google.maps.Map(element , {_x000D_
    zoom: 17,_x000D_
    scrollwheel: false,_x000D_
    center: {_x000D_
      lat: parseFloat(-33.915916),_x000D_
      lng: parseFloat(151.147159)_x000D_
//disable scrolling on a map (smoother UX)_x000D_
jQuery('.map-container').on("mouseleave", function(){_x000D_
  map.setOptions({ scrollwheel: false });_x000D_
jQuery('.map-container').on("mousedown", function() {_x000D_
  map.setOptions({ scrollwheel: true });_x000D_
.big-placeholder {_x000D_
  background-color: #1da261;_x000D_
  height: 300px;_x000D_
<script src=""></script>_x000D_
      <div class="big-placeholder">_x000D_
      <!-- START IMPORTANT part -->_x000D_
      <div class="map-container">_x000D_
        <div id="map-canvas" style="min-height: 400px;"></div>  _x000D_
      <!-- END IMPORTANT part-->_x000D_
      <div class="big-placeholder">_x000D_
      <script async defer src="">_x000D_

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

How about playing with these two properties?

disableClose: boolean - Whether the user can use escape or clicking on the backdrop to close the modal.

hasBackdrop: boolean - Whether the dialog has a backdrop.

How to solve SyntaxError on autogenerated

I had the exact same error, but then I later found out that I forget to activate the conda environment which had django and other required packages installed.

Solution: Create a conda or virtual environment with django installed, and activate it before you use the command: $ python migrate

What does auto do in margin:0 auto?

From the CSS specification on Calculating widths and margins for Block-level, non-replaced elements in normal flow:

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

How do I print part of a rendered HTML page in JavaScript?

Try this JavaScript code:

function printout() {

    var newWindow =;

How do I get the SelectedItem or SelectedIndex of ListView in

VB6: Listview1.selecteditem

VB10: Listview1.FocusedItem.Text

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists:

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

Instagram: Share photo from webpage

Updated June 2020

It is no longer possible... allegedly. If you have a Facebook or Instagram dedicated contact (because you work in either a big agency or with a big client) it may potentially be possible depending on your use case, but it's highly discouraged.

Before December 2019:

It is now "possible":

The Content Publishing API is a subset of Instagram Graph API endpoints that allow you to publish media objects. Publishing media objects with this API is a two step process — you first create a media object container, then publish the container on your Business Account.

Its worth noting that "The Content Publishing API is in closed beta with Facebook Marketing Partners and Instagram Partners only. We are not accepting new applicants at this time." from

Difference between Node object and Element object?

Best source of information for all of your DOM woes

"Objects implementing the Document, DocumentFragment, DocumentType, Element, Text, ProcessingInstruction, or Comment interface (simply called nodes) participate in a tree."

"Element nodes are simply known as elements."

What is your most productive shortcut with Vim?

nnoremap q; q: in my .vimrc, keeps the flow when crafting a complicated search&replace.

javascript /jQuery - For Loop

.each() should work for you. or or you could use .map.

var newArray = $(array).map(function(i) {
    return $('#event' + i, response).html();

Edit: I removed the adding of the prepended 0 since it is suggested to not use that.

If you must have it use

var newArray = $(array).map(function(i) {
    var number = '' + i;
    if (number.length == 1) {
        number = '0' + number;
    return $('#event' + number, response).html();

Extracting specific columns in numpy array

You can use the following:

extracted_data = data.ix[:,['Column1','Column2']]

Ruby max integer

Reading the friendly manual? Who'd want to do that?

start =
largest_known_fixnum = 1
smallest_known_bignum = nil

until smallest_known_bignum == largest_known_fixnum + 1
  if smallest_known_bignum.nil?
    next_number_to_try = largest_known_fixnum * 1000
    next_number_to_try = (smallest_known_bignum + largest_known_fixnum) / 2 # Geometric mean would be more efficient, but more risky

  if next_number_to_try <= largest_known_fixnum ||
       smallest_known_bignum && next_number_to_try >= smallest_known_bignum
    raise "Can't happen case" 

  case next_number_to_try
    when Bignum then smallest_known_bignum = next_number_to_try
    when Fixnum then largest_known_fixnum = next_number_to_try
    else raise "Can't happen case"

finish =
puts "The largest fixnum is #{largest_known_fixnum}"
puts "The smallest bignum is #{smallest_known_bignum}"
puts "Calculation took #{finish - start} seconds"

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

Started working after adding property:


[email protected]
[email protected]

How can I change default dialog button text color in android 5

The simpliest solution is:; //Only after .show() was called

How to show two figures using matplotlib?

Alternatively to calling at the end of the script, you can also control each figure separately doing:

f = plt.figure(1)

g = plt.figure(2)


In this case you must call raw_input to keep the figures alive. This way you can select dynamically which figures you want to show

Note: raw_input() was renamed to input() in Python 3

How do you push just a single Git branch (and no other branches)?

So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.

To push the contents of foo to origin/master, you first need to set its upstream:

git checkout foo
git branch -u origin/master

Then you can push to this branch using:

git push origin HEAD:master

In the last command you can add --force to replace the entire history of origin/master with that of foo.

How to add a class to body tag?



selecting an entire row based on a variable excel vba

One needs to make sure the space between the variables and '&' sign. Check the image. (Red one showing invalid commands)


The correct solution is

Dim copyToRow: copyToRow = 5      
Rows(copyToRow & ":" & copyToRow).Select

Check whether an input string contains a number in javascript

If I'm not mistaken, the question requires "contains number", not "is number". So:

function hasNumber(myString) {
  return /\d/.test(myString);

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

Is this what you're asking for?

int[] numbers = { 1, 2, 3 };
numbers.ToList().ForEach(n => Console.WriteLine(n));

Command / failed with exit code 1

In my case,

Build Phases -> check Compile Sources files -> delete xxx.swift files that xcode says "can't find "xxx.swift"

IntelliJ and Tomcat.. Howto..?

Which version of IntelliJ are you using? Note that since last year, IntelliJ exists in two versions:

  • Ultimate Edition, which is the complete IDE
  • Community Edition, which is free but does not support JavaEE developments.

(see differences here)

In case you are using the Community Edition, you will not be able to manage a Tomcat installation.

In case you are using the Ultimate Edition, you can have a look at:

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

I had a problem where it did not allow me to insert it even after setting the IDENTITY_INSERT ON.

The problem was that i did not specify the column names and for some reason it did not like it.

INSERT INTO tbl Values(vals)

So basically do the full INSERT INTO tbl(cols) Values(vals)

Recording video feed from an IP camera over a network

about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.

Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.

So i found the solution!

If you want something done right, do it yourself.

I present to you Shinobi! Shinobi : The Open Source CCTV Platform

enter image description here

Convert/cast an stdClass object to another class

And yet another approach using the decorator pattern and PHPs magic getter & setters:

// A simple StdClass object    
$stdclass = new StdClass();
$stdclass->foo = 'bar';

// Decorator base class to inherit from
class Decorator {

    protected $object = NULL;

    public function __construct($object)
       $this->object = $object;  

    public function __get($property_name)
        return $this->object->$property_name;   

    public function __set($property_name, $value)
        $this->object->$property_name = $value;   

class MyClass extends Decorator {}

$myclass = new MyClass($stdclass)

// Use the decorated object in any type-hinted function/method
function test(MyClass $object) {
    echo $object->foo . '<br>';
    $object->foo = 'baz';
    echo $object->foo;   


Failed to locate the winutils binary in the hadoop binary path

Simple Solution: Download it from here and add to $HADOOP_HOME/bin



For hadoop-2.6.0 you can download binaries from Titus Barik blog >>.

I have not only needed to point HADOOP_HOME to extracted directory [path], but also provide system property -Djava.library.path=[path]\bin to load native libs (dll).

Convert Python dict into a dataframe

d = {'Date': list(yourDict.keys()),'Date_Values': list(yourDict.values())}
df = pandas.DataFrame(data=d)

If you don't encapsulate yourDict.keys() inside of list() , then you will end up with all of your keys and values being placed in every row of every column. Like this:

Date \ 0 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
1 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
2 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
3 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...
4 (2012-06-08, 2012-06-09, 2012-06-10, 2012-06-1...

But by adding list() then the result looks like this:

Date Date_Values 0 2012-06-08 388 1 2012-06-09 388 2 2012-06-10 388 3 2012-06-11 389 4 2012-06-12 389 ...

ng-mouseover and leave to toggle item using mouse in angularjs

I'd probably change your example to look like this:

<ul ng-repeat="task in tasks">
  <li ng-mouseover="enableEdit(task)" ng-mouseleave="disableEdit(task)">{{}}</li>
  <span ng-show="task.editable"><a>Edit</a></span>

$scope.enableEdit = function(item){
  item.editable = true;

$scope.disableEdit = function(item){
  item.editable = false;

I know it's a subtle difference, but makes the domain a little less bound to UI actions. Mentally it makes it easier to think about an item being editable rather than having been moused over.

Example jsFiddle.

How do I set a program to launch at startup

Thanks to everyone for responding so fast. Joel, I used your option 2 and added a registry key to the "Run" folder of the current user. Here's the code I used for anyone else who's interested.

    using Microsoft.Win32;
    private void SetStartup()
        RegistryKey rk = Registry.CurrentUser.OpenSubKey
            ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);

        if (chkStartUp.Checked)
            rk.SetValue(AppName, Application.ExecutablePath);


redistributable offline .NET Framework 3.5 installer for Windows 8

After several month without real solution for this problem, I suppose that the best solution is to upgrade the application to .NET framework 4.0, which is supported by Windows 8, Windows 10 and Windows 2012 Server by default and it is still available as offline installation for Windows XP.

Execute command on all files in a directory

I'm doing this on my raspberry pi from the command line by running:

for i in *;do omxplayer "$i";done

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

As it mentioned above assigning more than 50 % RAM memory to your emmulator.

For me fixed this way too.

My machine have 8GB and I assigned 4GB for per device. Resetting it solve my problem.

What should I do when 'svn cleanup' fails?

While facing a similar issue, manual merge in the repository sync view helped to solve the issue.

One file name was conflicting with other and it clearly mentioned the issue. Renaming the newer file to a different name resolved it.

CSS grid wrapping

You want either auto-fit or auto-fill inside the repeat() function:

grid-template-columns: repeat(auto-fit, 186px);

The difference between the two becomes apparent if you also use a minmax() to allow for flexible column sizes:

grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));

This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:

Enter image description here

Using auto-fit instead will prevent empty columns, stretching yours further if necessary:

Enter image description here

How do I do a bulk insert in mySQL using node.js

Bulk inserts are possible by using nested array, see the github page

Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')

You just insert a nested array of elements.

An example is given in here

var mysql = require('mysql');
var conn = mysql.createConnection({

var sql = "INSERT INTO Test (name, email, n) VALUES ?";
var values = [
    ['demian', '[email protected]', 1],
    ['john', '[email protected]', 2],
    ['mark', '[email protected]', 3],
    ['pete', '[email protected]', 4]
conn.query(sql, [values], function(err) {
    if (err) throw err;

Note: values is an array of arrays wrapped in an array

[ [ [...], [...], [...] ] ]

There is also a totally different node-msql package for bulk insertion

Commenting out code blocks in Atom

Possible reason: watch out for overlapping keybindings. It has happened in my case and deactivated the initial toggle line comment binding:

enter image description here

The Keybindings you can find in the Edit -> Preferences -> Keybindings of the application navbar.

The solution was overriding binding for github:toggle-patch-selection-mode

enter image description here

Android View shadow

If you are in need of the shadows properly to be applied then you have to do the following.

Consider this view, defined with a background drawable:

    android:background="@drawable/myrect" />

The background drawable is defined as a rectangle with rounded corners:

<shape xmlns:android=""
    <solid android:color="#42000000" />
    <corners android:radius="5dp" />

This is the recomended way of appying shadows check this out

What does it mean to "call" a function in Python?

When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:

def add(a,b):
    return a + b

you would call the function like this:


which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:

answer = add(4,7)

Which would set the variable answer equal to 11 in this case.

Python function global variables?

You can directly access a global variable inside a function. If you want to change the value of that global variable, use "global variable_name". See the following example:

var = 1
def global_var_change():
      global var
      var = "value changed"
global_var_change() #call the function for changes
print var

Generally speaking, this is not a good programming practice. By breaking namespace logic, code can become difficult to understand and debug.

How to Exit a Method without Exiting the Program?

There are two ways to exit a method early (without quitting the program):

  • Use the return keyword.
  • Throw an exception.

Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.

If your method returns void then you can write return without a value:


Specifically about your code:

  • There is no need to write the same test three times. All those conditions are equivalent.
  • You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:

    if (textBox1.Text == String.Empty)
        textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    return; // Are you sure you want the return to be here??
  • If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.

  • You might want to use Environment.Newline instead of "\r\n".
  • You might want to consider another way to display invalid input other than writing messages to a text box.

How to detect if a string contains special characters?

SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)

How to detect the currently pressed key?

if (Control.ModifierKeys == Keys.Shift)
    //Shift is pressed

The cursor x/y position is a property, and a keypress (like a mouse click/mousemove) is an event. Best practice is usually to let the interface be event driven. About the only time you would need the above is if you're trying to do a shift + mouseclick thing.

How to set default Checked in checkbox ReactJS?

If someone wants to handle dynamic data with multiple rows, this is for handing dynamic data.

You can check if the rowId is equal to 0.

If it is equal to 0, then you can set the state of the boolean value as true.

interface MyCellRendererState {
    value: boolean;
constructor(props) {
        this.state = {
            value: props.value ? props.value : false
        this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
handleCheckboxChange() {
        this.setState({ value: !this.state.value });
render() {
        const { value } = this.state;
        const rowId = this.props.rowIndex
        if (rowId === 0) {
           this.state = {
             value : true }
        return ( 
          <div onChange={this.handleCheckboxChange}>

Java: getMinutes and getHours

int hr=Time.valueOf(;
int minutes=Time.valueOf(;

These functions will return int values in hours and minutes.

How to remove all namespaces from XML with C#?

Another solution that takes into account possibly interleaving TEXT and ELEMENT nodes, e.g.:



using System.Linq;

namespace System.Xml.Linq
    public static class XElementTransformExtensions
        public static XElement WithoutNamespaces(this XElement source)
            return new XElement(source.Name.LocalName,

        public static XAttribute WithoutNamespaces(this XAttribute source)
            return !source.IsNamespaceDeclaration
                ? new XAttribute(source.Name.LocalName, source.Value)
                : default(XAttribute);

        public static XNode WithoutNamespaces(this XNode source)
                source is XElement
                    ? WithoutNamespaces((XElement)source)
                    : source;

Import regular CSS file in SCSS file?

Good news everyone, Chris Eppstein created a compass plugin with inline css import functionality:

Now, importing a CSS file is as easy as:

@import "CSS:library/some_css_file"

Better way to get type of a Javascript variable?

Angus Croll recently wrote an interesting blog post about this -

He goes through the pros and cons of the various methods then defines a new method 'toType' -

var toType = function(obj) {
  return ({})\s([a-zA-Z]+)/)[1].toLowerCase()

concat scope variables into string in angular directive expression

<a ngHref="/path/{{obj.val1}}/{{obj.val2}}">{{obj.val1}}, {{obj.val2}}</a>

How to set Default Controller in MVC 4 & MVC 5

I didnt see this question answered:

How should I setup a default Area when the application starts?

So, here is how you can set up a default Area:

var route = routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    ).DataTokens = new RouteValueDictionary(new { area = "MyArea" });

Java simple code: Unexpected end of file from server

In my case it was solved just passing proxy to connection. Thanks to @Andreas Panagiotidis.

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<YOUR.HOST>", 80)));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy);

Passing a URL with brackets to curl

Never mind, I found it in the docs:

              This  option  switches  off  the "URL globbing parser". When you set this option, you can
              specify URLs that contain the letters {}[] without having them being interpreted by  curl
              itself.  Note  that  these  letters  are not normal legal URL contents but they should be
              encoded according to the URI standard.

Python 2.7 getting user input and manipulating as string without quotations

The issue seems to be resolved in Python version 3.4.2.

testVar = input("Ask user for something.")

Will work fine.

How to stretch a table over multiple pages

You should \usepackage{longtable}.

how do I change text in a label with swift?

Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:

self.simpleLabel.text = "message"

Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.

Pass correct "this" context to setTimeout callback?

If you're using underscore, you can use bind.


if (this.options.destroyOnHide) {
     setTimeout(_.bind(this.tip.destroy, this), 1000);

Event binding on dynamically created elements?

You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:

function addCallbacks(eles){


// ... add elements ...

Forcing anti-aliasing using css: Is this a myth?

I think you got it a bit wrong. Someone in the thread you pasted says that you can stop anti-aliasing by using px instead of pt, not that you can force it by using the latter. I'm a bit sceptical to both of the claims though...

Utilizing multi core for tar+gzip/bzip compression/decompression

You can also use the tar flag "--use-compress-program=" to tell tar what compression program to use.

For example use:

tar -c --use-compress-program=pigz -f tar.file dir_to_zip 

How to retrieve available RAM from Windows command line?

systeminfo is a command that will output system information, including available memory

How to iterate over the file in python

with open('test.txt', 'r') as inf, open('test1.txt', 'w') as outf:
    for line in inf:
        line = line.strip()
        if line:
                outf.write(str(int(line, 16)))
            except ValueError:
                print("Could not parse '{0}'".format(line))

jQuery .attr("disabled", "disabled") not working in Chrome

if you are removing all disabled attributes from input, then why not just do:


Then after ajax success:

$("input[type='text']").attr('disabled', true);

Make sure you use remove the disabled attribute before submit, or it won't submit that data. If you need to submit it before changing, you need to use readonly instead.

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

openssl s_client using a proxy

since openssl v1.1.0

C:\openssl>openssl version
OpenSSL 1.1.0g  2 Nov 2017
C:\openssl>openssl s_client -proxy -connect -CAfile C:\TEMP\internalCA.crt
depth=2 DC = com, DC = xxxx, CN = xxxx CA interne
verify return:1
depth=1 C = FR, L = CROIX, CN = svproxysg1, emailAddress = [email protected]
verify return:1
depth=0 C = US, ST = California, L = Mountain View, O = Google Inc, CN =
verify return:1
Certificate chain
 0 s:/C=US/ST=California/L=Mountain View/O=Google Inc/
   i:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
 1 s:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
   i:/DC=com/DC=xxxxx/CN=xxxxx CA interne
Server certificate

UIButton Image + Text IOS

Xcode-9 and Xcode-10 Apple done few changes regarding Edge Inset now, you can change it under size-inspector.

Please follow below steps:

Step-1: Input text and select image which you want to show:

enter image description here

Step-2: Select button control as per your requirement as shown in below image:

enter image description here

Step-3: Now go-to size inspector and add value as per your requirement:

enter image description here

Remove or adapt border of frame of legend using matplotlib

One more related question, since it took me forever to find the answer:

How to make the legend background blank (i.e. transparent, not white):

legend = plt.legend()

Warning, you want 'none' (the string). None means the default color instead.

What is the meaning of "Failed building wheel for X" in pip install?

Error :

System : aws ec2 instance (t2 small)

issue : while installing opencv python via

pip3 install opencv-python

  Problem with the CMake installation, aborting build. CMake executable is cmake
  Failed building wheel for opencv-python
  Running clean for opencv-python

What worked for me

pip3 install --upgrade pip setuptools wheel

After this you still might received fallowing error error

    from .cv2 import *
ImportError: cannot open shared object file: No such file or directory

Installing libgl solved the error for me.

sudo apt update
sudo apt install libgl1-mesa-glx

Hope this helps

How to view file diff in git before commit

I think this is the perfect use case warranting a GUI. - Although I totally understand that it can also be achieved well enough within the command line.

Personally, every commit of mine, I do from the git-gui. In which I can make multiple atomic commits with separate hunks/lines if it makes sense to do so.

Gut Gui enables viewing of the diffs in a well formatted colored interface, is rather light. Looks like this is something you should checkout too.

Checking character length in ruby

Verification, do not forget the to_s

 def nottolonng?(value)
   if value.to_s.length <=8
     return true
     return false

Shortcuts in Objective-C to concatenate NSStrings

Inspired by NSMutableString idea from Chris, I make a perfect macro imho. It supports insert nil elements without any Exceptions.

#import <libextobjc/metamacros.h>

#define STR_CONCAT(...) \
    ({ \
        __auto_type str__ = [NSMutableString string]; \
        metamacro_foreach_cxt(never_use_immediately_str_concatify_,, str__, __VA_ARGS__) \
        (NSString *)str__.copy; \

#define never_use_immediately_str_concatify_(INDEX, CONTEXT, VAR) \
    [CONTEXT appendString:VAR ?: @""];


STR_CONCAT(@"button_bg_", @(count).stringValue, @".png"); 
// button_bg_2.png

If you like, you can use id type as parameter by using [VAR description] instead of NSString.

tqdm in Jupyter Notebook prints new progress bars repeatedly

If the other tips here don't work and - just like me - you're using the pandas integration through progress_apply, you can let tqdm handle it:

from tqdm.autonotebook import tqdm

df.progress_apply(row_function, axis=1)

The main point here lies in the tqdm.autonotebook module. As stated in their instructions for use in IPython Notebooks, this makes tqdm choose between progress bar formats used in Jupyter notebooks and Jupyter consoles - for a reason still lacking further investigations on my side, the specific format chosen by tqdm.autonotebook works smoothly in pandas, while all others didn't, for progress_apply specifically.

Get most recent file in a directory on Linux

using R recursive option .. you may consider this as enhancement for good answers here

ls -arRtlh | tail -50

angularjs to output plain text instead of html

Use this function like

   return this ? String(this).replace(/<[^>]+>/gm, '') : '';

  "<span>My text</span>".text()
  My text


CSS transition fade on hover

I recommend you to use an unordered list for your image gallery.

You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.

#photos li {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;

#photos li:hover {
    opacity: 1;

Counting the number of True Booleans in a Python List

If you are only concerned with the constant True, a simple sum is fine. However, keep in mind that in Python other values evaluate as True as well. A more robust solution would be to use the bool builtin:

>>> l = [1, 2, True, False]
>>> sum(bool(x) for x in l)

UPDATE: Here's another similarly robust solution that has the advantage of being more transparent:

>>> sum(1 for x in l if x)

P.S. Python trivia: True could be true without being 1. Warning: do not try this at work!

>>> True = 2
>>> if True: print('true')
>>> l = [True, True, False, True]
>>> sum(l)
>>> sum(bool(x) for x in l)
>>> sum(1 for x in l if x)

Much more evil:

True = False

How to get document height and width without using jquery

If you want to get the full width of the page, including overflow, use document.body.scrollWidth.

How does Python manage int and long?

Python 2 will automatically set the type based on the size of the value. A guide of max values can be found below.

The Max value of the default Int in Python 2 is 65535, anything above that will be a long

For example:

>> print type(65535)
<type 'int'>
>>> print type(65536*65536)
<type 'long'>

In Python 3 the long datatype has been removed and all integer values are handled by the Int class. The default size of Int will depend on your CPU architecture.

For example:

  • 32 bit systems the default datatype for integers will be 'Int32'
  • 64 bit systems the default datatype for integers will be 'Int64'

The min/max values of each type can be found below:

  • Int8: [-128,127]
  • Int16: [-32768,32767]
  • Int32: [-2147483648,2147483647]
  • Int64: [-9223372036854775808,9223372036854775807]
  • Int128: [-170141183460469231731687303715884105728,170141183460469231731687303715884105727]
  • UInt8: [0,255]
  • UInt16: [0,65535]
  • UInt32: [0,4294967295]
  • UInt64: [0,18446744073709551615]
  • UInt128: [0,340282366920938463463374607431768211455]

If the size of your Int exceeds the limits mentioned above, python will automatically change it's type and allocate more memory to handle this increase in min/max values. Where in Python 2, it would convert into 'long', it now just converts into the next size of Int.

Example: If you are using a 32 bit operating system, your max value of an Int will be 2147483647 by default. If a value of 2147483648 or more is assigned, the type will be changed to Int64.

There are different ways to check the size of the int and it's memory allocation. Note: In Python 3, using the built-in type() method will always return <class 'int'> no matter what size Int you are using.

Passing ArrayList from servlet to JSP


        ArrayList<Actor> list = new ArrayList<Actor>();
        list = (ArrayList<Actor>) request.getAttribute("actors");
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">


    <h2>This is Actor Class</h2>
                <th>First Name</th>
                <th>Last Name</th>
            <% for(int i = 0; i < list.size(); i++) {
                Actor actor = new Actor();
                actor = list.get(i);



The model backing the <Database> context has changed since the database was created

Now it's:

protected override void OnModelCreating(DbModelBuilder modelBuilder)

in your YourDbContext.cs file.

Disable form autofill in Chrome without disabling autocomplete

I stumbled upon the weird chrome autofill behaviour today. It happened to enable on fields called: "embed" and "postpassword" (filling there login and password) with no apparent reason. Those fields had already autocomplete set to off.

None of the described methods seemed to work. None of the methods from the another answer worked as well. I came upon my own idea basing on Steele's answer (it might have actually worked, but I require the fixed post data format in my application):

Before the real password, add those two dummy fields:

<input type='text' style='display: none'>
<input type='password' style='display: none'>

Only this one finally disabled autofill altogether for my form.

It's a shame, that disabling such a basic behavior is that hard and hacky.

Save bitmap to file function

Here is the function which help you

private void saveBitmap(Bitmap bitmap,String path){
            try {
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                    // PNG is a lossless format, the compression factor (100) is ignored
                } catch (Exception e) {
                } finally {
                    try {
                        if (outputStream != null) {
                    } catch (IOException e) {
            } catch (Exception e) {

Unable to set data attribute using jQuery Data() API

I was having serious problems with

.data('property', value);

It was not setting the data-property attribute.

Started using jQuery's .attr():

Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.

.attr('property', value)

to set the value and


to retrieve the value.

Now it just works!

Finding the length of an integer in C

You can write a function like this:

unsigned numDigits(const unsigned n) {
    if (n < 10) return 1;
    return 1 + numDigits(n / 10);

Delete data with foreign key in SQL Server table

Set the FOREIGN_KEY_CHECKS before and after your delete SQL statements.



Accessing JSON elements

import json

# some JSON:
json_str =  '{ "name":"Sarah", "age":25, "city":"Chicago"}'

# parse json_str:
json = json.loads(json_str)

# get tags from json   
tags = []
for tag in json:

# print each tag name e your content
for i in range(len(tags)):
    print(tags[i] + ': ' + str(json[tags[i]]))

How to attach a process in gdb

With a running instance of myExecutableName having a PID 15073:

hitting Tab twice after $ gdb myExecu in the command line, will automagically autocompletes to:

$ gdb myExecutableName 15073

and will attach gdb to this process. That's nice!

Rename specific column(s) in pandas

Use the pandas.DataFrame.rename funtion. Check this link for description.

data.rename(columns = {'gdp': 'log(gdp)'}, inplace = True)

If you intend to rename multiple columns then

data.rename(columns = {'gdp': 'log(gdp)', 'cap': 'log(cap)', ..}, inplace = True)

Unicode characters in URLs

Depending on your URL scheme, you can make the UTF-8 encoded part "not important". For example, if you look at Stack Overflow URLs, they're of the following form:

However, the server doesn't actually care if you get the part after the identifier wrong, so this also works:

So if you had a layout like this, then you could potentially use UTF-8 in the part after the identifier and it wouldn't really matter if it got garbled. Of course this probably only works in somewhat specialised circumstances...

Calculate row means on subset of columns

Starting with your data frame DF, you could use the data.table package:


## EDIT: As suggested by @MichaelChirico, setDT converts a
## data.frame to a data.table by reference and is preferred
## if you don't mind losing the data.frame

# EDIT: To get the column name 'Mean':

DF[, .(Mean = rowMeans(.SD)), by = ID]

#      ID     Mean
# [1,]  A 3.666667
# [2,]  B 4.333333
# [3,]  C 3.333333
# [4,]  D 4.666667
# [5,]  E 4.333333

Find ALL tweets from a user (not just the first 3,200)

You can use twitter search page to bypass 3,200 limit. However you have to scroll down many times in the search results page. For example, I searched tweets from @beyinsiz_adam. This is the link of search results:

Now in order to scroll down many times, you can use the following javascript code.

    var myVar=setInterval(function(){myTimer()},1000);
    function myTimer() {

Just run it in the FireBug console. And wait some time to load all tweets.

How to bind bootstrap popover on dynamic elements

I did this and it works for me. "content" is placesContent object. not the html content!

var placesContent = $('#placescontent');
        trigger: "click",
        placement: "bottom",
        container: 'body',
        html : true,
        content : placesContent,

$('#places').on('', function(){
  $('#addPlaceBtn').on('click', addPlace);

<div id="placescontent"><div id="addPlaceBtn">Add</div></div>

$apply already in progress error

If scope must be applied in some cases, then you can set a timeout so that the $apply is deferred until the next tick

setTimeout(function(){ scope.$apply(); });

or wrap your code in a $timeout(function(){ .. }); because it will automatically $apply the scope at the end of execution. If you need your function to behave synchronously, I'd do the first.

Remove duplicate rows in MySQL

Simple and fast for all cases:

CREATE TEMPORARY TABLE IF NOT EXISTS _temp_duplicates AS (SELECT FROM table_with_duplications dub GROUP BY dub.field_must_be_uniq_1, dub.field_must_be_uniq_2 HAVING COUNT(*)  > 1);

DELETE FROM table_with_duplications WHERE id IN (SELECT id FROM _temp_duplicates);

How to split a python string on new line characters

? Splitting line in Python:

Have you tried using str.splitlines() method?:

From the docs:


Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']

Which delimiters are considered?

This method uses the universal newlines approach to splitting lines.

The main difference between Python 2.X and Python 3.X is that the former uses the universal newlines approach to splitting lines, so "\r", "\n", and "\r\n" are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:

  • \v or \x0b: Line Tabulation (added in Python 3.2).
  • \f or \x0c: Form Feed (added in Python 3.2).
  • \x1c: File Separator.
  • \x1d: Group Separator.
  • \x1e: Record Separator.
  • \x85: Next Line (C1 Control Code).
  • \u2028: Line Separator.
  • \u2029: Paragraph Separator.

splitlines VS split:

Unlike str.split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> ''.splitlines()

>>> 'Line 1\n'.splitlines()
['Line 1']

While str.split('\n') returns:

>>> ''.split('\n')

>>> 'Line 1\n'.split('\n')
['Line 1', '']

?? Removing additional whitespace:

If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines(), you could use str.splitlines() together with str.strip():

>>> [str.strip() for str in 'Line 1  \n  \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']

? Removing empty strings (''):

Lastly, if you want to filter out the empty strings from the resulting list, you could use filter():

>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']

>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']

Additional comment regarding the original question:

As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

JUnit tests pass in Eclipse but fail in Maven Surefire

I suddenly experienced this error, and the solution for me was to disable to run tests in parallel.

Your milage may vary, since I could lower number of failing tests by configuring surefire to run parallel tests by ´classes´.:


As I wrote first, this was not enough for my test suite, so I completely disabled parallel by removing the <configuration> section.

Submit HTML form, perform javascript function (alert then redirect)

Looks like your form is submitting which is the default behaviour, you can stop it with this:

<form action="" method="post" onsubmit="completeAndRedirect();return false;">

How to undo a successful "git cherry-pick"?

One command and does not use the destructive git reset command:

GIT_SEQUENCE_EDITOR="sed -i 's/pick/d/'" git rebase -i HEAD~ --autostash

It simply drops the commit, putting you back exactly in the state before the cherry-pick even if you had local changes.

How to hide Bootstrap previous modal when you opening new one?

Toggle both modals


Vue Js - Loop via v-for X times (in a range)

I have solved it with Dov Benjamin's help like that:

  <li v-for="(n,index) in 2">{{ object.price }}</li>

And another method, for both V1.x and 2.x of vue.js

Vue 1:

<p v-for="item in items | limitBy 10">{{ item }}</p>


// Via slice method in computed prop

<p v-for="item in filteredItems">{{ item }}</p>

computed: {
   filteredItems: function () {
     return this.items.slice(0, 10)

How to output git log with the first line only?

You can define a global alias so you can invoke a short log in a more comfortable way:

git config --global alias.slog "log --pretty=oneline --abbrev-commit"

Then you can call it using git slog (it even works with autocompletion if you have it enabled).

Declare a dictionary inside a static class

The correct syntax ( as tested in VS 2008 SP1), is this:

public static class ErrorCode
    public static IDictionary<string, string> ErrorCodeDic;
     static ErrorCode()
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };

jQuery: how to trigger anchor link's click event

It worked for me:

     window.location = $('#myanchor').attr('href');

Most popular screen sizes/resolutions on Android phones

Also, their "device dashboard" stats at:

can be pretty helpful. They are current and derived from Android Market visits.

jQuery ui dialog change title after load-callback

I tried to implement the result of Nick which is:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:

    $("#modal_popup").dialog('option', 'title', 'My New Title');
    $("#modal_popup").dialog({ width: 950, height: 550);

I fixed this by adding the title to the javascript function arguments of each dialog on the page:

function show_popup1() {
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});

function show_popup2() {
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});

What does "while True" mean in Python?

while loops continue to loop until the condition is false. For instance (pseudocode):

i = 0
while i < 10

With each iteration of the loop, i will be incremented by 1, until it is 10. At that point, the condition i < 10 is no longer true, and the loop will complete.

Since the condition in while True is explicitly and always true, the loop will never end (until it is broken out of some other way, usually by a construct like break within the loop body).

How to use php serialize() and unserialize()

Most storage mediums can store string types. They can not directly store a PHP data structure such as an array or object, and they shouldn't, as that would couple the data storage medium with PHP.

Instead, serialize() allows you to store one of these structs as a string. It can be de-serialised from its string representation with unserialize().

If you are familiar with json_encode() and json_decode() (and JSON in general), the concept is similar.

change values in array when doing foreach

To add or delete elements entirely which would alter the index, by way of extension of zhujy_8833 suggestion of slice() to iterate over a copy, simply count the number of elements you have already deleted or added and alter the index accordingly. For example, to delete elements:

let values = ["A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8"];
let count = 0;
values.slice().forEach((value, index) => {
    if (value === "A2" || value === "A5") {
        values.splice(index - count++, 1);

// Expected: [ 'A0', 'A1', 'A3', 'A4', 'A6', 'A7', 'A8' ]

To insert elements before:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - count--, 0, 'newVal');

// Expected: ['newVal', A0, 'A1', 'A2', 'A3', 'A4', 'A5', 'newVal', 'A6', 'A7', 'newVal', 'A8' ]

To insert elements after:

if (value === "A0" || value === "A6" || value === "A8") {
    values.splice(index - --count, 0, 'newVal');

// Expected: ['A0', 'newVal', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'newVal', 'A7', 'A8', 'newVal']

To replace an element:

if (value === "A3" || value === "A4" || value === "A7") {
    values.splice(index, 1, 'newVal');

// Expected: [ 'A0', 'A1', 'A2', 'newVal', 'newVal', 'A5', 'A6', 'newVal', 'A8' ]

Note: if implementing both 'before' and 'after' inserts, code should handle 'before' inserts first, other way around would not be as expected

Try-catch block in Jenkins pipeline script

Look up the AbortException class for Jenkins. You should be able to use the methods to get back simple messages or stack traces. In a simple case, when making a call in a script block (as others have indicated), you can call getMessage() to get the string to echo to the user. Example:

script {
        try {
            sh "sudo docker rmi frontend-test"
        } catch (err) {
            echo err.getMessage()
            echo "Error detected, but we will continue."
        ...continue with other code...

What's the difference between lists and tuples?

Just a quick extension to list vs tuple responses:

  • Due to dynamic nature, list allocates more bit buckets than the actual memory required. This is done to prevent costly reallocation operation in case extra items are appended in the future.

  • On the other hand, being static, lightweight tuple object does not reserve extra memory required to store them.

CSS for the "down arrow" on a <select> element?

There's a cool CSS-only solution to styling dropdowns here:

Basically, wrap the select in a container div, style the select to be 18px wider than the container with a transparent background, give overflow:hidden to the container (to chop off the browser-generated arrow), and add your background image with stylized arrow to the container.

Doesn't work in IE7 (or 6), but seriously, I say if you're using IE7 you deserve a less-pretty dropdown experience.

XML Schema minOccurs / maxOccurs default values

Short answer:

As written in xsd:

<xs:attribute name="minOccurs" type="xs:nonNegativeInteger" use="optional" default="1"/>
<xs:attribute name="maxOccurs" type="xs:allNNI" use="optional" default="1"/>

If you provide an attribute with number, then the number is boundary. Otherwise attribute should appear exactly once.

client denied by server configuration

in my case,

i'm using macOS Mojave (Apache/2.4.34). There was an issue in virtual host settings at /etc/apache2/extra/httpd-vhosts.conf file. after adding the required directory tag my problem was gone.

Require all granted

Hope the full virtual host setup structure will save you.

<VirtualHost *:80>
    DocumentRoot "/Users/vagabond/Sites/MainProjectFolderName/public/"
    ServerName project.loc

    <Directory /Users/vagabond/Sites/MainProjectFolderName/public/>
        Require all granted

    ErrorLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-error_log"
    CustomLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-access_log" common

all you've to do replace the MainProjectFolderName with your exact ProjectFolderName.

Change bootstrap navbar collapse breakpoint without using LESS

Hi i think you can do it using CSS like this you can change breakpoint bootstrap menu

    @media (max-width: 1200px) {
    .navbar-header {
        float: none;
    .navbar-left,.navbar-right {
        float: none !important;
    .navbar-toggle {
        display: block;

    .navbar-collapse.collapse {
        display: none!important;
    .navbar-nav {
        float: none!important; 
    .navbar-nav>li {
        float: none;
        display:block !important;
   .navbar-nav .open .dropdown-menu {
       position: static;
       float: none;
       width: auto;
       margin-top: 0;
       background-color: transparent;
       border: 0;
       -webkit-box-shadow: none;
       box-shadow: none;

Site does not exist error for a2ensite

So .. quickest way is rename site config names ending in ".conf"

mv /etc/apache2/sites-available/mysite /etc/apache2/sites-available/mysite.conf

a2ensite mysite.conf

other notes on previous comments:

  • IncludeOptional wasn't introduced until apache 2.36 - making change above followed by restart on 2.2 will leave your server down!

  • also, version 2.2 a2ensite can't be hacked as described

as well, since your sites-available file is actually a configuration file, it should be named that way anyway..

In general do not restart services (webservers are one type of service):

  • folks can't find them if they are not running! Think linux not MS Windows..

Servers can run for many years - live update, reload config, etc.

The cloud doesn't mean you have to restart to load a configuration file.

  • When changing configuration of a service use "reload" not "restart".

  • restart stops the service then starts service - if there is a any problem in your change to the config, the service will not restart.

  • reload will give an error but the service never shuts down giving you a chance to fix the config error which could only be bad syntax.

debian or ubunto [service-name for this thread is apache2]

service {service-name} {start} {stop} {reload} ..

other os's left as an excersize for the reader.

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub


str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
  print ("The word tiger was not found.")


string.match(s, pattern, optional index)

Returns the capture groups found.


str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
  print ("The word tiger was not found.")

Using Mockito to mock classes with generic parameters

Create a test utility method. Specially useful if you need it for more than once.

public void testMyTest() {
    // ...
    Foo<Bar> mockFooBar = mockFoo();
    when(mockFooBar.getValue).thenReturn(new Bar());

    Foo<Baz> mockFooBaz = mockFoo();
    when(mockFooBaz.getValue).thenReturn(new Baz());

    Foo<Qux> mockFooQux = mockFoo();
    when(mockFooQux.getValue).thenReturn(new Qux());
    // ...

@SuppressWarnings("unchecked") // still needed :( but just once :)
private <T> Foo<T> mockFoo() {
    return mock(Foo.class);

How can I change text color via keyboard shortcut in MS word 2010

Press Alt+H(h) and then you'll see the shortcuts on the toolbar, press FC to operate color menu and press A(Automatic) for black or browse through other colors using arrow keys.

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

I found this can also occur if the most of the data plotted is outside of the axis limits. In that case, adjust the axis scales accordingly.

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)

Here is the result. enter image description here

Input type for HTML form for integer

If you're using HTML5, you should use the input type number. If you are using xhtml or html 4, input type should be text.

Inject service in app.config

Set up your service as a custom AngularJS Provider

Despite what the Accepted answer says, you actually CAN do what you were intending to do, but you need to set it up as a configurable provider, so that it's available as a service during the configuration phase.. First, change your Service to a provider as shown below. The key difference here is that after setting the value of defer, you set the defer.promise property to the promise object returned by $http.get:

Provider Service: (provider: service recipe)

app.provider('dbService', function dbServiceProvider() {

  //the provider recipe for services require you specify a $get function
  this.$get= ['dbhost',function dbServiceFactory(dbhost){
     // return the factory as a provider
     // that is available during the configuration phase
     return new DbService(dbhost);  


function DbService(dbhost){
    var status;

    this.setUrl = function(url){
        dbhost = url;

    this.getData = function($http) {
        return $http.get(dbhost+'db.php/score/getData')
                 // handle any special stuff here, I would suggest the following:
                 status = 'ok';
        = data;
                 status = 'error';
                 status.message = message;
                 // now we return an object with data or information about error 
                 // for special handling inside your application configuration
                 return status;

Now, you have a configurable custom Provider, you just need to inject it. Key difference here being the missing "Provider on your injectable".


app.config(function ($routeProvider) { 
        .when('/', {
            templateUrl: "partials/editor.html",
            controller: "AppCtrl",
            resolve: {
                dbData: function(DbService, $http) {
                     *dbServiceProvider returns a dbService instance to your app whenever
                     * needed, and this instance is setup internally with a promise, 
                     * so you don't need to worry about $q and all that
                    return DbService('').getData();

use resolved data in your appCtrl

app.controller('appCtrl',function(dbData, DbService){
     $scope.dbData = dbData;

     // You can also create and use another instance of the dbService here...
     // to do whatever you programmed it to do, by adding functions inside the 
     // constructor DbService(), the following assumes you added 
     // a rmUser(userObj) function in the factory
     $scope.removeDbUser = function(user){


Possible Alternatives

The following alternative is a similar approach, but allows definition to occur within the .config, encapsulating the service to within the specific module in the context of your app. Choose the method that right for you. Also see below for notes on a 3rd alternative and helpful links to help you get the hang of all these things

app.config(function($routeProvider, $provide) {
    //set up your service inside the module's config.

        .when('/', {
            templateUrl: "partials/editor.html",
            controller: "AppCtrl",
            resolve: {

A few helpful Resources

  • John Lindquist has an excellent 5 minute explanation and demonstration of this at, and it's one of the free lessons! I basically modified his demonstration by making it $http specific in the context of this request
  • View the AngularJS Developer guide on Providers
  • There is also an excellent explanation about factory/service/provider at

The provider gives you a bit more configuration over the .service method, which makes it better as an application level provider, but you could also encapsulate this within the config object itself by injecting $provide into config like so:

Java 8 - Best way to transform a list: map or foreach?

If using 3rd Pary Libaries is ok cyclops-react defines Lazy extended collections with this functionality built in. For example we could simply write

ListX myListToParse;

ListX myFinalList = myListToParse.filter(elt -> elt != null) .map(elt -> doSomething(elt));

myFinalList is not evaluated until first access (and there after the materialized list is cached and reused).

[Disclosure I am the lead developer of cyclops-react]

How to get PID by process name?

If your OS is Unix base use this code:

import os
def check_process(name):
    output = []
    cmd = "ps -aef | grep -i '%s' | grep -v 'grep' | awk '{ print $2 }' > /tmp/out"
    os.system(cmd % name)
    with open('/tmp/out', 'r') as f:
        line = f.readline()
        while line:
            line = f.readline()
            if line.strip():

    return output

Then call it and pass it a process name to get all PIDs.

>>> check_process('firefox')
['499', '621', '623', '630', '11733']

Select data from date range between two dates

SELECT * from Product_sales where
(From_date BETWEEN '2013-01-03'AND '2013-01-09') OR 
(To_date BETWEEN '2013-01-03' AND '2013-01-09') OR 
(From_date <= '2013-01-03' AND To_date >= '2013-01-09')

You have to cover all possibilities. From_Date or To_Date could be between your date range or the record dates could cover the whole range.

If one of From_date or To_date is between the dates, or From_date is less than start date and To_date is greater than the end date; then this row should be returned.

iPad WebApp Full Screen in Safari

If you want to stay in a browser without launching a new window use this HTML code:

<a href="javascript:this.location = 'index.php?page=1'">

Could not autowire field in spring. why?

Well there's a problem with the creation of the ContactServiceImpl bean. First, make sure that the class is actually instantiated by debugging the no-args constructor when the Spring context is initiated and when an instance of ContactController is created.

If the ContactServiceImpl is actually instantiated by the Spring context, but it's simply not matched against your @Autowire annotation, try being more explicit in your annotation injection. Here's a guy dealing with a similar problem as yours and giving some possible solutions:

If you ask me, I think you'll be ok if you replace

private ContactService contactService;


private ContactService contactService;

Order of execution of tests in TestNG

If I understand your question correctly in that you want to run tests in a specified order, TestNG IMethodInterceptor can be used. Take a look at on how to leverage them.

If you want run some preinitialization, take a look at IHookable and associated thread

Maven plugins can not be found in IntelliJ

Recently I faced the same issue. All tips doesn't work in my cause.

But I fix it.

Go to Intellij idea setting, find Maven, and in it you need to open Repository tab and update maven and local repos. That's all.

Detecting when the 'back' button is pressed on a navbar

This works for me in iOS 9.3.x with Swift:

override func didMoveToParentViewController(parent: UIViewController?) {

    if parent == self.navigationController?.parentViewController {
        print("Back tapped")

Unlike other solutions here, this doesn't seem to trigger unexpectedly.

What does the percentage sign mean in Python

In python 2.6 the '%' operator performed a modulus. I don't think they changed it in 3.0.1

The modulo operator tells you the remainder of a division of two numbers.

Unable to find the requested .Net Framework Data Provider. It may not be installed. - when following mvc3 tutorial

I had a similer problem with SqlClient on WCF service. My solution was to put that lines in client app.config

     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />

Hopes it helps for someone..

Action Image MVC3 Razor

This turned out to be a very useful thread.

For those who are allergic to curly braces, here is the VB.NET version of Lucas' and Crake's answers:

Public Module ActionImage
    Function ActionImage(html As HtmlHelper, Action As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString

        Dim url = New UrlHelper(html.ViewContext.RequestContext)

        Dim imgHtml As String
        'Build the <img> tag
        Dim imgBuilder = New TagBuilder("img")
        With imgBuilder
            .MergeAttribute("src", url.Content(ImagePath))
            .MergeAttribute("alt", AltText)
            imgHtml = .ToString(TagRenderMode.Normal)
        End With

        Dim aHtml As String
        'Build the <a> tag
        Dim aBuilder = New TagBuilder("a")
        With aBuilder
            .MergeAttribute("href", url.Action(Action, RouteValues))
            .InnerHtml = imgHtml 'Include the <img> tag inside
            aHtml = aBuilder.ToString(TagRenderMode.Normal)
        End With

        Return MvcHtmlString.Create(aHtml)

    End Function

    Function ActionImage(html As HtmlHelper, Action As String, Controller As String, RouteValues As Object, ImagePath As String, AltText As String) As MvcHtmlString

        Dim url = New UrlHelper(html.ViewContext.RequestContext)

        Dim imgHtml As String
        'Build the <img> tag
        Dim imgBuilder = New TagBuilder("img")
        With imgBuilder
            .MergeAttribute("src", url.Content(ImagePath))
            .MergeAttribute("alt", AltText)
            imgHtml = .ToString(TagRenderMode.Normal)
        End With

        Dim aHtml As String
        'Build the <a> tag
        Dim aBuilder = New TagBuilder("a")
        With aBuilder
            .MergeAttribute("href", url.Action(Action, Controller, RouteValues))
            .InnerHtml = imgHtml 'Include the <img> tag inside
            aHtml = aBuilder.ToString(TagRenderMode.Normal)
        End With

        Return MvcHtmlString.Create(aHtml)

    End Function

End Module

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

Regex date validation for yyyy-mm-dd

you can test this expression:


validates a yyyy-mm-dd, yyyy mm dd, or yyyy/mm/dd date

makes sure day is within valid range for the month - does NOT validate Feb. 29 on a leap year, only that Feb. Can have 29 days

Matches (tested) : 0001-12-31 | 9999 09 30 | 2002/03/03

Date validation with ASP.NET validator

A CustomValidator would also work here:

<asp:CustomValidator runat="server"
    ErrorMessage="enter valid date" />


protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
    DateTime minDate = DateTime.Parse("1000/12/28");
    DateTime maxDate = DateTime.Parse("9999/12/28");
    DateTime dt;

    args.IsValid = (DateTime.TryParse(args.Value, out dt) 
                    && dt <= maxDate 
                    && dt >= minDate);

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

I had been facing this problems since 2 weeks, finally figured it out using a Sysinternal tool called Process monitor (ProcMon.exe). The problem has to do with the automatic updates settings. I applied the below solution and got it working

Solution: Tools -> Options -> Environment -> Extensions and Updates -> (uncheck) Automatically check for updates->OK

jQuery: How to get to a particular child of a parent?

You could use .each() with .children() and a selector within the parenthesis:

//Grab Each Instance of Box.

    //For Each Instance, grab a child called .something1. Fade It Out.

Errno 13 Permission denied Python

For future searchers, if none of the above worked, for me, python was trying to open a folder as a file.

How can I add numbers in a Bash script?

Use the $(( )) arithmetic expansion.

num=$(( $num + $metab ))

See Chapter 13. Arithmetic Expansion for more information.

Better way to sum a property value in an array

How to sum array of object using Javascript

const traveler = [
  {  description: 'Senior', Amount: 50},
  {  description: 'Senior', Amount: 50},
  {  description: 'Adult', Amount: 75},
  {  description: 'Child', Amount: 35},
  {  description: 'Infant', Amount: 25 }

const traveler = [_x000D_
    {  description: 'Senior', Amount: 50},_x000D_
    {  description: 'Senior', Amount: 50},_x000D_
    {  description: 'Adult', Amount: 75},_x000D_
    {  description: 'Child', Amount: 35},_x000D_
    {  description: 'Infant', Amount: 25 },_x000D_
function sum(arrayData, key){_x000D_
   return arrayData.reduce((a,b) => {_x000D_
  return {Amount : a.Amount + b.Amount}_x000D_
_x000D_ `

How to remove last n characters from every element in the R vector

Although this is mostly the same with the answer by @nfmcclure, I prefer using stringr package as it provdies a set of functions whose names are most consistent and descriptive than those in base R (in fact I always google for "how to get the number of characters in R" as I can't remember the name nchar()).

str_sub(iris$Species, end=-4)
str_sub(iris$Species, 1, str_length(iris$Species)-3)

This removes the last 3 characters from each value at Species column.

pow (x,y) in Java

x^y is not "x to the power of y". It's "x XOR y".

What is a simple command line program or script to backup SQL server databases?

You could use a VB Script I wrote exactly for this purpose:

Schedule a task in the "Task Scheduler" to execute the script as you like and it'll backup the entire DB to a BAK file and save it wherever you specify.

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.

Online tutorials


Character Classes

Escape Sequences


(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")





Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

Angular HttpClient "Http failure during parsing"

I had the same problem and the cause was That at time of returning a string in your backend (spring) you might be returning as return "spring used"; But this isn't parsed right according to spring. Instead use return "\" spring used \""; -Peace out

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

On a Mac, I had to do the following:

sudo chown -R $USER /data/db
sudo chown -R $USER /tmp/

because there was also a file inside /tmp which Mongo also needed access