SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

How do I assert equality on two classes without an equals method?

From your comments to other answers, I don't understand what you want.

Just for the sake of discussion, lets say that the the class did override the equals method.

So your UT will look something like:

SomeType expected = // bla
SomeType actual = // bli

Assert.assertEquals(expected, actual). 

And you are done. Moreover, you can not get the "full equality picture" if the assertion fails.

From what I understand, you are saying that even if the type did override equals, you would not be interested in it, since you want to get the "full equality picture". So there is no point in extending and overriding equals either.

So you have to options: either compare property by property, using reflection or hard-coded checks, I would suggest the latter. Or: compare human readable representations of these objects.

For example, you can create a helper class that serializes the type you wish tocompare to an XML document and than compare the resulting XML! in this case, you can visually see what exactly is equal and what is not.

This approach will give you the opportunity to look at the full picture but it is also relatively cumbersome (and a little error prone at first).

What is the difference between linear regression and logistic regression?

In short: Linear Regression gives continuous output. i.e. any value between a range of values. Logistic Regression gives discrete output. i.e. Yes/No, 0/1 kind of outputs.

How to delete all files from a specific folder?

Add the following namespace,

using System.IO;

and use the Directory class to reach on the specific folder:

string[] fileNames = Directory.GetFiles(@"your directory path");
foreach (string fileName in fileNames)
    File.Delete(fileName);

Is it possible to have empty RequestParam values use the defaultValue?

You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:

@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
    if(i == null) {
        i = 10;
    }
    // ...
}

I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:

http://example.com/test

How to validate an OAuth 2.0 access token for a resource server?

An update on @Scott T.'s answer: the interface between Resource Server and Authorization Server for token validation was standardized in IETF RFC 7662 in October 2015, see: https://tools.ietf.org/html/rfc7662. A sample validation call would look like:

POST /introspect HTTP/1.1
Host: server.example.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer 23410913-abewfq.123483

token=2YotnFZFEjr1zCsicMWpAA

and a sample response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "active": true,
  "client_id": "l238j323ds-23ij4",
  "username": "jdoe",
  "scope": "read write dolphin",
  "sub": "Z5O3upPC88QrAjx00dis",
  "aud": "https://protected.example.net/resource",
  "iss": "https://server.example.com/",
  "exp": 1419356238,
  "iat": 1419350238,
  "extension_field": "twenty-seven"
}

Of course adoption by vendors and products will have to happen over time.

Set active tab style with AngularJS

Came here for solution .. though above solutions are working fine but found them little bit complex unnecessary. For people who still looking for a easy and neat solution, it will do the task perfectly.

<section ng-init="tab=1">
                <ul class="nav nav-tabs">
                    <li ng-class="{active: tab == 1}"><a ng-click="tab=1" href="#showitem">View Inventory</a></li>
                    <li ng-class="{active: tab == 2}"><a ng-click="tab=2" href="#additem">Add new item</a></li>
                    <li ng-class="{active: tab == 3}"><a ng-click="tab=3" href="#solditem">Sold item</a></li>
                </ul>
            </section>

How to use ArgumentCaptor for stubbing?

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

How to change the scrollbar color using css

You can use the following attributes for webkit, which reach into the shadow DOM:

::-webkit-scrollbar              { /* 1 */ }
::-webkit-scrollbar-button       { /* 2 */ }
::-webkit-scrollbar-track        { /* 3 */ }
::-webkit-scrollbar-track-piece  { /* 4 */ }
::-webkit-scrollbar-thumb        { /* 5 */ }
::-webkit-scrollbar-corner       { /* 6 */ }
::-webkit-resizer                { /* 7 */ }

Here's a working fiddle with a red scrollbar, based on code from this page explaining the issues.

http://jsfiddle.net/hmartiro/Xck2A/1/

Using this and your solution, you can handle all browsers except Firefox, which at this point I think still requires a javascript solution.

how to create a list of lists

You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:

>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

This may not be an exact answer to your question (in terms of WebDriver), but I've found that the java.awt library is more stable than selenium.Keys. So, a page down action using the former will be:

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PAGE_DOWN);
robot.keyRelease(KeyEvent.VK_PAGE_DOWN);

Adding values to specific DataTable cells

If it were a completely new row that you wanted to only set one value, you would need to add the whole row and then set the individual value:

DataRow dr = dt.NewRow();
dr[3].Value = "Some Value";
dt.Rows.Add(dr);

Otherwise, you can find the existing row and set the cell value

DataRow dr = dt.Rows[theRowNumber];
dr[3] = "New Value";

not:first-child selector

As I used ul:not(:first-child) is a perfect solution.

div ul:not(:first-child) {
    background-color: #900;
}

Why is this a perfect because by using ul:not(:first-child), we can apply CSS on inner elements. Like li, img, span, a tags etc.

But when used others solutions:

div ul + ul {
  background-color: #900;
}

and

div li~li {
    color: red;
}

and

ul:not(:first-of-type) {}

and

div ul:nth-child(n+2) {
    background-color: #900;
}

These restrict only ul level CSS. Suppose we cannot apply CSS on li as `div ul + ul li'.

For inner level elements the first Solution works perfectly.

div ul:not(:first-child) li{
        background-color: #900;
    }

and so on ...

Difference between JSONObject and JSONArray

Best programmatically Understanding.

when syntax is {}then this is JsonObject

when syntax is [] then this is JsonArray

A JSONObject is a JSON-like object that can be represented as an element in the JSONArray. JSONArray can contain a (or many) JSONObject

Hope this will helpful to you !

CodeIgniter - File upload required validation

  1. set a rule to check the file name (if the form is multipart)

    $this->form_validation->set_rules('upload_file[name]', 'Upload file', 'required', 'No upload image :(');

  2. overwrite the $_POST array as follows:

    $_POST['upload_file'] = $_FILES['upload_file']

  3. and then do:

    $this->form_validation->run()

How to get the current taxonomy term ID (not the slug) in WordPress?

It's the term slug you want.Looks like you can get the id like this if that's what you need:

function get_term_link( $term, $taxonomy = '' ) {
    global $wp_rewrite;

    if ( !is_object($term) ) {
        if ( is_int( $term ) ) {
            $term = get_term( $term, $taxonomy );
        } else {
            $term = get_term_by( 'slug', $term, $taxonomy );
        }
    }

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

What is the Gradle artifact dependency graph command?

If you got a lot configurations the output might be pretty lengthy. To just show dependencies for the runtime configuration, run

gradle dependencies --configuration runtime

How to reverse MD5 to get the original string?

No, that's not really possible, as

  • there can be more than one string giving the same MD5
  • it was designed to be hard to "reverse"

The goal of the MD5 and its family of hashing functions is

  • to get short "extracts" from long string
  • to make it hard to guess where they come from
  • to make it hard to find collisions, that is other words having the same hash (which is a very similar exigence as the second one)

Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.

This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...

Links in <select> dropdown options

Add an onchange event handler and set the pages location to the value

<select id="foo">
    <option value="">Pick a site</option>
    <option value="http://www.google.com">x</option>
    <option value="http://www.yahoo.com">y</option>
</select>

<script>
    document.getElementById("foo").onchange = function() {
        if (this.selectedIndex!==0) {
            window.location.href = this.value;
        }        
    };
</script>

How to apply bold text style for an entire row using Apache POI?

This worked for me

    Object[][] bookData = { { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 },
            { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 } };

    String[] headers = new String[] { "HEader 1", "HEader 2", "HEader 3" };

    int noOfColumns = headers.length;
    int rowCount = 0;

    Row rowZero = sheet.createRow(rowCount++);
    CellStyle style = workbook.createCellStyle();
    Font font = workbook.createFont();
    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
    style.setFont(font);
    for (int col = 1; col <= noOfColumns; col++) {
        Cell cell = rowZero.createCell(col);
        cell.setCellValue(headers[col - 1]);
        cell.setCellStyle(style);
    }

Making heatmap from pandas DataFrame

Please note that the authors of seaborn only want seaborn.heatmap to work with categorical dataframes. It's not general.

If your index and columns are numeric and/or datetime values, this code will serve you well.

Matplotlib heat-mapping function pcolormesh requires bins instead of indices, so there is some fancy code to build bins from your dataframe indices (even if your index isn't evenly spaced!).

The rest is simply np.meshgrid and plt.pcolormesh.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def conv_index_to_bins(index):
    """Calculate bins to contain the index values.
    The start and end bin boundaries are linearly extrapolated from 
    the two first and last values. The middle bin boundaries are 
    midpoints.

    Example 1: [0, 1] -> [-0.5, 0.5, 1.5]
    Example 2: [0, 1, 4] -> [-0.5, 0.5, 2.5, 5.5]
    Example 3: [4, 1, 0] -> [5.5, 2.5, 0.5, -0.5]"""
    assert index.is_monotonic_increasing or index.is_monotonic_decreasing

    # the beginning and end values are guessed from first and last two
    start = index[0] - (index[1]-index[0])/2
    end = index[-1] + (index[-1]-index[-2])/2

    # the middle values are the midpoints
    middle = pd.DataFrame({'m1': index[:-1], 'p1': index[1:]})
    middle = middle['m1'] + (middle['p1']-middle['m1'])/2

    if isinstance(index, pd.DatetimeIndex):
        idx = pd.DatetimeIndex(middle).union([start,end])
    elif isinstance(index, (pd.Float64Index,pd.RangeIndex,pd.Int64Index)):
        idx = pd.Float64Index(middle).union([start,end])
    else:
        print('Warning: guessing what to do with index type %s' % 
              type(index))
        idx = pd.Float64Index(middle).union([start,end])

    return idx.sort_values(ascending=index.is_monotonic_increasing)

def calc_df_mesh(df):
    """Calculate the two-dimensional bins to hold the index and 
    column values."""
    return np.meshgrid(conv_index_to_bins(df.index),
                       conv_index_to_bins(df.columns))

def heatmap(df):
    """Plot a heatmap of the dataframe values using the index and 
    columns"""
    X,Y = calc_df_mesh(df)
    c = plt.pcolormesh(X, Y, df.values.T)
    plt.colorbar(c)

Call it using heatmap(df), and see it using plt.show().

enter image description here

Twitter bootstrap remote modal shows same content every time

Thanks merv. I started tinkering around boostrap.js but your answer is a quick and clean workaround. Here's what I ended up using in my code.

$('#modal-item').on('hidden', function() {
    $(this).removeData('modal');
});

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

Works for any number from 0 to 999999999.

This program gets a number from the user, divides it into three parts and stores them separately in an array. The three numbers are passed through a function that convert them into words. Then it adds "million" to the first part and "thousand" to the second part.

#include <iostream>
using namespace std;
int buffer = 0, partFunc[3] = {0, 0, 0}, part[3] = {0, 0, 0}, a, b, c, d;
long input, nFake = 0;
const char ones[][20] = {"",       "one",       "two",      "three",
                         "four",    "five",      "six",      "seven",
                         "eight",   "nine",      "ten",      "eleven",
                         "twelve",  "thirteen",  "fourteen", "fifteen",
                         "sixteen", "seventeen", "eighteen", "nineteen"};
const char tens[][20] = {"",     "ten",   "twenty",  "thirty", "forty",
                         "fifty", "sixty", "seventy", "eighty", "ninety"};
void convert(int funcVar);
int main() {
  cout << "Enter the number:";
  cin >> input;
  nFake = input;
  buffer = 0;
  while (nFake) {
    part[buffer] = nFake % 1000;
    nFake /= 1000;
    buffer++;
  }
  if (buffer == 0) {
    cout << "Zero.";
  } else if (buffer == 1) {
    convert(part[0]);
  } else if (buffer == 2) {
    convert(part[1]);
    cout << " thousand,";
    convert(part[0]);
  } else {
    convert(part[2]);
    cout << " million,";

    if (part[1]) {
      convert(part[1]);
      cout << " thousand,";
    } else {
      cout << "";
    }
    convert(part[0]);
  }
  system("pause");
  return (0);
}

void convert(int funcVar) {
  buffer = 0;
  if (funcVar >= 100) {
    a = funcVar / 100;
    b = funcVar % 100;
    if (b)
      cout << " " << ones[a] << " hundred and";
    else
      cout << " " << ones[a] << " hundred ";
    if (b < 20)
      cout << " " << ones[b];
    else {
      c = b / 10;
      cout << " " << tens[c];
      d = b % 10;
      cout << " " << ones[d];
    }
  } else {
    b = funcVar;
    if (b < 20)
      cout << ones[b];
    else {
      c = b / 10;
      cout << tens[c];
      d = b % 10;
      cout << " " << ones[d];
    }
  }
}

Adding onClick event dynamically using jQuery

Or you can use an arrow function to define it:

$(document).ready(() => {
  $('#bfCaptchaEntry').click(()=>{
    
  });
});

For better browser support:

$(document).ready(function() {
  $('#bfCaptchaEntry').click(function (){
    
  });
});

How to split page into 4 equal parts?

Similar to other posts, but with an important distinction to make this work inside a div. The simpler answers aren't very copy-paste-able because they directly modify div or draw over the entire page.

The key here is that the containing div dividedbox has relative positioning, allowing it to sit nicely in your document with the other elements, while the quarters within have absolute positioning, giving you vertical/horizontal control inside the containing div.

As a bonus, text is responsively centered in the quarters.

HTML:

<head>
  <meta charset="utf-8">
  <title>Box model</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <h1 id="title">Title Bar</h1>
  <div id="dividedbox">
    <div class="quarter" id="NW">
      <p>NW</p>
    </div>
    <div class="quarter" id="NE">
      <p>NE</p>
    </div>
    <div class="quarter" id="SE">
      <p>SE</p>
    </div>?
    <div class="quarter" id="SW">
      <p>SW</p>
    </div>
  </div>
</body>

</html>

CSS:

html, body { height:95%;} /* Important to make sure your divs have room to grow in the document */
#title { background: lightgreen}
#dividedbox { position: relative; width:100%; height:95%}   /* for div growth */
.quarter {position: absolute; width:50%; height:50%;  /* gives quarters their size */
  display: flex; justify-content: center; align-items: center;} /* centers text */
#NW { top:0;    left:0;     background:orange;     }
#NE { top:0;    left:50%;   background:lightblue;  }
#SW { top:50%;  left:0;     background:green;      }
#SE { top:50%;  left:50%;   background:red;        }

http://jsfiddle.net/og0j2d3v/

How do I count unique values inside a list

ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list
unique_words = set(words)

Get data from file input in JQuery

I created a form data object and appended the file:

var form = new FormData(); 
form.append("video", $("#fileInput")[0].files[0]);

and i got:

------WebKitFormBoundaryNczYRonipfsmaBOK
Content-Disposition: form-data; name="video"; filename="Wildlife.wmv"
Content-Type: video/x-ms-wmv

in the headers sent. I can confirm this works because my file was sent and stored in a folder on my server. If you don't know how to use the FormData object there is some documentation online, but not much. Form Data Object Explination by Mozilla

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

Use "whereis" command.

$ whereis tomcat8
tomcat8: /usr/sbin/tomcat8 /etc/tomcat8 /usr/libexec/tomcat8 /usr/share/tomcat8

Handling of non breaking space: <p>&nbsp;</p> vs. <p> </p>

How about a workaround? In my case I took the value of the textarea in a jQuery variable, and changed all "<p>&nbsp" to <p class="clear"> and clear class to have certain height and margin, as the following example:

jQuery

tinyMCE.triggerSave();
var val = $('textarea').val();
val = val.replace(/<p>&nbsp/g, '<p class="clear">');

the val is then saved to the database with the new val.

CSS

p.clear{height: 2px; margin-bottom: 3px;}

You can adjust the height & margin as you wish. And since 'p' is a display: block element. it should give you the expected output.

Hope that helps!

Send data from a textbox into Flask?

Unless you want to do something more complicated, feeding data from a HTML form into Flask is pretty easy.

  • Create a view that accepts a POST request (my_form_post).
  • Access the form elements in the dictionary request.form.

templates/my-form.html:

<form method="POST">
    <input name="text">
    <input type="submit">
</form>
from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template('my-form.html')

@app.route('/', methods=['POST'])
def my_form_post():
    text = request.form['text']
    processed_text = text.upper()
    return processed_text

This is the Flask documentation about accessing request data.

If you need more complicated forms that need validation then you can take a look at WTForms and how to integrate them with Flask.

Note: unless you have any other restrictions, you don't really need JavaScript at all to send your data (although you can use it).

Run script on mac prompt "Permission denied"

In my case, I had made a stupid typo in the shebang.

So in case someone else on with fat fingers stumbles across this question:

Whoops: #!/usr/local/bin ruby

I meant to write: #!/usr/bin/env ruby

The vague error ZSH gives sent me down the wrong path:

ZSH: zsh: permission denied: ./foo.rb

Bash: bash: ./foo.rb: /usr/local/bin: bad interpreter: Permission denied

Windows equivalent of linux cksum command

In the year 2019, Microsoft offers the following solution for Windows 10. This solution works for SHA256 checksum.

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-filehash?view=powershell-6

Press the Windows key. Type PowerShell. Select Windows Powershell. Press Enter key. Paste the command

Get-FileHash C:\Users\Donald\Downloads\File-to-be-checked-by-sha256.exe | Format-List

Replace File-to-be-checked-by-sha256.exe by the name of your file to be checked.

Replace the path to your path where the file is. Press Enter key. Powershell shows then the following

Algorithm : SHA256 Hash : 123456789ABCDEFGH1234567890... Path : C:\Users\Donald\Downloads\File-to-be-checked-by-sha256.exe

How can I return to a parent activity correctly?

Try this solution use NavUtils.navigateUpFromSameTask(this); in the child activity: https://stackoverflow.com/a/49980835/7308789

Setting multiple attributes for an element at once with JavaScript

If you wanted a framework-esq syntax (Note: IE 8+ support only), you could extend the Element prototype and add your own setAttributes function:

Element.prototype.setAttributes = function (attrs) {
    for (var idx in attrs) {
        if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object') {
            for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];}
        } else if (idx === 'html') {
            this.innerHTML = attrs[idx];
        } else {
            this.setAttribute(idx, attrs[idx]);
        }
    }
};

This lets you use syntax like this:

var d = document.createElement('div');
d.setAttributes({
    'id':'my_div',
    'class':'my_class',
    'styles':{
        'backgroundColor':'blue',
        'color':'red'
    },
    'html':'lol'
});

Try it: http://jsfiddle.net/ywrXX/1/

If you don't like extending a host object (some are opposed) or need to support IE7-, just use it as a function

Note that setAttribute will not work for style in IE, or event handlers (you shouldn't anyway). The code above handles style, but not events.

Documentation

Add vertical whitespace using Twitter Bootstrap?

Just use <br/>. I found myself here looking for the answer to this question and then felt sort of silly for not thinking about using a simple line break as suggested by user JayKilleen in a comment.

how to get the value of css style using jquery

I doubt css understands left by itself. You need to use it specifying position. You are using .css() correctly

position: relative/absolute/whatever;
left: 900px;

heres a fiddle of it working

http://jsfiddle.net/gFLZe/

and without the position here's what you get

http://jsfiddle.net/gkkm5/

Change your if statement to be like this - with quotes around -900px

var n = $("items").css("left");

if(n == '-900px'){
    $(".items span").fadeOut("slow");
}

http://jsfiddle.net/gFLZe/1/

How to style icon color, size, and shadow of Font Awesome Icons

I had the same problem when I tried to use the icons directly from BootstrapCDN (the easiest way). Then I downloaded the CSS file and copied it to my site's CSS folder the CSS file (Described under the 'easy way' in font awesome documentation), and everything started working as they should.

JavaScript: function returning an object

I would take those directions to mean:

  function makeGamePlayer(name,totalScore,gamesPlayed) {
        //should return an object with three keys:
        // name
        // totalScore
        // gamesPlayed

         var obj = {  //note you don't use = in an object definition
             "name": name,
             "totalScore": totalScore,
             "gamesPlayed": gamesPlayed
          }
         return obj;
    }

How to check if a variable is both null and /or undefined in JavaScript

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}

MS Access DB Engine (32-bit) with Office 64-bit

A similar approach to @Peter Coppins answer. This, I think, is a bit easier and doesn't require the use of the Orca utility:

  1. Check the "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" registry key and make sure the value "mso.dll" is NOT present. If it is present, then Office 64-bit seems to be installed and you should not need this workaround.

  2. Download the Microsoft Access Database Engine 2010 Redistributable.

  3. From the command line, run: AccessDatabaseEngine_x64.exe /passive

(Note: this installer silently crashed or failed for me, so I unzipped the components and ran: AceRedist.msi /passive and that installed fine. Maybe a Windows 10 thing.)

  1. Delete or rename the "mso.dll" value in the "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Common\FilesPaths" key.

Source: How to install 64-bit Microsoft Database Drivers alongside 32-bit Microsoft Office

Best way to check that element is not present using Selenium WebDriver with java

public boolean isDisplayed(WebElement element) {
        try {
            return element.isDisplayed();
        } catch (NoSuchElementException e) {
            return false;
        }
    }

If you wan t to check that element is displayed on the page your check should be:

if(isDisplayed(yourElement){
...
}
else{
...
}

CURLOPT_RETURNTRANSFER set to true doesnt work on hosting server

Just try this line:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

after:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

JavaScript Editor Plugin for Eclipse

In 2015 I would go with:

  • For small scripts: The js editor + jsHint plugin
  • For large code bases: TypeScript Eclipse plugin, or a similar transpiled language... I only know that TypeScript works well in Eclipse.

Of course you may want to keep JS for easy project setup and to avoid the transpilation process... there is no ultimate solution.

Or just wait for ECMA6, 7, ... :)

How to resolve "Input string was not in a correct format." error?

The problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check.

Use Int32.TryParse(value, out number) instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
    Image1.Width= imageWidth;
}

Powershell: Get FQDN Hostname

It can also be retrieved from the registry:

Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' |
   % { $_.'NV HostName', $_.'NV Domain' -join '.' }

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had this issue when having a custom display in my terminal when creating a new git project (I have my branch display before the pathname e.g. :/current/path). All I needed to do was do my initial commit to my master branch to get this message to go away.

How can I make a checkbox readonly? not disabled?

You may simply add onclick="return false" - this will stop browser executing default action (checkbox checked/not checked will not be changed)

Failure during conversion to COFF: file invalid or corrupt

In my case it was just caused because there was not enough space on the disk for cvtres.exe to write the files it had to.

The error was preceded by this line

CVTRES : fatal error CVT1106: cannot write to file

How can I detect whether an iframe is loaded?

You may try this (using jQuery)

_x000D_
_x000D_
$(function(){_x000D_
    $('#MainPopupIframe').load(function(){_x000D_
        $(this).show();_x000D_
        console.log('iframe loaded successfully')_x000D_
    });_x000D_
        _x000D_
    $('#click').on('click', function(){_x000D_
        $('#MainPopupIframe').attr('src', 'https://heera.it');    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Using plain javascript

_x000D_
_x000D_
window.onload=function(){_x000D_
    var ifr=document.getElementById('MainPopupIframe');_x000D_
    ifr.onload=function(){_x000D_
        this.style.display='block';_x000D_
        console.log('laod the iframe')_x000D_
    };_x000D_
    var btn=document.getElementById('click');    _x000D_
    btn.onclick=function(){_x000D_
        ifr.src='https://heera.it';    _x000D_
    };_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Also you can try this (dynamic iframe)

_x000D_
_x000D_
$(function(){_x000D_
    $('#click').on('click', function(){_x000D_
        var ifr=$('<iframe/>', {_x000D_
            id:'MainPopupIframe',_x000D_
            src:'https://heera.it',_x000D_
            style:'display:none;width:320px;height:400px',_x000D_
            load:function(){_x000D_
                $(this).show();_x000D_
                alert('iframe loaded !');_x000D_
            }_x000D_
        });_x000D_
        $('body').append(ifr);    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

onMeasure custom view explanation

If you don't need to change something onMeasure - there's absolutely no need for you to override it.

Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).

You can check the onMeasure method here :

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

public static int getDefaultSize(int size, int measureSpec) {
    int result = size;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    switch (specMode) {
    case MeasureSpec.UNSPECIFIED:
        result = size;
        break;
    case MeasureSpec.AT_MOST:
    case MeasureSpec.EXACTLY:
        result = specSize;
        break;
    }
    return result;
}

Overriding SDK code to be replaced with the exact same code makes no sense.

This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.

Android MediaPlayer Stop and Play

To stop the Media Player without the risk of an Illegal State Exception, you must do

  try {
        mp.reset();
        mp.prepare();
        mp.stop();
        mp.release();
        mp=null;
       }
  catch (Exception e)
         {
           e.printStackTrace();
         }

rather than just

try {
       mp.stop();
       mp.release();
       mp=null;
    } 
catch (Exception e) 
    {
      e.printStackTrace();
    }

HTML SELECT - Change selected option by VALUE using JavaScript

try out this....

JSFIDDEL DEMO

using javascript

?document.getElementById('sel').value = 'car';??????????

using jQuery

$('#sel').val('car');

How can I tell if a VARCHAR variable contains a substring?

    IF CHARINDEX('TextToSearch',@TextWhereISearch, 0) > 0 => TEXT EXISTS

    IF PATINDEX('TextToSearch', @TextWhereISearch) > 0 => TEXT EXISTS

    Additionally we can also use LIKE but I usually don't use LIKE.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

Simple solution to consume the \n character:

import java.util.Scanner;
class string
{
    public static void main(String a[]){
        int a;
        String s;
        Scanner scan = new Scanner(System.in);

        System.out.println("enter a no");
        a = scan.nextInt();
        System.out.println("no is ="+a);

        scan.nextLine();
        System.out.println("enter a string");
        s = scan.nextLine();
        System.out.println("string is="+s);
    }
}

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

Of course that works; when @item1 = N'', it IS NOT NULL.

You can define @item1 as NULL by default at the top of your stored procedure, and then not pass in a parameter.

Using unset vs. setting a variable to empty

Mostly you don't see a difference, unless you are using set -u:

/home/user1> var=""
/home/user1> echo $var

/home/user1> set -u
/home/user1> echo $var

/home/user1> unset var
/home/user1> echo $var
-bash: var: unbound variable

So really, it depends on how you are going to test the variable.

I will add that my preferred way of testing if it is set is:

[[ -n $var ]]  # True if the length of $var is non-zero

or

[[ -z $var ]]  # True if zero length

How to throw std::exceptions with variable messages?

There are different exceptions such as runtime_error, range_error, overflow_error, logic_error, etc.. You need to pass the string into its constructor, and you can concatenate whatever you want to your message. That's just a string operation.

std::string errorMessage = std::string("Error: on file ")+fileName;
throw std::runtime_error(errorMessage);

You can also use boost::format like this:

throw std::runtime_error(boost::format("Error processing file %1") % fileName);

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

How do I revert back to an OpenWrt router configuration?

Those who are facing this problem: Don't panic.

Short answer:

Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)

Long answer: Let's learn how to restart the router.

  1. Set your PC's IP address: 192.168.1.2 and subnetmask 255.255.255.0 and gateway 192.168.1.1
  2. Power off the router
  3. Disconnect the WAN cable
  4. Only connect your PC Ethernet cable to ETH0
  5. Power on the router
  6. Wait for the router to start the boot sequence (SYS LED starts blinking)
  7. When the SYS LED is blinking, hit the restart button (the SYS LED will be blinking at a faster rate means your router is in failsafe mode). (You have to hit the button before the router boots.)
  8. telnet 192.168.1.1
  9. Run these commands:

    mount_root ## this remounts your partitions from read-only to read/write mode
    
    firstboot  ## This will reset your router after reboot
    
    reboot -f ## And force reboot
    
  10. Log in the web interface using web browser.

link to see the official failsafe mode.

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

You could use prop as well. Check the following code below.

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").prop("readonly", false); 
     }
     else{ 
         $("#no_of_staff").prop("readonly", true); 
     }
   });
});

Difference between Method and Function?

well, in some programming languages they are called functions others call it methods, the fact is they are the same thing. It just represents an abstractized form of reffering to a mathematical function:

f -> f(N:N).

meaning its a function with values from natural numbers (just an example). So besides the name Its exactly the same thing, representing a block of code containing instructions in resolving your purpose.

How do I create a folder in a GitHub repository?

First you have to clone the repository to you local machine

git clone github_url local_directory

Then you can create local folders and files inside your local_directory, and add them to the repository using:

git add file_path

You can also add everything using:

git add .

Note that Git does not track empty folders. A workaround is to create a file inside the empty folder you want to track. I usually name that file empty, but it can be whatever name you choose.

Finally, you commit and push back to GitHub:

git commit
git push

For more information on Git, check out the Pro Git book.

TypeError: $ is not a function WordPress

Other than noConflict, this is helpful too:

(function( $ ) {
    // Variables and DOM Caching using $.
    var body = $('body');
    console.log(body);
})( jQuery );

How do I run Google Chrome as root?

STEP 1: cd /opt/google/chrome

STEP 2: edit google-chrome file. gedit google-chrome

STEP 3: find this line: exec -a "$0" "$HERE/chrome" "$@".

Mostly this line is in the end of google-chrome file.

Comment it out like this : #exec -a "$0" "$HERE/chrome" "$@"

STEP 4:add a new line at the same place.

exec -a "$0" "$HERE/chrome" "$@" --user-data-dir

STEP 5: save google-chrome file and quit. And then you can use chrome as root user. Enjoy it!

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

How to convert any date format to yyyy-MM-dd

string sourceDateText = "31-08-2012";
DateTime sourceDate = DateTime.Parse(sourceDateText, "dd-MM-yyyy")
string formatted = sourceDate.ToString("yyyy-MM-dd");

Can you force Visual Studio to always run as an Administrator in Windows 8?

VSCommands didn't work for me and caused a problem when I installed Visual Studio 2010 aside of Visual Studio 2012.

After some experimentations I found the trick:

Go to HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers and add an entry with the name "C:\Program Files (x86)\Common Files\Microsoft Shared\MSEnv\VSLauncher.exe" and the value "RUNASADMIN".

This should solve your issue. I've also blogged about that.

How to find the serial port number on Mac OS X?

Found the port esp32 was connected to by -

ls /dev/*

You would get a long list and you can find the port you need

How do I show my global Git configuration?

The shortest,

git config -l

shows all inherited values from: system, global and local

Capturing a form submit with jquery and .submit

Just a tip: Remember to put the code detection on document.ready, otherwise it might not work. That was my case.

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
Parallel.ForEach(list_lines, line =>
{
    //Your stuff
});

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

Can media queries resize based on a div element instead of the screen?

This is currently not possible with CSS alone as @BoltClock wrote in the accepted answer, but you can work around that by using JavaScript.

I created a container query (aka element query) prolyfill to solve this kind of issue. It works a bit different than other scripts, so you don’t have to edit the HTML code of your elements. All you have to do is include the script and use it in your CSS like so:

.element:container(width > 99px) {
    /* If its container is at least 100px wide */
}

https://github.com/ausi/cq-prolyfill

PHP display current server path

  • To get your current working directory: getcwd() (documentation)
  • To get the document root directory: $_SERVER['DOCUMENT_ROOT']
  • To get the filename of the current script: $_SERVER['SCRIPT_FILENAME']

vertical alignment of text element in SVG

After looking at the SVG Recommendation I've come to the understanding that the baseline properties are meant to position text relative to other text, especially when mixing different fonts and or languages. If you want to postion text so that it's top is at y then you need use dy = "y + the height of your text".

Android Imagebutton change Image OnClick

That is because imgButton is null. Try this instead:

findViewById(R.id.imgButton).setBackgroundResource(R.drawable.ic_action_search);

or much easier to read:

imgButton = (Button) findViewById(R.id.imgButton);
imgButton.setOnClickListener(imgButtonHandler);

then in onClick: imgButton.setBackgroundResource(R.drawable.ic_action_search);

HTML.HiddenFor value set

You shouldn't need to set the value in the attributes parameter. MVC should automatically bind it for you.

@Html.HiddenFor(model => model.title, new { id= "natureOfVisitField" })

CodeIgniter -> Get current URL relative to base url

If url helper is loaded, use

current_url();

will be better

Importing packages in Java

You should use

import Dan.Vik;

This makes the class visible and the its public methods available.

Creating an instance of class

  1. Allocates some dynamic memory from the free store, and creates an object in that memory using its default constructor. You never delete it, so the memory is leaked.
  2. Does exactly the same as 1; in the case of user-defined types, the parentheses are optional.
  3. Allocates some automatic memory, and creates an object in that memory using its default constructor. The memory is released automatically when the object goes out of scope.
  4. Similar to 3. Notionally, the named object foo4 is initialised by default-constructing, copying and destroying a temporary object; usually, this is elided giving the same result as 3.
  5. Allocates a dynamic object, then initialises a second by copying the first. Both objects are leaked; and there's no way to delete the first since you don't keep a pointer to it.
  6. Does exactly the same as 5.
  7. Does not compile. Foo foo5 is a declaration, not an expression; function (and constructor) arguments must be expressions.
  8. Creates a temporary object, and initialises a dynamic object by copying it. Only the dynamic object is leaked; the temporary is destroyed automatically at the end of the full expression. Note that you can create the temporary with just Foo() rather than the equivalent Foo::Foo() (or indeed Foo::Foo::Foo::Foo::Foo())

When do I use each?

  1. Don't, unless you like unnecessary decorations on your code.
  2. When you want to create an object that outlives the current scope. Remember to delete it when you've finished with it, and learn how to use smart pointers to control the lifetime more conveniently.
  3. When you want an object that only exists in the current scope.
  4. Don't, unless you think 3 looks boring and what to add some unnecessary decoration.
  5. Don't, because it leaks memory with no chance of recovery.
  6. Don't, because it leaks memory with no chance of recovery.
  7. Don't, because it won't compile
  8. When you want to create a dynamic Bar from a temporary Foo.

How to create Gmail filter searching for text only at start of subject line?

The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.

Remove shadow below actionbar

add app:elevation="0dp" in AppBarLayout for hiding shadow in appbar

Adding Google Translate to a web site

<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script type="text/javascript">
  function googleTranslateElementInit() {
      new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
  }
</script>

Easiest way to copy a table from one database to another?

Try mysqldbcopy (documentation)

Or you can create a "federated table" on your target host. Federated tables allow you to see a table from a different database server as if it was a local one. (documentation)

After creating the federated table, you can copy data with the usual insert into TARGET select * from SOURCE

How to insert data into SQL Server

I think you lack to pass Connection object to your command object. and it is much better if you will use command and parameters for that.

using (SqlConnection connection = new SqlConnection("ConnectionStringHere"))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;            // <== lacking
        command.CommandType = CommandType.Text;
        command.CommandText = "INSERT into tbl_staff (staffName, userID, idDepartment) VALUES (@staffName, @userID, @idDepart)";
        command.Parameters.AddWithValue("@staffName", name);
        command.Parameters.AddWithValue("@userID", userId);
        command.Parameters.AddWithValue("@idDepart", idDepart);

        try
        {
            connection.Open();
            int recordsAffected = command.ExecuteNonQuery();
        }
        catch(SqlException)
        {
            // error here
        }
        finally
        {
            connection.Close();
        }
    }
}

Put content in HttpResponseMessage object?

Inspired by Simon Mattes' answer, I needed to satisfy IHttpActionResult required return type of ResponseMessageResult. Also using nashawn's JsonContent, I ended up with...

        return new System.Web.Http.Results.ResponseMessageResult(
            new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
            {
                Content = new JsonContent(JsonConvert.SerializeObject(contact, Formatting.Indented))
            });

See nashawn's answer for JsonContent.

How can I run a directive after the dom has finished rendering?

If you can't use $timeout due to external resources and cant use a directive due to a specific issue with timing, use broadcast.

Add $scope.$broadcast("variable_name_here"); after the desired external resource or long running controller/directive has completed.

Then add the below after your external resource has loaded.

$scope.$on("variable_name_here", function(){ 
   // DOM manipulation here
   jQuery('selector').height(); 
}

For example in the promise of a deferred HTTP request.

MyHttpService.then(function(data){
   $scope.MyHttpReturnedImage = data.image;
   $scope.$broadcast("imageLoaded");
});

$scope.$on("imageLoaded", function(){ 
   jQuery('img').height(80).width(80); 
}

How to Read from a Text File, Character by Character in C++

Assuming that temp is a char and textFile is a std::fstream derivative...

The syntax you're looking for is

textFile.get( temp );

what's the correct way to send a file from REST web service to client?

If you want to return a File to be downloaded, specially if you want to integrate with some javascript libs of file upload/download, then the code bellow should do the job:

@GET
@Path("/{key}")
public Response download(@PathParam("key") String key,
                         @Context HttpServletResponse response) throws IOException {
    try {
        //Get your File or Object from wherever you want...
            //you can use the key parameter to indentify your file
            //otherwise it can be removed
        //let's say your file is called "object"
        response.setContentLength((int) object.getContentLength());
        response.setHeader("Content-Disposition", "attachment; filename="
                + object.getName());
        ServletOutputStream outStream = response.getOutputStream();
        byte[] bbuf = new byte[(int) object.getContentLength() + 1024];
        DataInputStream in = new DataInputStream(
                object.getDataInputStream());
        int length = 0;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            outStream.write(bbuf, 0, length);
        }
        in.close();
        outStream.flush();
    } catch (S3ServiceException e) {
        e.printStackTrace();
    } catch (ServiceException e) {
        e.printStackTrace();
    }
    return Response.ok().build();
}

How to select records without duplicate on just one field in SQL?

Ignore duplicate rows in SQL. I think this may help you.

    SELECT res2.*
    FROM
    (SELECT res1.*,ROW_NUMBER() OVER(PARTITION BY res1.title ORDER BY res1.id)as num
     FROM 
    (select * from [dbo].[tbl_countries])as res1
    )as res2
    WHERE res2.num=1

How do I resolve a path relative to an ASP.NET MVC 4 application root?

Just use the following

Server.MapPath("~/Data/data.html")

Determine command line working directory when running node bin script

Current Working Directory

To get the current working directory, you can use:

process.cwd()

However, be aware that some scripts, notably gulp, will change the current working directory with process.chdir().

Node Module Path

You can get the path of the current module with:

  • __filename
  • __dirname

Original Directory (where the command was initiated)

If you are running a script from the command line, and you want the original directory from which the script was run, regardless of what directory the script is currently operating in, you can use:

process.env.INIT_CWD

Original directory, when working with NPM scripts

It's sometimes desirable to run an NPM script in the current directory, rather than the root of the project.

This variable is available inside npm package scripts as:

$INIT_CWD.

You must be running a recent version of NPM. If this variable is not available, make sure NPM is up to date.

This will allow you access the current path in your package.json, e.g.:

scripts: {
  "customScript": "gulp customScript --path $INIT_CWD"
}

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Show div #id on click with jQuery

The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready() then it should work perfectly well:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").show("slow");
        });

    });

An alternative is to place the <script></script> at the foot of the page, so it's encountered after the DOM has been loaded and ready.

To make the div hide again, once the #music element is clicked, simply use toggle():

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").toggle();
        });
    });

JS Fiddle demo.

And for fading:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").fadeToggle();
        });
    });

JS Fiddle demo.

Map with Key as String and Value as List in Groovy

you don't need to declare Map groovy internally recognizes it

def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']

// print the values..
    println "First Name: ${personDetails.firstName}"
    println "Last Name: ${personDetails.lastName}"

http://grails.asia/groovy-map-tutorial

Setting different color for each series in scatter plot on matplotlib

You can always use the plot() function like so:

import matplotlib.pyplot as plt

import numpy as np

x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]
plt.figure()
for y in ys:
    plt.plot(x, y, 'o')
plt.show()

plot as scatter but changes colors

How store a range from excel into a Range variable?

What is currentWorksheet? It works if you use the built-in ActiveSheet.

dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

Is true == 1 and false == 0 in JavaScript?

It's true that true and false don't represent any numerical values in Javascript.

In some languages (e.g. C, VB), the boolean values are defined as actual numerical values, so they are just different names for 1 and 0 (or -1 and 0).

In some other languages (e.g. Pascal, C#), there is a distinct boolean type that is not numerical. It's possible to convert between boolean values and numerical values, but it doesn't happen automatically.

Javascript falls in the category that has a distinct boolean type, but on the other hand Javascript is quite keen to convert values between different data types.

For example, eventhough a number is not a boolean, you can use a numeric value where a boolean value is expected. Using if (1) {...} works just as well as if (true) {...}.

When comparing values, like in your example, there is a difference between the == operator and the === operator. The == equality operator happily converts between types to find a match, so 1 == true evaluates to true because true is converted to 1. The === type equality operator doesn't do type conversions, so 1 === true evaluates to false because the values are of different types.