Programs & Examples On #Minibuffer

The minibuffer is a part of Emacs used to read in complex commands or arguments.

How to replace a character with a newline in Emacs?

Don't forget that you can always cut and paste into the minibuffer.

So you can just copy a newline character (or any string) from your buffer, then yank it when prompted for the replacement text.

Setting dropdownlist selecteditem programmatically

Well if I understood correctly your question. The Solution for setting the value for a given dropdownlist will be:

dropdownlist1.Text="Your Value";

This will work only if the value is existing in the data-source of the dropdownlist.

How To Set Up GUI On Amazon EC2 Ubuntu server

So I follow first answer, but my vnc viewer gives me grey screen when I connect to it. And I found this Ask Ubuntu link to solve that.

The only difference with previous answer is you need to install these extra packages:

apt-get install gnome-panel gnome-settings-daemon metacity nautilus gnome-terminal

And use this ~/.vnc/xstartup file:



[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &

gnome-panel &
gnome-settings-daemon &
metacity &
nautilus &
gnome-terminal &

Everything else is the same.

Tested on EC2 Ubuntu 14.04 LTS.

Laravel is there a way to add values to a request array

You can add parameters to the request from a middleware by doing:

public function handle($request, Closure $next)
    $request->route()->setParameter('foo', 'bar');
    return $next($request);

Passing bash variable to jq

I resolved this issue by escaping the inner double quotes

projectID=$(cat file.json | jq -r ".resource[] | select(.username==\"$EMAILID\") | .id")

A warning - comparison between signed and unsigned integer expressions

The important difference between signed and unsigned ints is the interpretation of the last bit. The last bit in signed types represent the sign of the number, meaning: e.g:

0001 is 1 signed and unsigned 1001 is -1 signed and 9 unsigned

(I avoided the whole complement issue for clarity of explanation! This is not exactly how ints are represented in memory!)

You can imagine that it makes a difference to know if you compare with -1 or with +9. In many cases, programmers are just too lazy to declare counting ints as unsigned (bloating the for loop head f.i.) It is usually not an issue because with ints you have to count to 2^31 until your sign bit bites you. That's why it is only a warning. Because we are too lazy to write 'unsigned' instead of 'int'.

Access Database opens as read only

The main reason for this is when the database is open somewhere else.

This could be as already said by many others:

  • not being closed properly somewhere
  • already open somewhere

When recently I had the same problem although different versions, I started to search for the reason.

In my case I had an excel file that queried data from the database.

In case the excel file is opened before the database, access would give this error.


Check all files/connections related to the database. An open ODBC connection or query used in excel (my case) open the mdb file and will make it readonly.

Export to CSV using MVC, C# and jQuery

I Think you have forgot to use




please check

What is the purpose of a plus symbol before a variable?

Operator + is a unary operator which converts value to number. Below I prepared a table with corresponding results of using this operator for different values.

| Value                       | + (Value) |
| 1                           | 1         |
| '-1'                        | -1        |
| '3.14'                      | 3.14      |
| '3'                         | 3         |
| '0xAA'                      | 170       |
| true                        | 1         |
| false                       | 0         |
| null                        | 0         |
| 'Infinity'                  | Infinity  |
| 'infinity'                  | NaN       |
| '10a'                       | NaN       |
| undefined                   | Nan       |
| ['Apple']                   | Nan       |
| function(val){ return val } | NaN       |

Operator + returns value for objects which have implemented method valueOf.

let something = {
    valueOf: function () {
        return 25;


#1071 - Specified key was too long; max key length is 1000 bytes

This error means that length of index index is more then 1000 bytes. MySQL and storage engines may have this restriction. I have got similar error on MySQL 5.5 - 'Specified key was too long; max key length is 3072 bytes' when ran this script:

  column1 varchar(500) NOT NULL,
  column2 varchar(500) NOT NULL,
  column3 varchar(500) NOT NULL,
  column4 varchar(500) NOT NULL,
  column5 varchar(500) NOT NULL,
  column6 varchar(500) NOT NULL,
  KEY `index` (column1, column2, column3, column4, column5, column6)

UTF8 is multi-bytes, and key length is calculated in this way - 500 * 3 * 6 = 9000 bytes.

But note, next query works!

  column1 varchar(500) NOT NULL,
  column2 varchar(500) NOT NULL,
  column3 varchar(500) NOT NULL,
  column4 varchar(500) NOT NULL,
  column5 varchar(500) NOT NULL,
  column6 varchar(500) NOT NULL,
  KEY `index` (column1, column2, column3, column4, column5, column6)

...because I used CHARSET=latin1, in this case key length is 500 * 6 = 3000 bytes.

selecting rows with id from another table

SELECT terms.*
FROM terms JOIN terms_relation ON id=term_id
WHERE taxonomy='categ'

Combine two (or more) PDF's

Following method merges two pdfs( f1 and f2) using iTextSharp. The second pdf is appended after a specific index of f1.

 string f1 = "D:\\a.pdf";
 string f2 = "D:\\Iso.pdf";
 string outfile = "D:\\c.pdf";
 appendPagesFromPdf(f1, f2, outfile, 3);

  public static void appendPagesFromPdf(String f1,string f2, String destinationFile, int startingindex)
            PdfReader p1 = new PdfReader(f1);
            PdfReader p2 = new PdfReader(f2);
            int l1 = p1.NumberOfPages, l2 = p2.NumberOfPages;

            //Create our destination file
            using (FileStream fs = new FileStream(destinationFile, FileMode.Create, FileAccess.Write, FileShare.None))
                Document doc = new Document();

                PdfWriter w = PdfWriter.GetInstance(doc, fs);
                for (int page = 1; page <= startingindex; page++)
                    w.DirectContent.AddTemplate(w.GetImportedPage(p1, page), 0, 0);
                    //Used to pull individual pages from our source

                }//  copied pages from first pdf till startingIndex
                for (int i = 1; i <= l2;i++)
                    w.DirectContent.AddTemplate(w.GetImportedPage(p2, i), 0, 0);
                }// merges second pdf after startingIndex
                for (int i = startingindex+1; i <= l1;i++)
                    w.DirectContent.AddTemplate(w.GetImportedPage(p1, i), 0, 0);
                }// continuing from where we left in pdf1 



How do you know if Tomcat Server is installed on your PC

The port 8005 is used as service port. You can send a shutdown command (a configurable password) to that port. It will not "speak" HTTP, so you cannot use your browser to connect.

The default port for delivering web-content is 8080.

But there may be other applications listen to that port. So your tomcat may not start, if the port is not available.

You asked "How do you know, if tomcat server is installed on your PC?". The answer to that question is: You can't

You can't determine, if it is installed, because it may be only extracted from a ZIP archive or packaged within another application (Like JBoss AS (I think)).

How can I insert vertical blank space into an html document?

Read up some on css, it's fun:

  .bottom-three {
     margin-bottom: 3cm;

<p class="bottom-three">
   This is the first question?
<p class="bottom-three">
   This is the second question?

Rendering HTML in a WebView with custom CSS

It's as simple as is:

WebView webview = (WebView) findViewById(;

And your some.html needs to contain something like:

<link rel="stylesheet" type="text/css" href="style.css" />

How to remove element from ArrayList by checking its value?

Use a iterator to loop through list and then delete the required object.

    Iterator itr = a.iterator();

Best way to "push" into C# array

Check out this documentation page:

The Add function is the first one under Methods.

Could not load file or assembly 'Newtonsoft.Json, Version=, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I was facing this issue when I added Nuget package Newtonsoft.Json into my two .netstandard library projects and it grabbed almost my full day to solve this issue.

Exception -: Could not load file or assembly 'Newtonsoft.Json, Version=, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The system cannot find the file specified.

Solution -: I had to remove package from Nuget and went to the following location and followed the next steps -

Step 1. Go to location "C:\Users[UserName].nuget\packages\newtonsoft.json\12.0.2\lib" and here you will get all Nuget versions you installed previously.

enter image description here

Step 2. Since i wanted to use it in my .netstandard 2.0 library project, so i copied "netstandard2.0" folder from this location and paste somewhere my preferred location (**where i generally keep 3rd party dlls).

Step 3. Now i added DLL reference from here to my both project and this way problem solved.


List all employee's names and their managers by manager name using an inner join

select a.empno,a.ename,a.job,a.mgr,B.empno,B.ename as MGR_name, B.job as MGR_JOB from 
    emp a, emp B where a.mgr=B.empno ;

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

For array type Please try this one.

 List<MyStok> myDeserializedObjList = (List<MyStok>)Newtonsoft.Json.JsonConvert.DeserializeObject(sc), typeof(List<MyStok>));

Please See here for details to deserialise Json

How to configure PHP to send e-mail?

You need to have a smtp service setup in your local machine in order to send emails. There are many available freely just search on google.

If you own a server or VPS upload the script and it will work fine.

DateTime's representation in milliseconds?

This other solution for covert datetime to unixtimestampmillis C#.

private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

public static long GetCurrentUnixTimestampMillis()
    DateTime localDateTime, univDateTime;
    localDateTime = DateTime.Now;          
    univDateTime = localDateTime.ToUniversalTime();
    return (long)(univDateTime - UnixEpoch).TotalMilliseconds;

java: Class.isInstance vs Class.isAssignableFrom

Both answers are in the ballpark but neither is a complete answer.

MyClass.class.isInstance(obj) is for checking an instance. It returns true when the parameter obj is non-null and can be cast to MyClass without raising a ClassCastException. In other words, obj is an instance of MyClass or its subclasses.

MyClass.class.isAssignableFrom(Other.class) will return true if MyClass is the same as, or a superclass or superinterface of, Other. Other can be a class or an interface. It answers true if Other can be converted to a MyClass.

A little code to demonstrate:

public class NewMain
    public static void main(String[] args)
        NewMain nm = new NewMain();

    class A { }

    class B extends A { }

    public void doit()
        A myA = new A();
        B myB = new B();
        A[] aArr = new A[0];
        B[] bArr = new B[0];

        System.out.println("b instanceof a: " + (myB instanceof A)); // true
        System.out.println("b isInstance a: " + A.class.isInstance(myB)); //true
        System.out.println("a isInstance b: " + B.class.isInstance(myA)); //false
        System.out.println("b isAssignableFrom a: " + A.class.isAssignableFrom(B.class)); //true
        System.out.println("a isAssignableFrom b: " + B.class.isAssignableFrom(A.class)); //false
        System.out.println("bArr isInstance A: " + A.class.isInstance(bArr)); //false
        System.out.println("bArr isInstance aArr: " + aArr.getClass().isInstance(bArr)); //true
        System.out.println("bArr isAssignableFrom aArr: " + aArr.getClass().isAssignableFrom(bArr.getClass())); //true

round value to 2 decimals javascript

If you want it visually formatted to two decimals as a string (for output) use toFixed():

var priceString = someValue.toFixed(2);

The answer by @David has two problems:

  1. It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g. 134.1999999999 instead of "134.20".

  2. If your value is an integer or rounds to one tenth, you will not see the additional decimal value:

    var n = 1.099;
    (Math.round( n * 100 )/100 ).toString() //-> "1.1"
    n.toFixed(2)                            //-> "1.10"
    var n = 3;
    (Math.round( n * 100 )/100 ).toString() //-> "3"
    n.toFixed(2)                            //-> "3.00"

And, as you can see above, using toFixed() is also far easier to type. ;)

Pass a simple string from controller to a view MVC3

@Steve Hobbs' answer is probably the best, but some of your other solutions could have worked. For example, @Html.Label(ViewBag.CurrentPath); will probably work with an explicit cast, like @Html.Label((string)ViewBag.CurrentPath);. Also, your reference to currentPath in @Html.Label(ViewData["CurrentPath"].ToString()); is capitalized, wherein your other code it is not, which is probably why you were getting null reference exceptions.

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I had the same problem:

curl -v -H "Content-Type: application/json" -X PUT -d '{"name":"json","surname":"gson","married":true,"age":32,"salary":123,"hasCar":true,"childs":["serkan","volkan","aybars"]}' XXXXXX/ponyo/UserModel/json

* About to connect() to localhost port 8081 (#0)
*   Trying ::1...
* Connection refused
*   Trying
* connected
* Connected to localhost ( port 8081 (#0)
> PUT /ponyo/UserModel/json HTTP/1.1
> User-Agent: curl/7.28.1
> Host: localhost:8081
> Accept: */*
> Content-Type: application/json
> Content-Length: 121
* upload completely sent off: 121 out of 121 bytes
< HTTP/1.1 415 Unsupported Media Type
< Content-Type: text/html; charset=iso-8859-1
< Date: Wed, 09 Apr 2014 13:55:43 GMT
< Content-Length: 0
* Connection #0 to host localhost left intact
* Closing connection #0

I resolved it by adding the dependency to pom.xml as follows. Please try it.


java.lang.UnsupportedClassVersionError: Bad version number in .class file?

i solved this problem by changing jre required for server (in my case is tomcat). From Server tab in eclipse, double click on the server (in order to open page for server configuration), click on Runtime environment, then change JRE required

filename and line number of Python script

In Python 3 you can use a variation on:

def Deb(msg = None):
  print(f"Debug {sys._getframe().f_back.f_lineno}: {msg if msg is not None else ''}")

In code, you can then use:

Deb("Some useful information")

To produce:

123: Some useful information

Where the 123 and 124 are the lines that the calls are made from.

How to correctly display .csv files within Excel 2013?

For Excel 2013:

  1. Open Blank Workbook.
  2. Go to DATA tab.
  3. Click button From Text in the General External Data section.
  4. Select your CSV file.
  5. Follow the Text Import Wizard. (in step 2, select the delimiter of your text)

Which JDK version (Language Level) is required for Android Studio?

Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago.

I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...

Python: URLError: <urlopen error [Errno 10060]

The error code 10060 means it cannot connect to the remote peer. It might be because of the network problem or mostly your setting issues, such as proxy setting.

You could try to connect the same host with other tools(such as ncat) and/or with another PC within your same local network to find out where the problem is occuring.

For proxy issue, there are some material here:

Using an HTTP PROXY - Python

Why can't I get Python's urlopen() method to work on Windows?

Hope it helps!

Responsively change div size keeping aspect ratio

That's my solution

<div class="main" style="width: 100%;">
    <div class="container">
        <div class="sizing"></div>
        <div class="content"></div>

.main {
    width: 100%;
.container {
    width: 30%;
    float: right;
    position: relative;
.sizing {
    width: 100%;
    padding-bottom: 50%;
    visibility: hidden;
.content {
    width: 100%;
    height: 100%;
    background-color: red;
    position: absolute;
    margin-top: -50%;

TypeError: only integer scalar arrays can be converted to a scalar index with 1D numpy indices array

I get this error whenever I use np.concatenate the wrong way:

>>> a = np.eye(2)
>>> np.concatenate(a, a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in concatenate
TypeError: only integer scalar arrays can be converted to a scalar index

The correct way is to input the two arrays as a tuple:

>>> np.concatenate((a, a))
array([[1., 0.],
       [0., 1.],
       [1., 0.],
       [0., 1.]])

Python error when trying to access list by index - "List indices must be integers, not str"

Were you expecting player to be a dict rather than a list?

>>> player=[1,2,3]
>>> player["score"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
>>> player={'score':1, 'age': 2, "foo":3}
>>> player['score']

How to list containers in Docker

To show only running containers use the given command:

docker ps

To show all containers use the given command:

docker ps -a

To show the latest created container (includes all states) use the given command:

docker ps -l

To show n last created containers (includes all states) use the given command:

docker ps -n=-1

To display total file sizes use the given command:

docker ps -s

The content presented above is from

In the new version of Docker, commands are updated, and some management commands are added:

docker container ls

It is used to list all the running containers.

docker container ls -a

And then, if you want to clean them all,

docker rm $(docker ps -aq)

It is used to list all the containers created irrespective of its state.

And to stop all the Docker containers (force)

docker rm -f $(docker ps -a -q)  

Here the container is the management command.

Adding dictionaries together, Python

>>> dic0 = {'dic0':0}
>>> dic1 = {'dic1':1}
>>> ndic = dict(dic0.items() + dic1.items())
>>> ndic
{'dic0': 0, 'dic1': 1}

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

For me, this js reproduces the same problem that happens with Paola

My solution:

$(document.body).tooltip({selector: '[title]'})
.on('click mouseenter mouseleave','[title]', function(ev) {
    $(this).tooltip('mouseenter' === ev.type? 'show': 'hide');

jQuery click event on radio button doesn't get fired

put ur js code under the form html or use $(document).ready(function(){}) and try this.

$('#inline_content input[type="radio"]').click(function(){
                if($(this).val() == "walk_in"){

Underscore prefix for property and method names in JavaScript

import/export is now doing the job with ES6. I still tend to prefix not exported functions with _ if most of my functions are exported.

If you export only a class (like in angular projects), it's not needed at all.

export class MyOpenClass{

         return close();

    _privateStuff() { /* _ only as a convention */} 


function close(){ /*... this is really private... */ }

Oracle TNS names not showing when adding new connection to SQL Developer

SQL Developer will look in the following location in this order for a tnsnames.ora file

  1. $HOME/.tnsnames.ora
  2. $TNS_ADMIN/tnsnames.ora
  3. TNS_ADMIN lookup key in the registry
  4. /etc/tnsnames.ora ( non-windows )
  5. $ORACLE_HOME/network/admin/tnsnames.ora

To see which one SQL Developer is using, issue the command show tns in the worksheet

If your tnsnames.ora file is not getting recognized, use the following procedure:

  1. Define an environmental variable called TNS_ADMIN to point to the folder that contains your tnsnames.ora file.

    In Windows, this is done by navigating to Control Panel > System > Advanced system settings > Environment Variables...

    In Linux, define the TNS_ADMIN variable in the .profile file in your home directory.

  2. Confirm the os is recognizing this environmental variable

    From the Windows command line: echo %TNS_ADMIN%

    From linux: echo $TNS_ADMIN

  3. Restart SQL Developer

  4. Now in SQL Developer right click on Connections and select New Connection.... Select TNS as connection type in the drop down box. Your entries from tnsnames.ora should now display here.

What is the purpose of Android's <merge> tag in XML layouts?

blazeroni already made it pretty clear, I just want to add few points.

  • <merge> is used for optimizing layouts.It is used for reducing unnecessary nesting.
  • when a layout containing <merge> tag is added into another layout,the <merge> node is removed and its child view is added directly to the new parent.

Selenium Webdriver: Entering text into text field

Use this code.


When adding a Javascript library, Chrome complains about a missing source map, why?

When it s annoying with warnings like: DevTools failed to load SourceMap: Could not load content for http://********/bootstrap/4.5.0/css/ HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

Follow this path and remove that tricky /*# */ in bootstrap.min.css

jQuery - find table row containing table cell containing specific text

    var search = 'foo';
    $("table tr td").filter(function() {
        return $(this).text() == search;

Will turn the text red for rows which have a cell whose text is 'foo'.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

This is a problem for users who live in a country that is banned by Google (like Iran). for this reason we need to remove these restrictions by a proxy. follow me :

file->settings->Appearance&Behavior->System Setting-> Http Proxy-> Manual proxy configuration ->HTTP -> Host name : ->Port : 8118 .

and click Ok Button. then go to file-> Invalidate Caches/Restart . . . Use and enjoy the correct execution without error ;)

Equivalent of shell 'cd' command to change the working directory?

Further into direction pointed out by Brian and based on sh (1.0.8+)

from sh import cd, ls

print ls()

How link to any local file with markdown syntax?

None of the answers worked for me. But inspired in BarryPye's answer I found out it works when using relative paths!

# Contents from the '/media/user/' markdown file:

Read more [here](./ # It works!
Read more [here](file:///media/user/ # Doesn't work
Read more [here](/media/user/ # Doesn't work

MySQL and PHP - insert NULL rather than empty string

Check the variables before building the query, if they are empty, change them to the string NULL

Java: Best way to iterate through a Collection (here ArrayList)

The first option is better performance wise (As ArrayList implement RandomAccess interface). As per the java doc, a List implementation should implement RandomAccess interface if, for typical instances of the class, this loop:

 for (int i=0, n=list.size(); i < n; i++)

runs faster than this loop:

 for (Iterator i=list.iterator(); i.hasNext(); );

I hope it helps. First option would be slow for sequential access lists.

How can I selectively merge or pick changes from another branch in Git?

This is my workflow for merging selective files.

# Make a new branch (this will be temporary)
git checkout -b newbranch

# Grab the changes
git merge --no-commit  featurebranch

# Unstage those changes
git reset HEAD
(You can now see the files from the merge are unstaged)

# Now you can chose which files are to be merged.
git add -p

# Remember to "git add" any new files you wish to keep
git commit

Easiest way to compare arrays in C#

You can use Enumerable.Intersect:

int[] array1 = new int[] { 1, 2, 3, 4,5 },
      array2 = new int[] {7,8};

if (array1.Intersect(array2).Any())
    Console.WriteLine("not matched");

File changed listener in Java

You can listen file changes using a FileReader. Plz see the example below

// File content change listener 
private String fname;
private Object lck = new Object();
public void run()
        BufferedReader br = new BufferedReader( new FileReader( fname ) );
        String s;
        StringBuilder buf = new StringBuilder();
        while( true )
            s = br.readLine();
            if( s == null )
                synchronized( lck )
                    lck.wait( 500 );
               System.out.println( "s = " + s );

    catch( Exception e )

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

remove space between paragraph and unordered list

Every browser has some default styles that apply to a number of HTML elements, likes p and ul. The space you mention is likely created because of the default margin and padding of your browser. You can reset these though:

p { margin: 0; padding: 0; }
ul { margin: 0; padding: 0; }

You could also reset all default margins and paddings:

* { margin: 0; padding: 0; }

I suggest you take a look at normalize.css:

jQuery SVG, why can't I addClass?

After loading jquery.svg.js you must load this file:


Working example:

Create a list with initial capacity in Python

I ran S.Lott's code and produced the same 10% performance increase by preallocating. I tried Ned Batchelder's idea using a generator and was able to see the performance of the generator better than that of the doAllocate. For my project the 10% improvement matters, so thanks to everyone as this helps a bunch.

def doAppend(size=10000):
    result = []
    for i in range(size):
        message = "some unique object %d" % ( i, )
    return result

def doAllocate(size=10000):
    result = size*[None]
    for i in range(size):
        message = "some unique object %d" % ( i, )
        result[i] = message
    return result

def doGen(size=10000):
    return list("some unique object %d" % ( i, ) for i in xrange(size))

size = 1000
def testAppend():
    for i in xrange(size):

def testAlloc():
    for i in xrange(size):

def testGen():
    for i in xrange(size):



testAppend took 14440.000ms
testAlloc took 13580.000ms
testGen took 13430.000ms

Accessing private member variables from prototype-defined functions

You can use a prototype assignment within the constructor definition.

The variable will be visible to the prototype added method but all the instances of the functions will access the same SHARED variable.

function A()
  var sharedVar = 0;
  this.local = "";

  A.prototype.increment = function(lval)
    if (lval) this.local = lval;    
    alert((++sharedVar) + " while this.p is still " + this.local);

var a = new A();
var b = new A();    
a.increment("I belong to a");
b.increment("I belong to b");

I hope this can be usefull.

How to check if a file exists in Documents folder?

Swift 3:

let documentsURL = try! FileManager().url(for: .documentDirectory,
                                          in: .userDomainMask,
                                          appropriateFor: nil,
                                          create: true)

... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:

let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)


NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

Javascript replace with reference to matched group?

You can use replace instead of gsub.

"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")

Remove multiple objects with rm()

Make the list a character vector (not a vector of names)

rm(list = c('temp1','temp2'))


rm(temp1, temp2)

Passing data to a jQuery UI Dialog

You could do it like this:

  • mark the <a> with a class, say "cancel"
  • set up the dialog by acting on all elements with class="cancel":

    $('a.cancel').click(function() { 
      var a = this; 
        buttons: {
          "Yes": function() {
             window.location = a.href; 
      return false;

(plus your other options)

The key points here are:

  • make it as unobtrusive as possible
  • if all you need is the URL, you already have it in the href.

However, I recommend that you make this a POST instead of a GET, since a cancel action has side effects and thus doesn't comply with GET semantics...

Jquery click event not working after append method


As of jQuery version 1.7+, the on() method is the new replacement for the bind(), live() and delegate() methods.


$(document).on("click", "a.new_participant_form" , function() {

Or for more information CHECK HERE

Calling a Sub in VBA

Try -

Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)

As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

Mark error in form using Bootstrap

Bootstrap V3:

Official Doc Link 1
Official Doc Link 2

<div class="form-group has-success">
  <label class="control-label" for="inputSuccess">Input with success</label>
  <input type="text" class="form-control" id="inputSuccess" />
  <span class="help-block">Woohoo!</span>
<div class="form-group has-warning">
  <label class="control-label" for="inputWarning">Input with warning</label>
  <input type="text" class="form-control" id="inputWarning">
  <span class="help-block">Something may have gone wrong</span>
<div class="form-group has-error">
  <label class="control-label" for="inputError">Input with error</label>
  <input type="text" class="form-control" id="inputError">
  <span class="help-block">Please correct the error</span>

MySQLDump one INSERT statement for each data row

In newer versions change was made to the flags: from the documentation:

--extended-insert, -e

Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.


This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.

Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.


Turn off extended-insert

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

I really appreciate @raykrow's answer when one has this problem only in a test file! That is where I encountered it.

As it is often helpful to have another way to do something as a backup, I wanted to mention this technique that also works (instead of importing RouterTestingModule):

import { MockComponent } from 'ng2-mock-component';
. . .
  declarations: [
      selector: 'a',
      inputs: [ 'routerLink', 'routerLinkActiveOptions' ]
    . . .

(Typically, one would use routerLink on an <a> element but adjust the selector accordingly for other components.)

The second reason I wanted to mention this alternate solution is that, though it served me well in a number of spec files, I ran into a problem with it in one case:

Error: Template parse errors:
    More than one component matched on this element.
    Make sure that only one component's selector can match a given element.
    Conflicting components: ButtonComponent,Mock

I could not quite figure out how this mock and my ButtonComponent were using the same selector, so searching for an alternate approach led me here to @raykrow's solution.

Read and write a String from text file

For my txt file works this way:

let myFileURL = NSBundle.mainBundle().URLForResource("listacomuni", withExtension: "txt")!
let myText = try! String(contentsOfURL: myFileURL, encoding: NSISOLatin1StringEncoding)

How to get filename without extension from file path in Ruby

You can get directory path to current script with:

File.dirname __FILE__

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

A little improvement from Schnapple's version

int nLastColumn = dgv.Columns.Count - 1;
for (int i = 0; i < dgv.Columns.Count; i++)
    if (nLastColumn == i)
        dgv.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        dgv.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;

for (int i = 0; i < dgv.Columns.Count; i++)
    int colw = dgv.Columns[i].Width;
    dgv.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
    dgv.Columns[i].Width = colw;

raw_input function in Python

raw_input is a form of input that takes the argument in the form of a string whereas the input function takes the value depending upon your input. Say, a=input(5) returns a as an integer with value 5 whereas a=raw_input(5) returns a as a string of "5"

On a CSS hover event, can I change another div's styling?

The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS

         $("#b").css("background-color", "red");

Android global variable

There are a few different ways you can achieve what you are asking for.

1.) Extend the application class and instantiate your controller and model objects there.

public class FavoriteColorsApplication extends Application {

    private static FavoriteColorsApplication application;
    private FavoriteColorsService service;

    public FavoriteColorsApplication getInstance() {
        return application;

    public void onCreate() {
        application = this;

    private void initialize() {
        service = new FavoriteColorsService();

    public FavoriteColorsService getService() {
        return service;


Then you can call the your singleton from your custom Application object at any time:

public class FavoriteColorsActivity extends Activity {

private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();

protected void onCreate(Bundle savedInstanceState) {

    service = ((FavoriteColorsApplication) getApplication()).getService();
    favoriteColors = service.findAllColors();

    ListView lv = (ListView) findViewById(;
    adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,

2.) You can have your controller just create a singleton instance of itself:

public class Controller {
    private static final String TAG = "Controller";
    private static sController sController;
    private Dao mDao;

    private Controller() {
        mDao = new Dao();    

    public static Controller create() {
        if (sController == null) {
            sController = new Controller();
        return sController;

Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.

3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.

I hope I gave enough detail in regards to how you can do what you are hoping for.

Please run `npm cache clean`

This error can be due to many many things.

The key here seems the hint about error reading. I see you are working on a flash drive or something similar? Try to run the install on a local folder owned by your current user.

You could also try with sudo, that might solve a permission problem if that's the case.

Another reason why it cannot read could be because it has not downloaded correctly, or saved correctly. A little problem in your network could have caused that, and the cache clean would remove the files and force a refetch but that does not solve your problem. That means it would be more on the save part, maybe it didn't save because of permissions, maybe it didn't not save correctly because it was lacking disk space...

How to insert a picture into Excel at a specified cell position with VBA

Firstly, of all I recommend that the pictures are in the same folder as the workbook. You need to enter some codes in the Worksheet_Change procedure of the worksheet. For example, we can enter the following codes to add the image that with the same name as the value of cell in column A to the cell in column D:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim pic As Picture
If Intersect(Target, [A:A]) Is Nothing Then Exit Sub
On Error GoTo son

For Each pic In ActiveSheet.Pictures
    If Not Application.Intersect(pic.TopLeftCell, Range(Target.Offset(0, 3).Address)) Is Nothing Then
    End If
Next pic

ActiveSheet.Pictures.Insert(ThisWorkbook.Path & "\" & Target.Value & ".jpg").Select
Selection.Top = Target.Offset(0, 2).Top
Selection.Left = Target.Offset(0, 3).Left
Selection.ShapeRange.LockAspectRatio = msoFalse
Selection.ShapeRange.Height = Target.Offset(0, 2).Height
Selection.ShapeRange.Width = Target.Offset(0, 3).Width

End Sub

With the codes above, the picture is sized according to the cell it is added to.

Details and sample file here : Vba Insert image to cell

enter image description here

Can the Unix list command 'ls' output numerical chmod permissions?

it almost can ..

 ls -l | awk '{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/) \
             *2^(8-i));if(k)printf("%0o ",k);print}'

CodeIgniter - return only one row?

You've just answered your own question :) You can do something like this:

$query = $this->db->get();
$ret = $query->row();
return $ret->campaign_id;

You can read more about it here:

How to determine if Javascript array contains an object with an attribute that equals a given value?

const a = [{one:2},{two:2},{two:4}]
const b = a.filter(val => "two" in val).length;
if (b) {

What's the best way to trim std::string?

Ok this maight not be the fastest but it's... simple.

str = "   aaa    ";
int len = str.length();
// rtrim
while(str[len-1] == ' ') { str.erase(--len,1); }
// ltrim
while(str[0] == ' ') { str.erase(0,1); }

Fragment onResume() & onPause() is not called on backstack

Here's my more robust version of Gor's answer (using fragments.size()is unreliable due to size not being decremented after fragment is popped)

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        public void onBackStackChanged() {
            if (getFragmentManager() != null) {

                Fragment topFrag = NavigationHelper.getCurrentTopFragment(getFragmentManager());

                if (topFrag != null) {
                    if (topFrag instanceof YourFragment) {
                        //This fragment is being shown. 
                    } else {
                        //Navigating away from this fragment. 

And the 'getCurrentTopFragment' method:

public static Fragment getCurrentTopFragment(FragmentManager fm) {
    int stackCount = fm.getBackStackEntryCount();

    if (stackCount > 0) {
        FragmentManager.BackStackEntry backEntry = fm.getBackStackEntryAt(stackCount-1);
        return  fm.findFragmentByTag(backEntry.getName());
    } else {
        List<Fragment> fragments = fm.getFragments();
        if (fragments != null && fragments.size()>0) {
            for (Fragment f: fragments) {
                if (f != null && !f.isHidden()) {
                    return f;
    return null;

Highcharts - redraw() vs. new Highcharts.chart

var newData = [1,2,3,4,5,6,7];
var chart = $('#chartjs').highcharts();
chart.series[0].setData(newData, true);

Variable newData contains value that want to update in chart. Variable chart is an object of a chart. setData is a method provided by highchart to update data.

Method setData contains two parameters, in first parameter we need to pass new value as array and second param is Boolean value. If true then chart updates itself and if false then we have to use redraw() method to update chart (i.e chart.redraw();)

static const vs #define

Pros and cons between #defines, consts and (what you have forgot) enums, depending on usage:

  1. enums:

    • only possible for integer values
    • properly scoped / identifier clash issues handled nicely, particularly in C++11 enum classes where the enumerations for enum class X are disambiguated by the scope X::
    • strongly typed, but to a big-enough signed-or-unsigned int size over which you have no control in C++03 (though you can specify a bit field into which they should be packed if the enum is a member of struct/class/union), while C++11 defaults to int but can be explicitly set by the programmer
    • can't take the address - there isn't one as the enumeration values are effectively substituted inline at the points of usage
    • stronger usage restraints (e.g. incrementing - template <typename T> void f(T t) { cout << ++t; } won't compile, though you can wrap an enum into a class with implicit constructor, casting operator and user-defined operators)
    • each constant's type taken from the enclosing enum, so template <typename T> void f(T) get a distinct instantiation when passed the same numeric value from different enums, all of which are distinct from any actual f(int) instantiation. Each function's object code could be identical (ignoring address offsets), but I wouldn't expect a compiler/linker to eliminate the unnecessary copies, though you could check your compiler/linker if you care.
    • even with typeof/decltype, can't expect numeric_limits to provide useful insight into the set of meaningful values and combinations (indeed, "legal" combinations aren't even notated in the source code, consider enum { A = 1, B = 2 } - is A|B "legal" from a program logic perspective?)
    • the enum's typename may appear in various places in RTTI, compiler messages etc. - possibly useful, possibly obfuscation
    • you can't use an enumeration without the translation unit actually seeing the value, which means enums in library APIs need the values exposed in the header, and make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)

  1. consts:

    • properly scoped / identifier clash issues handled nicely
    • strong, single, user-specified type
      • you might try to "type" a #define ala #define S std::string("abc"), but the constant avoids repeated construction of distinct temporaries at each point of use
    • One Definition Rule complications
    • can take address, create const references to them etc.
    • most similar to a non-const value, which minimises work and impact if switching between the two
    • value can be placed inside the implementation file, allowing a localised recompile and just client links to pick up the change

  1. #defines:

    • "global" scope / more prone to conflicting usages, which can produce hard-to-resolve compilation issues and unexpected run-time results rather than sane error messages; mitigating this requires:
      • long, obscure and/or centrally coordinated identifiers, and access to them can't benefit from implicitly matching used/current/Koenig-looked-up namespace, namespace aliases etc.
      • while the trumping best-practice allows template parameter identifiers to be single-character uppercase letters (possibly followed by a number), other use of identifiers without lowercase letters is conventionally reserved for and expected of preprocessor defines (outside the OS and C/C++ library headers). This is important for enterprise scale preprocessor usage to remain manageable. 3rd party libraries can be expected to comply. Observing this implies migration of existing consts or enums to/from defines involves a change in capitalisation, and hence requires edits to client source code rather than a "simple" recompile. (Personally, I capitalise the first letter of enumerations but not consts, so I'd be hit migrating between those two too - maybe time to rethink that.)
    • more compile-time operations possible: string literal concatenation, stringification (taking size thereof), concatenation into identifiers
      • downside is that given #define X "x" and some client usage ala "pre" X "post", if you want or need to make X a runtime-changeable variable rather than a constant you force edits to client code (rather than just recompilation), whereas that transition is easier from a const char* or const std::string given they already force the user to incorporate concatenation operations (e.g. "pre" + X + "post" for string)
    • can't use sizeof directly on a defined numeric literal
    • untyped (GCC doesn't warn if compared to unsigned)
    • some compiler/linker/debugger chains may not present the identifier, so you'll be reduced to looking at "magic numbers" (strings, whatever...)
    • can't take the address
    • the substituted value need not be legal (or discrete) in the context where the #define is created, as it's evaluated at each point of use, so you can reference not-yet-declared objects, depend on "implementation" that needn't be pre-included, create "constants" such as { 1, 2 } that can be used to initialise arrays, or #define MICROSECONDS *1E-6 etc. (definitely not recommending this!)
    • some special things like __FILE__ and __LINE__ can be incorporated into the macro substitution
    • you can test for existence and value in #if statements for conditionally including code (more powerful than a post-preprocessing "if" as the code need not be compilable if not selected by the preprocessor), use #undef-ine, redefine etc.
    • substituted text has to be exposed:
      • in the translation unit it's used by, which means macros in libraries for client use must be in the header, so make and other timestamp-based recompilation tools will trigger client recompilation when they're changed (bad!)
      • or on the command line, where even more care is needed to make sure client code is recompiled (e.g. the Makefile or script supplying the definition should be listed as a dependency)

My personal opinion:

As a general rule, I use consts and consider them the most professional option for general usage (though the others have a simplicity appealing to this old lazy programmer).

Getting today's date in YYYY-MM-DD in Python?

I prefer this, because this is simple, but maybe somehow inefficient and buggy. You must check the exit code of shell command if you want a strongly error-proof program.

os.system('date +%Y-%m-%d')

Adding days to a date in Python

The previous answers are correct but it's generally a better practice to do:

import datetime

Then you'll have, using datetime.timedelta:

date_1 = datetime.datetime.strptime(start_date, "%m/%d/%y")

end_date = date_1 + datetime.timedelta(days=10)

C# get string from textbox

to get value of textbox

   string username = TextBox1.Text;
   string password = TextBox2.Text;

to set value of textbox

  TextBox1.Text = "my_username";
   TextBox2.Text = "12345";

OpenCV get pixel channel value from Mat image

Assuming the type is CV_8UC3 you would do this:

for(int i = 0; i < foo.rows; i++)
    for(int j = 0; j < foo.cols; j++)
        Vec3b bgrPixel =<Vec3b>(i, j);

        // do something with BGR values...

Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.

For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:

Here is how you might go about this:

uint8_t* pixelPtr = (uint8_t*);
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
    for(int j = 0; j < foo.cols; j++)
        bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
        bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
        bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R

        // do something with BGR values...

Or alternatively:

int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
    uint8_t* rowPtr = foo.row(i);
    for(int j = 0; j < foo.cols; j++)
        bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
        bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
        bgrPixel.val[2] = rowPtr[j*cn + 2]; // R

        // do something with BGR values...

Android overlay a view ontop of everything?

I have just made a solution for it. I made a library for this to do that in a reusable way that's why you don't need to recode in your XML. Here is documentation on how to use it in Java and Kotlin. First, initialize it from an activity from where you want to show the overlay-


Then you can hide and show it from anywhere in your app -

  /* For hiding the watermark*/

  /* For showing the watermark*/

Gif preview -


ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

 ngAfterViewInit() {
   setTimeout(() => {
   }, 0);

That is a good solution to resolve this problem.

Angularjs prevent form submission when input validation fails

Change the submit button to:

<button type="submit" ng-disabled="loginform.$invalid">Login</button>

How exactly do you configure httpOnlyCookies in ASP.NET?

Interestingly putting <httpCookies httpOnlyCookies="false"/> doesn't seem to disable httpOnlyCookies in ASP.NET 2.0. Check this article about SessionID and Login Problems With ASP .NET 2.0.

Looks like Microsoft took the decision to not allow you to disable it from the web.config. Check this post on

How to convert all tables from MyISAM into InnoDB?

This is a simple php script.

    @error_reporting(E_ALL | E_STRICT);
    @ini_set('display_errors', '1');

    $con = mysql_connect('server', 'user', 'pass');
    $dbName = 'moodle2014';

    $rs = mysql_query($sql, $con);

    $count = 0;
    $ok = 0;
    while($row = mysql_fetch_array($rs)){
            $count ++;
            $tbl = $row[0];
            $sql = "ALTER TABLE ".$dbName.".".$tbl." ENGINE=INNODB;";
            $resultado = mysql_query($sql);
            if ($resultado){
                    $ok ++;
                    echo $sql."<hr/>";
    if ($count == $ok){
            echo '<div style="color: green"><b>ALL OK</b></div>';
            echo '<div style="color: red"><b>ERRORS</b>Total tables: '.$count.', updated tables:'.$ok.'</div>';

Open Url in default web browser

In React 16.8+, using functional components, you would do

import React from 'react';
import { Button, Linking } from 'react-native';

const ExternalLinkBtn = (props) => {
  return <Button
            onPress={() => {
                .catch(err => {
                    console.error("Failed opening page because: ", err)
                    alert('Failed to open page')

export default function exampleUse() {
  return (
      <ExternalLinkBtn title="Example Link" url="" />

Escaping quotes and double quotes

I found myself in a similar predicament today while trying to run a command through a Node.js module:

I was using the PowerShell and trying to run:

command -e 'func($a)'

But with the extra symbols, PowerShell was mangling the arguments. To fix, I back-tick escaped double-quote marks:

command -e `"func($a)`"

variable or field declared void

Did you put void while calling your function?

For example:

void something(int x){

int main() {

    **void** something();

    return 0;


If so, you should delete the last void.

CSS to prevent child element from inheriting parent styles

Can't you style the forms themselves? Then, style the divs accordingly.

    /* styles */

You can always overrule inherited styles by making it important:

    /* styles */ !important

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.

Slide right to left?

Check the example here.


JavaScript isset() equivalent

function isset(variable) {
    try {
        return typeof eval(variable) !== 'undefined';
    } catch (err) {
        return false;

Differences in string compare methods in C#

  • s1.CompareTo(s2): Do NOT use if primary purpose is to determine whether two strings are equivalent
  • s1 == s2: Cannot ignore case
  • s1.Equals(s2, StringComparison): Throws NullReferenceException if s1 is null
  • String.Equals(s2, StringComparison): By process of eliminiation, this static method is the WINNER (assuming a typical use case to determine whether two strings are equivalent)!

UIBarButtonItem in navigation bar programmatically?

It's much easier with Swift 4 or Swift 4.2

inside your ViewDidLoad method, define your button and add it to the navigation bar.

override func viewDidLoad() {

    let logoutBarButtonItem = UIBarButtonItem(title: "Logout", style: .done, target: self, action: #selector(logoutUser))
    self.navigationItem.rightBarButtonItem  = logoutBarButtonItem


then you need to define the function that you mentioned inside action parameter as below

@objc func logoutUser(){

You need to add the @objc prefix as it's still making use of the legacy stuff (Objective C).

Position of a string within a string using Linux shell script?

With bash

a="The cat sat on the mat"
strindex() { 
  [[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
strindex "$a" "$b"   # prints 4
strindex "$a" foo    # prints -1

Better way to set distance between flexbox items

You can try CSS3's :not selector


#box {_x000D_
  display: flex;_x000D_
  width: 100px;_x000D_
  border: 1px red solid;_x000D_
.item {_x000D_
  background: gray;_x000D_
  width: 10px;_x000D_
  height: 100px;_x000D_
  flex: 1 1 auto;_x000D_
.item:not(:last-child) {_x000D_
  margin-right: 5px;_x000D_
<div id='box'>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_
  <div class='item'></div>_x000D_

Telling gcc directly to link a library statically

It is possible of course, use -l: instead of -l. For example -l:libXYZ.a to link with libXYZ.a. Notice the lib written out, as opposed to -lXYZ which would auto expand to libXYZ.

Where IN clause in LINQ

The "IN" clause is built into linq via the .Contains() method.

For example, to get all People whose .States's are "NY" or "FL":

using (DataContext dc = new DataContext("connectionstring"))
    List<string> states = new List<string>(){"NY", "FL"};
    List<Person> list = (from p in dc.GetTable<Person>() where states.Contains(p.State) select p).ToList();

Is there a way to @Autowire a bean that requires constructor arguments?

Most answers are fairly old, so it might have not been possible back then, but there actually is a solution that satisfies all the possible use-cases.

So right know the answers are:

  • Not providing a real Spring component (the factory design)
  • or does not fit every situation (using @Value you have to have the value in a configuration file somewhere)

The solution to solve those issues is to create the object manually using the ApplicationContext:

public class MyConstructorClass
    String var;

    public MyConstructorClass() {}
    public MyConstructorClass(String constrArg) {
        this.var = var;

public class MyBeanService implements ApplicationContextAware
    private static ApplicationContext applicationContext;

    MyConstructorClass myConstructorClass;

    public MyBeanService()
        // Creating the object manually
        MyConstructorClass myObject = new MyConstructorClass("hello world");
        // Initializing the object as a Spring component
        AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
        factory.initializeBean(myObject, myObject.getClass().getSimpleName());

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;

This is a cool solution because:

  • It gives you access to all the Spring functionalities on your object (@Autowired obviously, but also @Async for example),
  • You can use any source for your constructor arguments (configuration file, computed value, hard-coded value, ...),
  • It only requires you to add a few lines of code without having to change anything.
  • It can also be used to dynamically create a unknown number of instances of a Spring-managed class (I'm using it to create multiple asynchronous executors on the fly for example)

The only thing to keep in mind is that you have to have a constructor that takes no arguments (and that can be empty) in the class you want to instantiate (or an @Autowired constructor if you need it).

Where is the itoa function in Linux?

If you just want to print them:

void binary(unsigned int n)
    for(int shift=sizeof(int)*8-1;shift>=0;shift--)
       if (n >> shift & 1)


Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

How to make a variable accessible outside a function?

$.getJSON is an asynchronous request, meaning the code will continue to run even though the request is not yet done. You should trigger the second request when the first one is done, one of the choices you seen already in ComFreek's answer.

Alternatively you could use jQuery's $.when/.then(), similar to this:

var input = "netuetamundis";  var sID;  $(document).ready(function () {     $.when($.getJSON("" + input + "?api_key=API_KEY_HERE", function () {         obj = name;         sID =;         console.log(sID);     })).then(function () {         $.getJSON("" + sID + "/summary?api_key=API_KEY_HERE", function (stats) {             console.log(stats);         });     }); }); 

This would be more open for future modification and separates out the responsibility for the first call to know about the second call.

The first call can simply complete and do it's own thing not having to be aware of any other logic you may want to add, leaving the coupling of the logic separated.

How do I loop through children objects in javascript?

In ECS6, one may use Array.from():

const listItems = document.querySelector('ul').children;
const listArray = Array.from(listItems);
listArray.forEach((item) => {console.log(item)});

How to set a background image in Xcode using swift?

Swift 5.3 in XCode 12.2 Playgrounds

Place the cursor wherever in the code the #insertLiteral would have been in earlier versions. Select from the top-menu Editor->Insert Image Literal... and navigate to the file. Click Open.

The file is added to a playground Resource folder and will then appear when the playground is run in whichever view it was positioned when selected.

If a file is already in the playground Bundle, e.g. in /Resources, it can be dragged directly to the required position in the code (where it will be represented by an icon).

cf. Apple help docs give details of this and how to place other colour and file literals.

How to set up file permissions for Laravel?

Just to state the obvious for anyone viewing this discussion.... if you give any of your folders 777 permissions, you are allowing ANYONE to read, write and execute any file in that directory.... what this means is you have given ANYONE (any hacker or malicious person in the entire world) permission to upload ANY file, virus or any other file, and THEN execute that file...


There are basically two ways to setup your ownership and permissions. Either you give yourself ownership or you make the webserver the owner of all files.

Webserver as owner (the way most people do it, and the Laravel doc's way):

assuming www-data (it could be something else) is your webserver user.

sudo chown -R www-data:www-data /path/to/your/laravel/root/directory

if you do that, the webserver owns all the files, and is also the group, and you will have some problems uploading files or working with files via FTP, because your FTP client will be logged in as you, not your webserver, so add your user to the webserver user group:

sudo usermod -a -G www-data ubuntu

Of course, this assumes your webserver is running as www-data (the Homestead default), and your user is ubuntu (it's vagrant if you are using Homestead).

Then you set all your directories to 755 and your files to 644... SET file permissions

sudo find /path/to/your/laravel/root/directory -type f -exec chmod 644 {} \;    

SET directory permissions

sudo find /path/to/your/laravel/root/directory -type d -exec chmod 755 {} \;

Your user as owner

I prefer to own all the directories and files (it makes working with everything much easier), so, go to your laravel root directory:

cd /var/www/html/laravel >> assuming this is your current root directory
sudo chown -R $USER:www-data .

Then I give both myself and the webserver permissions:

sudo find . -type f -exec chmod 664 {} \;   
sudo find . -type d -exec chmod 775 {} \;

Then give the webserver the rights to read and write to storage and cache

Whichever way you set it up, then you need to give read and write permissions to the webserver for storage, cache and any other directories the webserver needs to upload or write too (depending on your situation), so run the commands from bashy above :

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

Now, you're secure and your website works, AND you can work with the files fairly easily

jQuery get the rendered height of an element?

If you are using jQuery already, your best bet is .outerHeight() or .height(), as has been stated.

Without jQuery, you can check the box-sizing in use and add up various paddings + borders + clientHeight, or you can use getComputedStyle:

var h = getComputedStyle(document.getElementById('someDiv')).height;

h will now be a string like a "53.825px".

And I can't find the reference, but I think I heard getComputedStyle() can be expensive, so it's probably not something you want to call on each window.onscroll event (but then, neither is jQuery's height()).

Reading rows from a CSV file in Python

I just leave my solution here.

import csv
import numpy as np

with open(name, newline='') as f:
    reader = csv.reader(f, delimiter=",")
    # skip header
    # convert csv to list and then to np.array
    data  = np.array(list(reader))[:, 1:] # skip the first column

print(data.shape) # => (N, 2)

# sum each row
s = data.sum(axis=1)
print(s.shape) # => (N,)

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

Here is a demo. Use position:fixed; top:0; left:0; so the header always stay on top.

?#header {
}.scroller {

Using cURL with a username and password?

It is safer to do:

curl --netrc-file my-password-file passing a plain user/password string on the command line, is a bad idea.

The format of the password file is (as per man curl):

machine <> login <username> password <password>


  1. Machine name must not include https:// or similar! Just the hostname.
  2. The words 'machine', 'login', and 'password' are just keywords; the actual information is the stuff after those keywords.

How do you implement a re-try-catch?

I know there are already many similar answers here, and mine is not much different, but I will post it anyway because it deals with a specific case/issue.

When dealing with the facebook Graph API in PHP you sometimes get an error, but immediately re-trying the same thing will give a positive result (for various magical Internet reasons that are beyond the scope of this question). In this case there is no need to fix any error, but to simply try again because there was some kind of "facebook error".

This code is used immediately after creating a facebook session:

//try more than once because sometimes "facebook error"
$attempt = 3;
while($attempt-- > 0)
    // To validate the session:
        $attempt = 0;
    catch (Facebook\FacebookRequestException $ex)
        // Session not valid, Graph API returned an exception with the reason.
        if($attempt <= 0){ echo $ex->getMessage(); }
    catch (\Exception $ex) 
        // Graph API returned info, but it may mismatch the current app or have expired.
        if($attempt <= 0){ echo $ex->getMessage(); }

Also, by having the for loop count down to zero ($attempt--) it makes it pretty easy to change the number of attempts in the future.

Python - IOError: [Errno 13] Permission denied:

For me, this was a permissions issue.

Use the 'Take Ownership' application on that specific folder. However, this sometimes seems to work only temporarily and is not a permanent solution.

PermissionError: [Errno 13] in python

For me, I was writing to a file that is opened in Excel.

How do write IF ELSE statement in a MySQL query

you must write it in SQL not it C/PHP style

IF( action = 2 AND state = 0, 1, 0 ) AS state

for use in query

IF ( action = 2 AND state = 0 ) THEN SET state = 1

for use in stored procedures or functions

libxml/tree.h no such file or directory

Follow the directions here, under "Setting up your project file."

Setting up your project file

You need to add libxml2.dylib to your project (don't put it in the Frameworks section). On the Mac, you'll find it at /usr/lib/libxml2.dylib and for the iPhone, you'll want the /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.0.sdk/usr/lib/libxml2.dylib version.

Since libxml2 is a .dylib (not a nice friendly .framework) we still have one more thing to do. Go to the Project build settings (Project->Edit Project Settings->Build) and find the "Search Paths". In "Header Search Paths" add the following path:


Also see the OP's answer.

Rerender view on browser resize with React

Had to bind it to 'this' in the constructor to get it working with Class syntax

class MyComponent extends React.Component {
  constructor(props) {
    this.resize = this.resize.bind(this)      
  componentDidMount() {
    window.addEventListener('resize', this.resize)
  componentWillUnmount() {
    window.removeEventListener('resize', this.resize)

What do .c and .h file extensions mean to C?

The .c files are source files which will be compiled. The .h files are used to expose the API of a program to either other part of that program or other program is you are creating a library.

For example, the program PizzaDelivery could have 1 .c file with the main program, and 1 .c file with utility functions. Now, for the main part of the program to be able to use the utility functions, you need to expose the API, via function prototype, into a .h file, this .h file being included by the main .c file.

Submit a form using jQuery

You can also use the jquery form plugin to submit using ajax aswell:

sed edit file in place

mv file.txt file.tmp && sed 's/foo/bar/g' < file.tmp > file.txt

Should preserve all hardlinks, since output is directed back to overwrite the contents of the original file, and avoids any need for a special version of sed.

Setting Android Theme background color

Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.

The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.

Escape Character in SQL Server

If you want to escape user input in a variable you can do like below within SQL

  Set @userinput = replace(@userinput,'''','''''')

The @userinput will be now escaped with an extra single quote for every occurance of a quote

How do I write out a text file in C# with a code page other than UTF-8?


System.IO.File.WriteAllText(path, text, Encoding.GetEncoding(28591));

Ambiguous overload call to abs(double)

Use fabs() instead of abs(), it's the same but for floats instead of integers.

How to create a custom exception type in Java?

You just need to create a class which extends Exception (for a checked exception) or any subclass of Exception, or RuntimeException (for a runtime exception) or any subclass of RuntimeException.

Then, in your code, just use

if (word.contains(" "))
    throw new MyException("some message");

Read the Java tutorial. This is basic stuff that every Java developer should know:

Getting "type or namespace name could not be found" but everything seems ok?

In my case, adding the dll as a reference gave the type or namespace name could not be found error. However, copying and pasting the dll file directly in bin folder resolved the error.

No idea why this worked.

How can I check if string contains characters & whitespace, not just whitespace?

This can be fast solution

return input < "\u0020" + 1;

Why do we use web.xml?

It says all the requests to go through WicketFilter

Also, if you use wicket WicketApplication for application level settings. Like URL patterns and things that are true at app level

This is what you need really,

Reading from memory stream to string

If you'd checked the results of stream.Read, you'd have seen that it hadn't read anything - because you haven't rewound the stream. (You could do this with stream.Position = 0;.) However, it's easier to just call ToArray:

settingsString = LocalEncoding.GetString(stream.ToArray());

(You'll need to change the type of stream from Stream to MemoryStream, but that's okay as it's in the same method where you create it.)

Alternatively - and even more simply - just use StringWriter instead of StreamWriter. You'll need to create a subclass if you want to use UTF-8 instead of UTF-16, but that's pretty easy. See this answer for an example.

I'm concerned by the way you're just catching Exception and assuming that it means something harmless, by the way - without even logging anything. Note that using statements are generally cleaner than writing explicit finally blocks.

Sending an Intent to browser to open specific URL

From XML

In case if you have the web-address/URL displayed on your view and you want it to make it clikable and direct user to particular website You can use:


In same way you can use different attributes of autoLink(email, phone, map, all) to accomplish your task...

error: expected class-name before ‘{’ token

I got the same error with a different problem,

I used namespaces in my headers and forgot the closing bracket and got this cryptic error instead.

How to pass a vector to a function?

You're passing in a pointer *random but you're using it like a reference &random

The pointer (what you have) says "This is the address in memory that contains the address of random"

The reference says "This is the address of random"

Facebook Architecture

"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"

I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.

Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.

If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.

How do I show a running clock in Excel?

See the below code (taken from this post)

Put this code in a Module in VBA (Developer Tab -> Visual Basic)

Dim TimerActive As Boolean
Sub StartTimer()
End Sub
Private Sub Start_Timer()
    TimerActive = True
    Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
    TimerActive = False
End Sub
Private Sub Timer()
    If TimerActive Then
        ActiveSheet.Cells(1, 1).Value = Time
        Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
    End If
End Sub

You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.

Private Sub Workbook_Open()
End Sub

Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.

How to resize a VirtualBox vmdk file

If you want to end having back a vmdk hard disk (maybe you are interested in using the disk in vwmare too), the complete steps are:

VBoxManage clonemedium "source.vmdk" "cloned.vdi" --format vdi
VBoxManage modifymedium "cloned.vdi" --resize 51200
VBoxManage clonemedium "cloned.vdi" "resized.vmdk" --format vmdk

The above will resize the hard disk up to 50GB (50 * 1024MB).

To complete things you need to resize the drive too! To achieve this, you might want to download gparted iso and boot from that iso to resize your drive (select the iso from within the virtualbox settings).

P.S. If your new size is too small, you'll get the same error even with your new vdi file.

git: Switch branch and ignore any changes without committing

Follow these steps:

  1. Git stash save will save all your changes even if you switch between branches.
git stash save
  1. Git checkout any other branch, now since you saved your changes you can move around any branch. The above command will make sure that your changes are saved.
git checkout branch
  1. Now when you come back to the branch use this command to get all your changes back.
git stash pop

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

.catch(error => { throw error}) is a no-op. It results in unhandled rejection in route handler.

As explained in this answer, Express doesn't support promises, all rejections should be handled manually:

router.get("/emailfetch", authCheck, async (req, res, next) => {
  try {
  //listing messages in users mailbox 
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
    emailFetch =
  } catch (err) {

How to enable C# 6.0 feature in Visual Studio 2013?

Information for obsoleted prerelease software:

According to this it's just a install and go for Visual Studio 2013:

In fact, installing the C# 6.0 compiler from this release involves little more than installing a Visual Studio 2013 extension, which in turn updates the MSBuild target files.

So just get the files from and you are ready to go.

You do have to know it is an outdated version of the specs implemented there, since they no longer update the package for Visual Studio 2013:

You can also try April's End User Preview, which installs on top of Visual Studio 2013. (note: this VS 2013 preview is quite out of date, and is no longer updated)

So if you do want to use the latest version, you have to download the Visual Studio 2015.

Write a mode method in Java to find the most frequently occurring element in an array

Here, I have coded using single loop. We are getting mode from a[j-1] because localCount was recently updated when j was j-1. Also N is size of the array & counts are initialized to 0.

        //After sorting the array 
        i = 0,j=0;
        while(i!=N && j!=N){
            if(ar[i] == ar[j]){
                localCount = 0;
            if(localCount > globalCount){
                globalCount = localCount;
                mode = ar[j-1]; 

Doing HTTP requests FROM Laravel to an external API

Basic Solution for Laravel 8 is

use Illuminate\Support\Facades\Http;

$response = Http::get('');

I had conflict between "GuzzleHTTP sending requests" and "Illuminate\Http\Request;" don't ask me why... [it's here to be searchable]

So looking for 1sec i found in Laravel 8 Doc...

**Guzzle is inside the Laravel 8 Http Request !**

as you can see

Laravel provides an expressive, minimal API around the Guzzle HTTP client, allowing you to quickly make outgoing HTTP requests to communicate with other web applications. Laravel's wrapper around Guzzle is focused on its most common use cases and a wonderful developer experience.

It worked for me very well, have fun and if helpful point up!

How do I specify the platform for MSBuild?

Hopefully this helps someone out there.

For platform I was specifying "Any CPU", changed it to "AnyCPU" and that fixed the problem.

msbuild C:\Users\Project\Project.publishproj /p:Platform="AnyCPU"  /p:DeployOnBuild=true /p:PublishProfile=local /p:Configuration=Debug

If you look at your .csproj file you'll see the correct platform name to use.

How to return rows from left table not found in right table?

This page gives a decent breakdown of the different join types, as well as venn diagram visualizations to help... well... visualize the difference in the joins.

As the comments said this is a quite basic query from the sounds of it, so you should try to understand the differences between the joins and what they actually mean.

Check out

You're looking for a query such as:

DECLARE @table1 TABLE (test int)
DECLARE @table2 TABLE (test int)



-- Here's the important part
FROM    @table1 a
LEFT    join @table2 b on a.test = b.test -- this will return all rows from a
WHERE   b.test IS null -- this then excludes that which exist in both a and b

-- Returned results:


Convert int to char in java

look at the following program for complete conversion concept

class typetest{
    public static void main(String args[]){
        byte a=1,b=2;
        char c=1,d='b';
        short e=3,f=4;
        int g=5,h=6;
        float i;
        double k=10.34,l=12.45;
        System.out.println("value of char variable c="+c);
        // if we assign an integer value in char cariable it's possible as above
        // but it's not possible to assign int value from an int variable in char variable 
        // (d=g assignment gives error as incompatible type conversion)
        System.out.println("char to int conversion is possible");
        System.out.println("int to double conversion is possible");
        System.out.println("int to float is possible and value of i = "+i);
        System.out.println("float to double is possible");

hope ,it will help at least something

Call to undefined function mysql_connect

Background about my (similar) problem:

I was asked to fix a PHP project, which made use of short tags. My WAMP server's PHP.ini had short_open_tag = off. In order to run the project for the first time, I modified this setting to short_open_tag = off.

PROBLEM Surfaced: Immediately after this change, all my mysql_connect() calls failed. It threw an error

fatal error: call to undefined function mysql_connect.

Solution: Simply set short_open_tag = off.

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

select development team in both project and target rest all things set to automatic then it will work

Java 8 List<V> into Map<K, V>

Map<String, Set<String>> collect = Arrays.asList(Locale.getAvailableLocales()).stream().collect(Collectors
                .toMap(l -> l.getDisplayCountry(), l -> Collections.singleton(l.getDisplayLanguage())));

How do I get the XML root node with C#?

I got the same question here. If the document is huge, it is not a good idea to use XmlDocument. The fact is that the first element is the root element, based on which XmlReader can be used to get the root element. Using XmlReader will be much more efficient than using XmlDocument as it doesn't require load the whole document into memory.

  using (XmlReader reader = XmlReader.Create(<your_xml_file>)) {
    while (reader.Read()) {
      // first element is the root element
      if (reader.NodeType == XmlNodeType.Element) {

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

Use X-Requested-With: XMLHttpRequest with your request header. So the response header will not contain WWW-Authenticate:Basic.

beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', ("Basic "
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

Clicking URLs opens default browser

If you're using a WebView you'll have to intercept the clicks yourself if you don't want the default Android behaviour.

You can monitor events in a WebView using a WebViewClient. The method you want is shouldOverrideUrlLoading(). This allows you to perform your own action when a particular URL is selected.

You set the WebViewClient of your WebView using the setWebViewClient() method.

If you look at the WebView sample in the SDK there's an example which does just what you want. It's as simple as:

private class HelloWebViewClient extends WebViewClient {
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return true;

Getting time difference between two times in PHP

You can also use DateTime class:

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');


1 second(s)

What Does 'zoom' do in CSS?

Surprised that nobody mentioned that zoom: 1; is useful for IE6-7, to solve most IE-only bugs by triggering hasLayout.

Remove blue border from css custom-styled button in Chrome

Don't forget the !important declaration, for a better result

button:focus {outline:0 !important;}

A rule that has the !important property will always be applied no matter where that rule appears in the CSS document.

How can I format a String number to have commas and round?

you can also use below solution -

public static String getRoundOffValue(double value){

        DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
        return df.format(value);

Passing multiple argument through CommandArgument of Button in

A little more elegant way of doing the same adding on to the above comment ..

<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
      <asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
      <asp:BoundField DataField="EntityId" HeaderText="EntityId"  />
    <asp:TemplateField ShowHeader="false">
           <asp:LinkButton ID="lnkCustomize" Text="Delete"  CommandName="Delete"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 

And on the server side:

protected void deleteRow(object sender, GridViewDeleteEventArgs e)
    string IdTemplate= e.Values["IdTemplate"].ToString();
    string EntityId = e.Values["EntityId"].ToString();

   // Do stuff..

Reading and writing binary file

You should pass length into fwrite instead of sizeof(buffer).

What's the main difference between Java SE and Java EE?

Java SE (formerly J2SE) is the basic Java environment. In Java SE, you make all the "standards" programs with Java, using the API described here. You only need a JVM to use Java SE.

Java EE (formerly J2EE) is the enterprise edition of Java. With it, you make websites, Java Beans, and more powerful server applications. Besides the JVM, you need an application server Java EE-compatible, like Glassfish, JBoss, and others.

How do I make a relative reference to another workbook in Excel?

I had a similar problem that I solved by using the following sequence:

  1. use the CELL("filename") function to get the full path to the current sheet of the current file.

  2. use the SEARCH() function to find the start of the [FileName]SheetName string of your current excel file and the sheet.

  3. use the LEFT function to extract the full path name of the directory that contains your current file.

  4. Concatenate the directory path name found in step #3 with the name of the file, the name of the worksheet, and the cell reference that you want to access.

  5. use the INDIRECT() function to access the CellPathName that you created in step #4.

Note: these same steps can also be used to access cells in files whose names are created dynamically. In step #4, use a text string that is dynamically created from the contents of cells, the current date or time, etc. etc.

A cell reference example (with each piece assembled separately) that includes all of these steps is:

=INDIRECT("'" & LEFT(CELL("filename"),SEARCH("[MyFileName]MySheetName",CELL("filename")) - 1) & "[" & "OtherFileName" & "]" & "OtherSheetName" & "'!" & "$OtherColumn$OtherRow" & "'")

Note that LibreOffice uses a slightly different CellPatnName syntax, as in the following example:

=INDIRECT(LEFT(CELL("filename"),SEARCH("[MyFileName]MySheetName",CELL("filename")) - 1) & "OtherFileName" & "'#$" & "OtherSheetName" & "." & "$OtherColumn$OtherRow")

What does the "On Error Resume Next" statement do?

On Error Statement - Specifies that when a run-time error occurs, control goes to the statement immediately following the statement. How ever Err object got populated.(Err.Number, Err.Count etc)

Changing capitalization of filenames in Git

Starting Git 2.0.1 (June 25th, 2014), a git mv will just work on a case insensitive OS.

See commit baa37bf by David Turner (dturner-tw).

mv: allow renaming to fix case on case insensitive filesystems

"git mv hello.txt Hello.txt" on a case insensitive filesystem always triggers "destination already exists" error, because these two names refer to the same path from the filesystem's point of view and requires the user to give "--force" when correcting the case of the path recorded in the index and in the next commit.

Detect this case and allow it without requiring "--force".

git mv hello.txt Hello.txt just works (no --force required anymore).

The other alternative is:

git config --global core.ignorecase false

And rename the file directly; git add and commit.

How to determine if OpenSSL and mod_ssl are installed on Apache2

The default Apache install is configured to send this information on the Server header line. You can view this for any server using the curl command.

$ curl --head http://localhost/
HTTP/1.1 200 OK
Date: Fri, 04 Sep 2009 08:14:03 GMT
Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8a DAV/2 PHP/5.2.6 SVN/1.5.4 proxy_html/3.0.0

Android Studio Image Asset Launcher Icon Background Color

the above approach didn't work for me on Android Studio 3.0. It still shows the background. I just made an empty background file

<?xml version="1.0" encoding="utf-8"?>

This worked except the full bleed layers

System.loadLibrary(...) couldn't find native library in my case

please add all suport


ndk {
        moduleName "serial_port"
        ldLibs "log", "z", "m"
        abiFilters "arm64-v8a","armeabi", "armeabi-v7a", "x86","x86_64","mips","mips64"


APP_ABI := arm64-v8a armeabi armeabi-v7a x86 x86_64 mips mips64

How to avoid using Select in Excel VBA

Two main reasons why .Select, .Activate, Selection, Activecell, Activesheet, Activeworkbook, etc. should be avoided

  1. It slows down your code.
  2. It is usually the main cause of runtime errors.

How do we avoid it?

1) Directly work with the relevant objects

Consider this code

Selection.Value = "Blah"
Selection.NumberFormat = "@"

This code can also be written as

With Sheets("Sheet1").Range("A1")
    .Value = "Blah"
    .NumberFormat = "@"
End With

2) If required declare your variables. The same code above can be written as

Dim ws as worksheet

Set ws = Sheets("Sheet1")

With ws.Range("A1")
    .Value = "Blah"
    .NumberFormat = "@"
End With

ArrayList filter

In , they introduced the method removeIf which takes a Predicate as parameter.

So it will be easy as:

List<String> list = new ArrayList<>(Arrays.asList("How are you",
                                                  "How you doing",
list.removeIf(s -> !s.contains("How"));

Send Message in C#

You don't need to send messages.

Add an event to the one form and an event handler to the other. Then you can use a third project which references the other two to attach the event handler to the event. The two DLLs don't need to reference each other for this to work.

Rails: FATAL - Peer authentication failed for user (PG::Error)

For permanent solution:

The problem is with your pg_hba. This line:

local   all             postgres                                peer

Should be

local   all             postgres                                md5

Then restart your postgresql server after changing this file.

If you're on Linux, command would be

sudo service postgresql restart

oracle.jdbc.driver.OracleDriver ClassNotFoundException


This line causes ClassNotFoundException, because you haven't placed ojdbc14.jar file in your lib folder of the project. or YOu haven't set the classpath of the required jar

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Until I get a better option, this is the most "bootstrappy" answer I can work out:


I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less file:

in _layout.cshtml master page

  • Move footer outside the body-content container
  • Use boostrap's navbar-fixed-bottom on the footer
  • Drop the <hr/> before the footer (as now redundant)

Relevant page HTML:

<div class="container-fluid body-content">
<footer class="navbar-fixed-bottom">
    <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>

In Site.less

  • Set HTML and BODY heights to 100%
  • Set BODY overflow to hidden
  • Set body-content div position to absolute
  • Set body-content div top to @navbar-height instead of hard-wiring value
  • Set body-content div bottom to 30px.
  • Set body-content div left and right to 0
  • Set body-content div overflow-y to auto


html {
    height: 100%;

    body {
        height: 100%;
        overflow: hidden;

        .container-fluid.body-content {
            position: absolute;
            top: @navbar-height;
            bottom: 30px;
            right: 0;
            left: 0;
            overflow-y: auto;

The remaining problem is there seems to be no defining variable for the footer height in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.

Add property to an array of objects

  Object.defineProperty(Results, "Active", {value : 'true',
                       writable : true,
                       enumerable : true,
                       configurable : true});

Remove white space above and below large text in an inline-block element

The browser is not adding any padding. Instead, letters (even uppercase letters) are generally considerably smaller in the vertical direction than the height of the font, not to mention the line height, which is typically by default about 1.2 times the font height (font size).

There is no general solution to this because fonts are different. Even for fixed font size, the height of a letter varies by font. And uppercase letters need not have the same height in a font.

Practical solutions can be found by experimentation, but they are unavoidably font-dependent. You will need to set the line height essentially smaller than the font size. The following seems to yield the desired result in different browsers on Windows, for the Arial font:

  display: inline-block;_x000D_
  font-size: 50px;_x000D_
  background-color: green;_x000D_
  line-height: 0.75em;_x000D_
  font-family: Arial;_x000D_
  position: relative;_x000D_
  bottom: -0.02em;_x000D_
<span class=foo><span class=bar>BIG TEXT</span></span>

The nested span elements are used to displace the text vertically. Otherwise, the text sits on the baseline, and under the baseline, there is room reserved for descenders (as in letters j and y).

If you look closely (with zooming), you will notice that there is very small space above and below most letters here. I have set things so that the letter “G” fits in. It extends vertically a bit farther than other uppercase letters because that way the letters look similar in height. There are similar issues with other letters, like “O”. And you need to tune the settings if you’ll need the letter “Q” since it has a descender that extends a bit below the baseline (in Arial). And of course, if you’ll ever need “É”, or almost any diacritic mark, you’re in trouble.

Android activity life cycle - what are all these methods for?

Adding some more info on top of highly rated answer (Added additional section of KILLABLE and next set of methods, which are going to be called in the life cycle):


enter image description here

Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed.

Because of this, you should use the onPause() method to write any persistent data (such as user edits) to storage. In addition, the method onSaveInstanceState(Bundle) is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created.

Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(Bundle) because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.

I would like to add few more methods. These are not listed as life cycle methods but they will be called during life cycle depending on some conditions. Depending on your requirement, you may have to implement these methods in your application for proper handling of state.

onPostCreate(Bundle savedInstanceState)

Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called).


Called when activity resume is complete (after onResume() has been called).

onSaveInstanceState(Bundle outState)

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

onRestoreInstanceState(Bundle savedInstanceState)

This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState.

My application code using all these methods:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText txtUserName;
    private EditText txtPassword;
    Button  loginButton;
    protected void onCreate(Bundle savedInstanceState) {
        Log.d("Ravi","Main OnCreate");
        txtUserName=(EditText) findViewById(;
        txtPassword=(EditText) findViewById(;
        loginButton =  (Button)  findViewById(;


    public void onClick(View view) {
        Log.d("Ravi", "Login processing initiated");
        Intent intent = new Intent(this,LoginActivity.class);
        Bundle bundle = new Bundle();
       // IntentFilter
    public void onActivityResult(int requestCode, int resultCode, Intent resIntent){
        Log.d("Ravi back result:", "start");
        String result = resIntent.getStringExtra("result");
        Log.d("Ravi back result:", result);
        TextView txtView = (TextView)findViewById(;

        Intent sendIntent = new Intent();
        sendIntent.putExtra(Intent.EXTRA_TEXT, "Message...");

    protected void onStart() {
        Log.d("Ravi","Main Start");

    protected void onRestart() {
        Log.d("Ravi","Main ReStart");

    protected void onPause() {
        Log.d("Ravi","Main Pause");

    protected void onResume() {
        Log.d("Ravi","Main Resume");

    protected void onStop() {
        Log.d("Ravi","Main Stop");

    protected void onDestroy() {
        Log.d("Ravi","Main OnDestroy");

    public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        Log.d("Ravi","Main onPostCreate");

    protected void onPostResume() {
        Log.d("Ravi","Main PostResume");

    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);

    protected void onRestoreInstanceState(Bundle savedInstanceState) {

Login Activity:

public class LoginActivity extends AppCompatActivity {

    private TextView txtView;
    protected void onCreate(Bundle savedInstanceState) {
        txtView = (TextView) findViewById(;
        Log.d("Ravi","Login OnCreate");
        Bundle bundle = getIntent().getExtras();
        //Intent  intent = new Intent(this,MainActivity.class);
        Intent  intent = new Intent();
       // finish();

output: ( Before pause)

D/Ravi: Main OnCreate
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

output: ( After resume from pause)

D/Ravi: Main ReStart
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

Note that onPostResume() is invoked even though it's not quoted as life cycle method.

ALTER DATABASE failed because a lock could not be placed on database

Killing the process ID worked nicely for me. When running "EXEC sp_who2" Command over a new query window... and filter the results for the "busy" database , Killing the processes with "KILL " command managed to do the trick. After that all worked again.

How to download python from command-line?

wget --no-check-certificate
tar -xzf Python-2.7.11.tgz  
cd Python-2.7.11

Now read the README file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.

sudo make install  

For Python 3.5 use the following download address:

For other versions and the most up to date download links:

Difference Between Schema / Database in MySQL

Yes, people use these terms interchangeably with regard to MySQL. Though oftentimes you will hear people inappropriately refer to the entire database server as the database.

Get Category name from Post ID

Use get_the_category() function.

$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);

Convert byte to string in Java

This is my version:

public String convertBytestoString(InputStream inputStream)
    int bytes;
    byte[] buffer = new byte[1024];

    bytes =;
    String stringData = new String(buffer,0,bytes);

    return stringData;


How to prepend a string to a column value in MySQL?

You can use the CONCAT function to do that:

UPDATE tbl SET col=CONCAT('test',col);

If you want to get cleverer and only update columns which don't already have test prepended, try

UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';

How to get Android crash logs?

The way to do this is to implement the Thread.UncaughtExceptionHandler interface and pass it to Thread.setDefaultUncaughtExceptionHandler() at the beginning of your Activity's onCreate(). Here is the implementation class TopExceptionHandler.

public class TopExceptionHandler implements Thread.UncaughtExceptionHandler {
    private Thread.UncaughtExceptionHandler defaultUEH;
    private Activity app = null;

    public TopExceptionHandler(Activity app) {
        this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); = app;

    public void uncaughtException(Thread t, Throwable e) {
        StackTraceElement[] arr = e.getStackTrace();
        String report = e.toString()+"\n\n";
        report += "--------- Stack trace ---------\n\n";
        for (int i=0; i<arr.length; i++) {
            report += "    "+arr[i].toString()+"\n";
        report += "-------------------------------\n\n";

        // If the exception was thrown in a background thread inside
        // AsyncTask, then the actual exception can be found with getCause

        report += "--------- Cause ---------\n\n";
        Throwable cause = e.getCause();
        if(cause != null) {
            report += cause.toString() + "\n\n";
            arr = cause.getStackTrace();
            for (int i=0; i<arr.length; i++) {
                report += "    "+arr[i].toString()+"\n";
        report += "-------------------------------\n\n";

        try {
            FileOutputStream trace = app.openFileOutput("stack.trace", 
        } catch(IOException ioe) {
        // ...

        defaultUEH.uncaughtException(t, e);

Note We let the Android framework's defaultUEH to handle it.

At the top of your Activity register an instance of above class like this:

public void onCreate(Bundle savedInstanceState) {

Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(this));

This handler saves the trace in a file. When ReaderScope restarts next time, it detects the file and prompts the user if he/she wants to email it to the developer.

To Email the Stack Trace, execute following code to pack it in an email.

try {
    BufferedReader reader = new BufferedReader(
        new InputStreamReader(ReaderScopeActivity.this.openFileInput("stack.trace")));
    while((line = reader.readLine()) != null) {
        trace += line+"\n";
} catch(FileNotFoundException fnfe) {
    // ...
} catch(IOException ioe) {
    // ...

Intent sendIntent = new Intent(Intent.ACTION_SEND);
String subject = "Error report";
String body = "Mail this to [email protected]: " + "\n" + trace + "\n";

sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"[email protected]"});
sendIntent.putExtra(Intent.EXTRA_TEXT, body);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject);

ReaderScopeActivity.this.startActivity(Intent.createChooser(sendIntent, "Title:"));


Or you can also use ACRA Error Reporting System.Just Include the ACRA.jar in your project libs and use the below code snippet before your launcher activity class declaration

@ReportsCrashes(formKey = "", mailTo = "[email protected];[email protected]", mode = ReportingInteractionMode.SILENT) 

or You can try this from console:-

adb logcat -b crash 

Removing duplicates from rows based on specific columns in an RDD/Spark DataFrame

Agree with David. To add on, it may not be the case that we want to groupBy all columns other than the column(s) in aggregate function i.e, if we want to remove duplicates purely based on a subset of columns and retain all columns in the original dataframe. So the better way to do this could be using dropDuplicates Dataframe api available in Spark 1.4.0

For reference, see:

Ruby Hash to array of values

hash.collect { |k, v| v }
#returns [["a", "b", "c"], ["b", "c"]] 

Enumerable#collect takes a block, and returns an array of the results of running the block once on every element of the enumerable. So this code just ignores the keys and returns an array of all the values.

The Enumerable module is pretty awesome. Knowing it well can save you lots of time and lots of code.

PDF Editing in PHP?

If you need really simple PDFs, then Zend or FPDF is fine. However I find them difficult and frustrating to work with. Also, because of the way the API works, there's no good way to separate content from presentation from business logic.

For that reason, I use dompdf, which automatically converts HTML and CSS to PDF documents. You can lay out a template just as you would for an HTML page and use standard HTML syntax. You can even include an external CSS file. The library isn't perfect and very complex markup or css sometimes gets mangled, but I haven't found anything else that works as well.

What is cURL in PHP?

cURL is a way you can hit a URL from your code to get a html response from it. cURL means client URL which allows you to connect with other URLs and use their responses in your code.

Simple way to transpose columns and rows in SQL?

This normally requires you to know ALL the column AND row labels beforehand. As you can see in the query below, the labels are all listed in their entirely in both the UNPIVOT and the (re)PIVOT operations.

MS SQL Server 2012 Schema Setup:

create table tbl (
    color varchar(10), Paul int, John int, Tim int, Eric int);
insert tbl select 
    'Red' ,1 ,5 ,1 ,3 union all select
    'Green' ,8 ,4 ,3 ,5 union all select
    'Blue' ,2 ,2 ,9 ,1;

Query 1:

select *
from tbl
unpivot (value for name in ([Paul],[John],[Tim],[Eric])) up
pivot (max(value) for color in ([Red],[Green],[Blue])) p


| Eric |   3 |     5 |    1 |
| John |   5 |     4 |    2 |
| Paul |   1 |     8 |    2 |
|  Tim |   1 |     3 |    9 |

Additional Notes:

  1. Given a table name, you can determine all the column names from sys.columns or FOR XML trickery using local-name().
  2. You can also build up the list of distinct colors (or values for one column) using FOR XML.
  3. The above can be combined into a dynamic sql batch to handle any table.

How to insert a new key value pair in array in php?

To add:

$arr["key"] = "value";

Then simply return $arr

Can't return directly like this way return $arr["key"] = "value";

PHP Multidimensional Array Searching (Find key by specific value)

function search($array, $key, $value) 
    $results = array(); 

    if (is_array($array)) 
        if (isset($array[$key]) && $array[$key] == $value) 
            $results[] = $array; 

        foreach ($array as $subarray) 
            $results = array_merge($results, search($subarray, $key, $value)); 

    return $results; 

What causes this error? "Runtime error 380: Invalid property value"

I think, basically the problem lies in the fact, as to under what version of the O/S has the programme been compiled and under what version of the O/S are you running the programme. I have seen a lot of updated dll and ocx files causing similar errors, especially when the programme has been compiled under older version of the dll and ocx files and during set up the latest dll and ocx files are retained.

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

If anyone wants to get the count with based on multiple conditions than here is a sample custom query

@Query("select count(sl) from SlUrl sl where sl.user =?1 And sl.creationDate between ?2 And ?3")
    long countUrlsBetweenDates(User user, Date date1, Date date2);

TypeError : Unhashable type

The real reason because set does not work is the fact, that it uses the hash function to distinguish different values. This means that sets only allows hashable objects. Why a list is not hashable is already pointed out.

how to use "AND", "OR" for RewriteCond on Apache?

This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.

In the top section you'll quickly spot the defines used to name these flags:

#define CONDFLAG_NONE               1<<0
#define CONDFLAG_NOCASE             1<<1
#define CONDFLAG_NOTMATCH           1<<2
#define CONDFLAG_ORNEXT             1<<3
#define CONDFLAG_NOVARY             1<<4

and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:

else if (   strcasecmp(key, "ornext") == 0
         || strcasecmp(key, "OR") == 0    ) {
    cfg->flags |= CONDFLAG_ORNEXT;

The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):

# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
    rewritecond_entry *c = &conds[i];

    # execute the current Condition, see if it matches
    rc = apply_rewrite_cond(c, ctx);

    # does this Condition have an 'OR' flag?
    if (c->flags & CONDFLAG_ORNEXT) {
        if (!rc) {
            /* One condition is false, but another can be still true. */
        else {
            /* skip the rest of the chained OR conditions */
            while (   i < rewriteconds->nelts
                   && c->flags & CONDFLAG_ORNEXT) {
                c = &conds[++i];
    else if (!rc) {
        return 0;

You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) ). If you would, for example, have these Conditions:

RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D

it would be interpreted as if ( (A OR B OR C) and D ).

change PATH permanently on Ubuntu

Assuming you want to add this path for all users on the system, add the following line to your /etc/profile.d/ (and possibly play.csh, etc):

export PATH

assignment operator overloading in c++


using namespace std;

class employee
    int idnum;
    double salary;

        employee(int a,int b)

        void dis()
            cout<<"1st emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl<<endl;

        void operator=(employee &emp)

        void show()
            cout<<"2nd emp:"<<endl<<"idnum="<<idnum<<endl<<"salary="<<salary<<endl;

    int a;
    double b;

    cout<<"enter id num and salary"<<endl;
    employee e1(a,b);
    employee e2;

What is the difference between a port and a socket?

With some analogy

Although a lot technical stuff is already given above for sockets... I would like to add my answer, just in case , if somebody still could not feel the difference between ip, port and sockets

Consider a server S,

and say person X,Y,Z need a service (say chat service) from that server S


IP address tells --> who? is that chat server 'S' that X,Y,Z want to contact

okay, you got "who is the server"

but suppose that server 'S' is providing some other services to other people as well,say 'S' provides storage services to person A,B,C


port tells ---> which? service you (X,Y,Z) need i.e. chat service and not that storage service

okay.., you make server to come to know that 'chat service' is what you want and not the storage


you are three and the server might want to identify all the three differently

there comes the socket

now socket tells--> which one? particular connection

that is , say ,

socket 1 for person X

socket 2 for person Y

and socket 3 for person Z

I hope it helps someone who was still confused :)

How to do IF NOT EXISTS in SQLite

How about this?


(Untested as I don't have SQLite... however this link is quite descriptive.)

Additionally, this should also work:

SELECT 'ANI Received'

Replace line break characters with <br /> in ASP.NET MVC Razor view

I needed to break some text into paragraphs ("p" tags), so I created a simple helper using some of the recommendations in previous answers (thank you guys).

public static MvcHtmlString ToParagraphs(this HtmlHelper html, string value) 
        value = html.Encode(value).Replace("\r", String.Empty);
        var arr = value.Split('\n').Where(a => a.Trim() != string.Empty);
        var htmlStr = "<p>" + String.Join("</p><p>", arr) + "</p>";
        return MvcHtmlString.Create(htmlStr);