Programs & Examples On #Ecos

A small-footprint real-time operating system intended for use in embedded systems across multiple architectures.

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

Specifying onClick event type with Typescript and React.Konva

As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget in this way.

interface KonvaTextEventTarget extends EventTarget {
  index: number

interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
  target: KonvaTextEventTarget

I then can declare the event as KonvaMouseEvent in my onclick MouseEventHandler function.

onClick={(event: KonvaMouseEvent) => {

I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.

Download and save PDF file with Python requests module

You can use urllib:

import urllib.request
urllib.request.urlretrieve(url, "filename.pdf")

Xcode Project vs. Xcode Workspace - Differences

A workspace is a collection of projects. It's useful to organize your projects when there's correlation between them (e.g.: Project A includes a library, that is provided as a project itself as project B. When you build the workspace project B is compiled and linked in project A).
It's common to use a workspace in the popular CocoaPods. When you install your pods, they are placed inside a workspace, that holds your project and the pod libraries.

How to enter a formula into a cell using VBA?

You aren't building your formula right.

Worksheets("EmployeeCosts").Range("B" & var1a).Formula =  "=SUM(H5:H" & var1a & ")"

This does the same as the following lines do:

Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"

which is what you are trying to do.

Also, you want to have the = at the beginning of the formala.

What is best way to start and stop hadoop ecosystem, with command line?

From Hadoop page, 

This will startup a Namenode, Datanode, Jobtracker and a Tasktracker on your machine.

This will bring up HDFS with the Namenode running on the machine you ran the command on. On such a machine you would need to separately start the job tracker has to be run on the master node

You would use on a single node cluster (i.e. where you would have all the services on the same node.The namenode is also the datanode and is the master node).

In multi-node setup,

You will use on the master node and would start what is necessary on the slaves as well.


Use on the node you want the Namenode to run on. This will bring up HDFS with the Namenode running on the machine you ran the command on and Datanodes on the machines listed in the slaves file.

Use on the machine you plan to run the Jobtracker on. This will bring up the Map/Reduce cluster with Jobtracker running on the machine you ran the command on and Tasktrackers running on machines listed in the slaves file. as stated by Tariq is used on each individual node. The master node will not start the services on the slaves.In a single node setup this will act same as a multi-node setup you will have to access each node (master as well as slaves) and execute on each of them.

Have a look at this it call config followed by dfs and mapred

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

        exec( @sqlHeader)

    IF @@TRANCOUNT > 0

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

How to multiply a BigDecimal by an integer in Java

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

Dealing with "Xerces hell" in Java/Maven?

What would help, except for excluding, is modular dependencies.

With one flat classloading (standalone app), or semi-hierarchical (JBoss AS/EAP 5.x) this was a problem.

But with modular frameworks like OSGi and JBoss Modules, this is not so much pain anymore. The libraries may use whichever library they want, independently.

Of course, it's still most recommendable to stick with just a single implementation and version, but if there's no other way (using extra features from more libs), then modularizing might save you.

A good example of JBoss Modules in action is, naturally, JBoss AS 7 / EAP 6 / WildFly 8, for which it was primarily developed.

Example module definition:

<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.jboss.msc">
    <main-class name="org.jboss.msc.Version"/>
        <property name="" value="foo"/>
        <resource-root path="jboss-msc-1.0.1.GA.jar"/>
        <module name="javax.api"/>
        <module name="org.jboss.logging"/>
        <module name="org.jboss.modules"/>
        <!-- Optional deps -->
        <module name="javax.inject.api" optional="true"/>
        <module name="org.jboss.threads" optional="true"/>

In comparison with OSGi, JBoss Modules is simpler and faster. While missing certain features, it's sufficient for most projects which are (mostly) under control of one vendor, and allow stunning fast boot (due to paralelized dependencies resolving).

Note that there's a modularization effort underway for Java 8, but AFAIK that's primarily to modularize the JRE itself, not sure whether it will be applicable to apps.

What is Node.js' Connect, Express and "middleware"?

The stupid simple answer

Connect and Express are web servers for nodejs. Unlike Apache and IIS, they can both use the same modules, referred to as "middleware".

"java.lang.OutOfMemoryError: PermGen space" in Maven build

I have found a solution of git bash command when you try to build war using git mvn clean install for “java.lang.OutOfMemoryError: PermGen space” in Maven build error come

use below command first 

$ export MAVEN_OPTS="-Xmx512m -Xss32m"

then use your mvn command to clean install /build war file

$ mvn clean install

NOTE: you don't need -XX:MaxPermSize argument in MAVEN_OPTS when your are using jdk1.8
Java HotSpot(TM) Client VM warning: ignoring option MaxPermSize=XXXm; support was removed in 8.0

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

If you are getting this instead:

Error: Template parse errors:

There is no directive with "exportAs" set to "ngModel"

Which was reported as a bug in github, then likely it is not a bug since you might:

  1. have a syntax error (e.g. an extra bracket: [(ngModel)]]=), OR
  2. be mixing Reactive forms directives, such as formControlName, with the ngModel directive. This "has been deprecated in Angular v6 and will be removed in Angular v7", since this mixes both form strategies, making it:
  • seem like the actual ngModel directive is being used, but in fact it's an input/output property named ngModel on the reactive form directive that simply approximates (some of) its behavior. Specifically, it allows getting/setting the value and intercepting value events. However, some of ngModel's other features - like delaying updates withngModelOptions or exporting the directive - simply don't work (...)

  • this pattern mixes template-driven and reactive forms strategies, which we generally don't recommend because it doesn't take advantage of the full benefits of either strategy. (...)

  • To update your code before v7, you'll want to decide whether to stick with reactive form directives (and get/set values using reactive forms patterns) or switch over to template-driven directives.

When you have an input like this:

<input formControlName="first" [(ngModel)]="value">

It will show a warning about mixed form strategies in the browser's console:

It looks like you're using ngModel on the same form field as formControlName.

However, if you add the ngModel as a value in a reference variable, example:

<input formControlName="first" #firstIn="ngModel" [(ngModel)]="value">

The error above is then triggered and no warning about strategy mixing is shown.

Looping through a DataTable

     foreach (DataRow row in dt.Rows) 
        foreach (DataColumn col in dt.Columns)


MS doesn't support LIMIT in t-sql. Most of the times i just get MAX(ID) and then subtract.

select * from ORDERS where ID >(select MAX(ID)-10 from ORDERS)

This will return less than 10 records when ID is not sequential.

PHP Redirect with POST data

You can let PHP do a POST, but then your php will get the return, with all sorts of complications. I think the simplest would be to actually let the user do the POST.

So, kind-of what you suggested, you'll get indeed this part:

Customer fill detail in Page A, then in Page B we create another page show all the customer detail there, click a CONFIRM button then POST to Page C.

But you can actually do a javascript submit on page B, so there is no need for a click. Make it a "redirecting" page with a loading animation, and you're set.

How do I create a random alpha-numeric string in C++?

Mehrdad Afshari's answer would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders:

#include <iostream>
#include <ctime>
#include <unistd.h>

using namespace std;

string gen_random(const int len) {
    string tmp_s;
    static const char alphanum[] =
    srand( (unsigned) time(NULL) * getpid());


    for (int i = 0; i < len; ++i) 
        tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
    return tmp_s;

int main(int argc, char *argv[]) {
    cout << gen_random(12) << endl;
    return 0;

How to edit incorrect commit message in Mercurial?

Good news: hg 2.2 just added git like --amend option.

and in tortoiseHg, you can use "Amend current revision" by select black arrow on the right of commit button


How to make python Requests work via socks proxy

The modern way:

pip install -U requests[socks]


import requests

resp = requests.get('', 

How to access the first property of a Javascript object?

we can also do with this approch.

var example = {
  foo1: { /* stuff1 */},
  foo2: { /* stuff2 */},
  foo3: { /* stuff3 */}

Get paragraph text inside an element

Try this:

<li onclick="myfunction(this)">

function myfunction(li) {
    var TextInsideLi = li.getElementsByTagName('p')[0].innerHTML;

Live demo

jquery AJAX and json format

Currently you are sending the data as typical POST values, which look like this:


If you want to send data as json you need to create an object with data and stringify it.

data: JSON.stringify(someobject)

Swift: Reload a View Controller

In Swift 4:


"While .. End While" doesn't work in VBA?

While constructs are terminated not with an End While but with a Wend.

While counter < 20
    counter = counter + 1

Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.

Also in the VBA help file:

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.

background-size in shorthand background property (CSS3)

You can do as

        background-size:400px 100px,50px 50px;

CKEditor automatically strips classes from div

Another option if using drupal is simply to add the css style that you want to use. that way it does not strip out the style or class name.

so in my case under the css tab in drupal 7 simply add something like


also check that font-styles button is enabled

How are iloc and loc different?

  • DataFrame.loc() : Select rows by index value
  • DataFrame.iloc() : Select rows by rows number

example :

  1. Select first 5 rows of a table, df1 is your dataframe


  1. Select first A, B rows of a table, df1 is your dataframe


How to upload folders on GitHub

You can also use the command line, Change directory where your folder is located then type the following :

     git init
     git add <folder1> <folder2> <etc.>
     git commit -m "Your message about the commit"
     git remote add origin
     git push -u origin master
     git push origin master  

How to get browser width using JavaScript code?

An adapted solution to modern JS of Travis' answer:

const getPageWidth = () => {
  const bodyMax = document.body
    ? Math.max(document.body.scrollWidth, document.body.offsetWidth)
    : 0;

  const docElementMax = document.documentElement
    ? Math.max(
    : 0;

  return Math.max(bodyMax, docElementMax);

PostgreSQL error: Fatal: role "username" does not exist

Something as simple as changing port from 5432 to 5433 worked for me.

SQL Developer is returning only the date, not the time. How do I fix this?

Well I found this way :

Oracle SQL Developer (Left top icon) > Preferences > Database > NLS and set the Date Format as MM/DD/YYYY HH24:MI:SS

enter image description here

Using CSS to insert text

Also check out the attr() function of the CSS content attribute. It outputs a given attribute of the element as a text node. Use it like so:

<div class="Owner Joe" />

div:before {
  content: attr(class);

Or even with the new HTML5 custom data attributes:

<div data-employeename="Owner Joe" />

div:before {
  content: attr(data-employeename);

Hide console window from Process.Start C#

This should work, try;

Add a System Reference.

using System.Diagnostics;

Then use this code to run your command in a hiden CMD Window.

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Enter your command here";


I haven't done anything with rank, but I discovered this today with row_number().

select item, name, sold, row_number() over(partition by item order by sold) as row from table_name

This will result in some repeating row numbers since in my case each name holds all items. Each item will be ordered by how many were sold.

|glasses |store1|  30 | 1  |
|glasses |store2|  35 | 2  |
|glasses |store3|  40 | 3  |
|shoes   |store2|  10 | 1  |
|shoes   |store1|  20 | 2  |
|shoes   |store3|  22 | 3  |

Oracle DateTime in Where Clause?

You can also use the following to include the TIME portion in your query:

     , DEPT
 WHERE TIME_CREATED >= TO_DATE('26/JAN/2011 00:00:00', 'dd/mon/yyyy HH24:MI:SS');

Install numpy on python3.3 - Install pip for python3

In the solution below I used python3.4 as binary, but it's safe to use with any version or binary of python. it works fine on windows too (except the downloading pip with wget obviously but just save the file locally and run it with python).

This is great if you have multiple versions of python installed, so you can manage external libraries per python version.

So first, I'd recommend, it's great to install pip :


Then you need to install pip for your version of python, I have python3.4 so for me this is the command :


Now pip is installed for python3.4 and in order to get libraries for python3.4 one need to call it within this version, like this :

python3.4 -m pip

So if you want to install numpy you would use :

python3.4 -m pip install numpy

Note that numpy is quite the heavy library. I thought my system was hanging and failing. But using the verbose option, you can see that the system is fine :

python3.4 -m pip install numpy -v

This may tell you that you lack python.h but you can easily get it :

On RHEL (Red hat, CentOS, Fedora) it would be something like this :

yum install python34-devel

On debian-like (Debian, Ubuntu, Kali, ...) :

apt-get install python34-dev

Then rerun this :

python3.4 -m pip install numpy -v

differences between using wmode="transparent", "opaque", or "window" for an embedded object on a webpage

also, with wmode=opaque and with IE, the Flash gets the keyboard events, but also the html page receives them, so it can't be use for something like embedding a flash game. Very annoying

Pass Javascript Array -> PHP

AJAX requests are no different from GET and POST requests initiated through a <form> element. Which means you can use $_GET and $_POST to retrieve the data.

When you're making an AJAX request (jQuery example):

// JavaScript file

elements = [1, 2, 9, 15].join(',')
$.post('/test.php', {elements: elements})

It's (almost) equivalent to posting this form:

<form action="/test.php" method="post">
  <input type="text" name="elements" value="1,2,9,15">

In both cases, on the server side you can read the data from the $_POST variable:

// test.php file

$elements = $_POST['elements'];
$elements = explode(',', $elements);

For the sake of simplicity I'm joining the elements with comma here. JSON serialization is a more universal solution, though.

How to add text to a WPF Label in code?

In normal winForms, value of Label object is changed by,

myLabel.Text= "Your desired string";

But in WPF Label control, you have to use .content property of Label control for example,

myLabel.Content= "Your desired string";

How to subtract/add days from/to a date?

There is of course a lubridate solution for this:

date <- "2009-10-01"

ymd(date) - 5
# [1] "2009-09-26"

is the same as

ymd(date) - days(5)
# [1] "2009-09-26"

Other time formats could be:

ymd(date) - months(5)
# [1] "2009-05-01"

ymd(date) - years(5)
# [1] "2004-10-01"

ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

If your installation was recent, you should to confirm if your installation is the installation SERVER... as mysql-server-5.5.. Maybe you installed only "mysql" .. this is only client instead of the server.

How to disassemble a memory range with GDB?

fopen() is a C library function and so you won't see any syscall instructions in your code, just a regular function call. At some point, it does call open(2), but it does that via a trampoline. There is simply a jump to the VDSO page, which is provided by the kernel to every process. The VDSO then provides code to make the system call. On modern processors, the SYSCALL or SYSENTER instructions will be used, but you can also use INT 80h on x86 processors.

How to dynamically update labels captions in VBA form?

If you want to use this in VBA:

For i = 1 To X
    UserForm1.Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value

Django Multiple Choice Field / Checkbox Select Multiple

Brant's solution is absolutely correct, but I needed to modify it to make it work with multiple select checkboxes and commit=false. Here is my solution:

class Choices(models.Model):
    description = models.CharField(max_length=300)

class Profile(models.Model):
   user = models.ForeignKey(User, blank=True, unique=True, verbose_name_('user'))
   the_choices = models.ManyToManyField(Choices)

class ProfileForm(forms.ModelForm):
    the_choices = forms.ModelMultipleChoiceField(queryset=Choices.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Profile
        exclude = ['user']

if request.method=='POST':
    form = ProfileForm(request.POST)
    if form.is_valid():
        profile =
        profile.user = request.user
        form.save_m2m() # needed since using commit=False
        form = ProfileForm()

return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))

How to unapply a migration in ASP.NET Core with EF Core



> dotnet ef database update <previous-migration-name>

Package Manager Console

PM> Update-Database <previous-migration-name>


PM> Update-Database MyInitialMigration

Then try to remove last migration.

Removing migration without database update doesn't work because you applied changes to database.

If using PMC, Try: PM> update-database 0 This will wipe the database and allow you to remove the Migration Snapshot on your Solution

How can I throw CHECKED exceptions from inside Java 8 streams?

The only built-in way of handling checked exceptions that can be thrown by a map operation is to encapsulate them within a CompletableFuture. (An Optional is a simpler alternative if you don't need to preserve the exception.) These classes are intended to allow you to represent contingent operations in a functional way.

A couple of non-trivial helper methods are required, but you can arrive at code that's relatively concise, while still making it apparent that your stream's result is contingent on the map operation having completed successfully. Here's what it looks like:

    CompletableFuture<List<Class<?>>> classes =
            Stream.of("java.lang.String", "java.lang.Integer", "java.lang.Double")
                  .map(cfc -> cfc.thenApply(Class::getSuperclass))
                                                  (List<Class<?>> l1, List<Class<?>> l2) -> { l1.addAll(l2); return l1; },
                                                  x -> x));
           .exceptionally(t -> { System.out.println("unable to get class: " + t); return null; });

This produces the following output:

[class java.lang.Object, class java.lang.Number, class java.lang.Number]

The applyOrDie method takes a Function that throws an exception, and converts it into a Function that returns an already-completed CompletableFuture -- either completed normally with the original function's result, or completed exceptionally with the thrown exception.

The second map operation illustrates that you've now got a Stream<CompletableFuture<T>> instead of just a Stream<T>. CompletableFuture takes care of only executing this operation if the upstream operation succeeded. The API makes this explict, but relatively painless.

Until you get to the collect phase, that is. This is where we require a pretty significant helper method. We want to "lift" a normal collection operation (in this case, toList()) "inside" the CompletableFuture -- cfCollector() lets us do that using a supplier, accumulator, combiner, and finisher that don't need to know anything at all about CompletableFuture.

The helper methods can be found on GitHub in my MonadUtils class, which is very much still a work in progress.

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

Majorly there are 3 ways of creating Objects-

Simplest one is using object literals.

const myObject = {}

Though this method is the simplest but has a disadvantage i.e if your object has behaviour(functions in it),then in future if you want to make any changes to it you would have to change it in all the objects.

So in that case it is better to use Factory or Constructor Functions.(anyone that you like)

Factory Functions are those functions that return an object.e.g-

function factoryFunc(exampleValue){
      exampleProperty: exampleValue 

Constructor Functions are those functions that assign properties to objects using "this" keyword.e.g-

function constructorFunc(exampleValue){
   this.exampleProperty= exampleValue;
const myObj= new constructorFunc(1);

LinearLayout not expanding inside a ScrollView

All the answers here didn't work (completely) for me. Just to recap what we wanna do for a complete answer: We have a ScrollView, supposedly filling the device's viewport, thus we set fillViewport to "true" in the layout xml. Then, inside the ScrollView, we have a LinearLayout containing everything else, and that LinearLayout should be at least as high as its parent ScrollView, so stuff that's supposed to be on the bottom (of the LinearLayout) is actually, as we want it, at the bottom of the screen (or at the bottom of the ScrollView, in case the LinearLayout's content has more hight than the screen.

Example activity_main.xml layout:

...content which might or might not be higher than screen height...

Then, in the activity's onCreate, we "wait" for the LinearLayout's layouting to be done (implying it's parent's layouting is also already done) and then set it's minimum height to the ScrollView's height. Thus it also works in case the ScrollView does not occupy the whole screen height. Whether you call .post(...) on the ScrollView or the inner LinearLayout should not make that much of a difference, if one doesn't work for you, try the other.

public class MainActivity extends AppCompatActivity {

@Override // Activity
protected void onCreate(Bundle savedInstanceState) {

    LinearLayout linearLayoutWrapper = findViewById(;

    ... -> {

Sadly, it's not an xml-only solution, but it works well enough for me, hope it also helps some other tortured android dev scouring the interwebs in search for a solution to this problem ;D

Hide axis values but keep axis tick labels in matplotlib

If you use the matplotlib object-oriented approach, this is a simple task using ax.set_xticklabels() and ax.set_yticklabels():

import matplotlib.pyplot as plt

# Create Figure and Axes instances
fig,ax = plt.subplots(1)

# Make your plot, set your axes labels

# Turn off tick labels

AngularJs: How to check for changes in file input fields?

You can simply add the below code in onchange and it will detect change. you can write a function on X click or something to remove file data..

document.getElementById(id).value = "";

How to check if a file exists from a url

Do a request with curl and see if it returns a 404 status code. Do the request using the HEAD request method so it only returns the headers without a body.

Add inline style using Javascript = '330px'; = 'left';

This should add an inline style to the element.

What are the rules for calling the superclass constructor?

If you have default parameters in your base constructor the base class will be called automatically.

using namespace std;

class Base
    Base(int a=1) : _a(a) {}

    int _a;

class Derived : public Base
  Derived() {}

  void printit() { cout << _a << endl; }

int main()
   Derived d;
   return 0;

Output is: 1

Assigning the return value of new by reference is deprecated

I recently moved a site using SimplePie ( from a server that was using PHP 5.2.17 to one that is using PHP 5.3.2. It was after this move that I began receiving a list of error messages such as this one:

Deprecated: Assigning the return value of new by reference is deprecated in .../php/ on line 738

After reviewing several discussions of this issue, I cleared things up by replacing all the instances of =& new with = new in the file.

I'm not experienced enough to know if this will work in all instances where these error messages are received but it worked in this particular case and it may be worth trying.

Appending to an empty DataFrame in Pandas?

That should work:

>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
0  0
1  1
2  2

But the append doesn't happen in-place, so you'll have to store the output if you want it:

>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
0  0
1  1
2  2

Which language uses .pde extension?

Bad news I'm afraid (or maybe great news?) : it isn't C code, it's an example of "Processing" - an open source language aimed at programming images. Take a look here

Looks very cool.

UITapGestureRecognizer - single tap and double tap

Some view have there own double tap recognizers built in (MKMapView being an example). To get around this you will need to implement UIGestureRecognizerDelegate method shouldRecognizeSimultaneouslyWithGestureRecognizer and return YES:

First implement your double and single recognizers:

// setup gesture recognizers
UITapGestureRecognizer* singleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
singleTapRecognizer.delegate = self;
singleTapRecognizer.numberOfTapsRequired = 1;

UITapGestureRecognizer* doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
doubleTapRecognizer.delegate = self;    // this allows
doubleTapRecognizer.numberOfTapsRequired = 2;
[singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];

And then implement:

#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer
*)otherGestureRecognizer {  return YES; }

How do I install Composer on a shared hosting?

You can do it that way:

  • Create a directory where you want to install composer (let's say /home/your_username/composer)
  • Go to this directory - cd /home/your_username/composer
  • Then run the following command:

    php -r "readfile('');" | php

  • After that if you want to run composer, you can do it this way (in this caseyou must be in the composer's dir): php composer.phar

  • As a next step, you can do this:

    alias composer="/home/your_username/composer/composer.phar".

    And run commands like you do it normally: $ composer install

Hope that helps

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

The spatial functions in PostGIS are much more functional (i.e. not constrained to BBOX operations) than those in the MySQL spatial functions. Check it out: link text

C# LINQ find duplicates in List

Find out if an enumerable contains any duplicate :

var anyDuplicate = enumerable.GroupBy(x => x.Key).Any(g => g.Count() > 1);

Find out if all values in an enumerable are unique :

var allUnique = enumerable.GroupBy(x => x.Key).All(g => g.Count() == 1);

How to reset db in Django? I get a command 'reset' not found error

Similar to LisaD's answer, Django Extensions has a great reset_db command that totally drops everything, instead of just truncating the tables like "flush" does.

python ./ reset_db

Merely flushing the tables wasn't fixing a persistent error that occurred when I was deleting objects. Doing a reset_db fixed the problem.

How to check whether a select box is empty using JQuery/Javascript

One correct way to get selected value would be

var selected_value = $('#fruit_name').val()

And then you should do

if(selected_value) { ... }

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

System.Collections.Generic.Dictionary<TKey, TValue> and System.Collections.Hashtable classes both maintain a hash table data structure internally. None of them guarantee preserving the order of items.

Leaving boxing/unboxing issues aside, most of the time, they should have very similar performance.

The primary structural difference between them is that Dictionary relies on chaining (maintaining a list of items for each hash table bucket) to resolve collisions whereas Hashtable uses rehashing for collision resolution (when a collision occurs, tries another hash function to map the key to a bucket).

There is little benefit to use Hashtable class if you are targeting for .NET Framework 2.0+. It's effectively rendered obsolete by Dictionary<TKey, TValue>.

How do I remove the passphrase for the SSH key without having to create a new key?

On the Mac you can store the passphrase for your private ssh key in your Keychain, which makes the use of it transparent. If you're logged in, it is available, when you are logged out your root user cannot use it. Removing the passphrase is a bad idea because anyone with the file can use it.

ssh-keygen -K

Add this to ~/.ssh/config

UseKeychain yes

get current date from [NSDate date] but set the time to 10:00 am

NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:10];
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];
[comps release];

Not tested in xcode though :)

How to randomize Excel rows

Here's a macro that allows you to shuffle selected cells in a column:

Option Explicit

Sub ShuffleSelectedCells()
  'Do nothing if selecting only one cell
  If Selection.Cells.Count = 1 Then Exit Sub
  'Save selected cells to array
  Dim CellData() As Variant
  CellData = Selection.Value
  'Shuffle the array
  ShuffleArrayInPlace CellData
  'Output array to spreadsheet
  Selection.Value = CellData
End Sub

Sub ShuffleArrayInPlace(InArray() As Variant)
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source:
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
  Dim J As Long, _
    N As Long, _
    Temp As Variant
  For N = LBound(InArray) To UBound(InArray)
    J = CLng(((UBound(InArray) - N) * Rnd) + N)
    If J <> N Then
      Temp = InArray(N, 1)
      InArray(N, 1) = InArray(J, 1)
      InArray(J, 1) = Temp
    End If
  Next N
End Sub

You can read the comments to see what the macro is doing. Here's how to install the macro:

  1. Open the VBA editor (Alt + F11).
  2. Right-click on "ThisWorkbook" under your currently open spreadsheet (listed in parentheses after "VBAProject") and select Insert / Module.
  3. Paste the code above and save the spreadsheet.

Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).

Read/Parse text file line by line in VBA

The below is my code from reading text file to excel file.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Close #1
End Sub

How to copy files from 'assets' folder to sdcard?

Based on Rohith Nandakumar's solution, I did something of my own to copy files from a subfolder of assets (i.e. "assets/MyFolder"). Also, I'm checking if the file already exists in sdcard before trying to copy again.

private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("MyFolder");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    if (files != null) for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in ="MyFolder/"+filename);
          File outFile = new File(getExternalFilesDir(null), filename);
          if (!(outFile.exists())) {// File does not exist...
                out = new FileOutputStream(outFile);
                copyFile(in, out);
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        finally {
            if (in != null) {
                try {
                } catch (IOException e) {
                    // NOOP
            if (out != null) {
                try {
                } catch (IOException e) {
                    // NOOP
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = != -1){
      out.write(buffer, 0, read);

How to import Google Web Font in CSS file?

Add the Below code in your CSS File to import Google Web Fonts.

@import url(;

Replace the Open+Sans parameter value with your Font name.

Your CSS file should look like:

@import url(;

   font-family: 'Open Sans',serif;

An unhandled exception was generated during the execution of the current web request

In my case, I created a new project and when I ran it the first time, it gave me the following error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

So my solution was to go to the Package Manager Console inside the Visual Studio and run:Update-Package

Problem solved!!

Can an Android NFC phone act as an NFC tag?

yes you can. Android kitkat boosts of this functionality here

difference between variables inside and outside of __init__()

I would like to add something to the responses that I read in this thread and this thread (which references this one).

Disclaimer: this remarks come from the experiments I ran

Variables outside __init__:

These are, in fact, static class variables and are, therefore, accesible to all instances of the class.

Variables inside __init__:

The value of these instance variables are only accesible to the instance at hand (through the self reference)

My contribution:

One thing that programmers must consider when using static class variables is that they can be shadowed by instance variables (if you are accessing the static class variables through the self reference).


Previously, I thought that both ways of declaring the variables were exactly the same (silly me), and that was partly because I could access both kind of variables through the self reference. It was now, when I ran into trouble, that I researched the topic and cleared it up.

The problem with accessing static class variables through the self reference is that it only references the static class variable if there is no instance variable with the same name, and to make things worse, trying to redefine a static class variable through the self reference does not work because an instance variable is created which then shadows the previously-accesible static class variable.

To get around this problem, you should always reference static class variables through the name of the class.


#!/usr/bin/env python

class Foo:
    static_var = 'every instance has access'

    def __init__(self,name):
        self.instance_var = 'I am %s' % name

    def printAll(self):
        print 'self.instance_var = %s' % self.instance_var
        print 'self.static_var = %s' % self.static_var
        print 'Foo.static_var = %s' % Foo.static_var

f1 = Foo('f1')


f1.static_var = 'Shadowing static_var'


f2 = Foo('f2')


Foo.static_var = 'modified class'



self.instance_var = I am f1
self.static_var = every instance has access
Foo.static_var = every instance has access
self.instance_var = I am f1
self.static_var = Shadowing static_var
Foo.static_var = every instance has access
self.instance_var = I am f2
self.static_var = every instance has access
Foo.static_var = every instance has access
self.instance_var = I am f1
self.static_var = Shadowing static_var
Foo.static_var = modified class
self.instance_var = I am f2
self.static_var = modified class
Foo.static_var = modified class

I hope this is helpful to someone

oracle SQL how to remove time from date

We can use TRUNC function in Oracle DB. Here is an example.


Output: 1/1/2018

How to find files modified in last x minutes (find -mmin does not work as expected)

I am working through the same need and I believe your timeframe is incorrect.

Try these:

  • 15min change: find . -mtime -.01
  • 1hr change: find . -mtime -.04
  • 12 hr change: find . -mtime -.5

You should be using 24 hours as your base. The number after -mtime should be relative to 24 hours. Thus -.5 is the equivalent of 12 hours, because 12 hours is half of 24 hours.

Add text to Existing PDF using Python

I know this is an older post, but I spent a long time trying to find a solution. I came across a decent one using only ReportLab and PyPDF so I thought I'd share:

  1. read your PDF using PdfFileReader(), we'll call this input
  2. create a new pdf containing your text to add using ReportLab, save this as a string object
  3. read the string object using PdfFileReader(), we'll call this text
  4. create a new PDF object using PdfFileWriter(), we'll call this output
  5. iterate through input and apply .mergePage(*text*.getPage(0)) for each page you want the text added to, then use output.addPage() to add the modified pages to a new document

This works well for simple text additions. See PyPDF's sample for watermarking a document.

Here is some code to answer the question below:

packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=letter)
<do something with canvas>
input = PdfFileReader(packet)

From here you can merge the pages of the input file with another document.

Save attachments to a folder and rename them

This is my Save Attachments script. You select all the messages that you want the attachments saved from, and it will save a copy there. It also adds text to the message body indicating where the attachment is saved. You could easily change the folder name to include the date, but you would need to make sure the folder existed before starting to save files.

Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String

' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next

' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")

' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection

' Set the Attachment folder.
strFolderpath = strFolderpath & "\Attachments\"

' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection

    ' This code only strips attachments from mail items.
    ' If objMsg.class=olMail Then
    ' Get the Attachments collection of the item.
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
    strDeletedFiles = ""

    If lngCount > 0 Then

        ' We need to use a count down loop for removing items
        ' from a collection. Otherwise, the loop counter gets
        ' confused and only every other item is removed.

        For i = lngCount To 1 Step -1

            ' Save attachment before deleting from item.
            ' Get the file name.
            strFile = objAttachments.Item(i).FileName

            ' Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            ' Save the attachment as a file.
            objAttachments.Item(i).SaveAsFile strFile

            ' Delete the attachment.

            'write the save as path to a string to add to the message
            'check for html and use html tags in link
            If objMsg.BodyFormat <> olFormatHTML Then
                strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
                strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
                strFile & "'>" & strFile & "</a>"
            End If

            'Use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        ' Adds the filename string to the message body and save it
        ' Check for HTML body
        If objMsg.BodyFormat <> olFormatHTML Then
            objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
            objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
        End If
    End If


Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

Easiest way to read/write a file's content in Python

Slow, ugly, platform-specific... but one-liner ;-)

import subprocess

contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0]

Stop embedded youtube iframe?

$('#aboutVideo .close').on('click',function(){_x000D_
   var reSrc = $('.aboutPlayer').attr("src");_x000D_
 width: 100%;_x000D_
 height: 100%;_x000D_
#aboutVideo .modal-dialog, #aboutVideo .modal-dialog .modal-content, #aboutVideo .modal-dialog .modal-content .modal-body{_x000D_
 width: 100%;_x000D_
 height: 100%;_x000D_
 margin: 0 !important;_x000D_
 padding: 0 !important;_x000D_
#aboutVideo .modal-header{_x000D_
 padding: 0px; _x000D_
 border-bottom: 0px solid #e5e5e5; _x000D_
 position: absolute;_x000D_
 right: 4%;_x000D_
 top: 4%;_x000D_
#aboutVideo .modal-header .close{_x000D_
 opacity: 1;_x000D_
 position: absolute;_x000D_
 z-index: 99;_x000D_
 color: #fff;_x000D_
#aboutVideo .modal-header button.close{_x000D_
      border-radius: 50%;_x000D_
    width: 7vw;_x000D_
    height: 7vw;_x000D_
    position: absolute;_x000D_
    right: 4%;_x000D_
    top: 7%;_x000D_
    background: aliceblue;_x000D_
#aboutVideo .modal-header button.close:hover{_x000D_
 background-color: rgba(255, 255, 255, 0.28);_x000D_
#aboutVideo .modal-header button.close img{_x000D_
 width: 20px;_x000D_
 margin-top: -0.2vw;_x000D_
<script src=""></script>_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
<li class="see-video fa" type="button" data-toggle="modal" data-target="#aboutVideo">_x000D_
   <label>SEE VIDEO</label>_x000D_
<div class="modal fade" id="aboutVideo" tabindex="-1" role="dialog" aria-labelledby="aboutVideoLabel">_x000D_
  <div class="modal-dialog" role="document">_x000D_
   <div class="modal-content">_x000D_
    <div class="modal-header">_x000D_
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><img src=""></span></button>_x000D_
    <div class="modal-body">_x000D_
    <iframe class="aboutPlayer" width="100%" height="100%" src="" frameborder="0" allowfullscreen poster=""></iframe>_x000D_

How to do a SOAP wsdl web services call from the command line

On linux command line, you can simply execute:

curl -H "Content-Type: text/xml; charset=utf-8" -H "SOAPAction:"  -d @your_soap_request.xml -X POST

How to Pass data from child to parent component Angular

In order to send data from child component create property decorated with output() in child component and in the parent listen to the created event. Emit this event with new values in the payload when ever it needed.

@Output() public eventName:EventEmitter = new EventEmitter();

to emit this event:


How can I disable all views inside the layout?

I like to have a control over the root view so I added the includeSelf flag to deepForEach

fun ViewGroup.deepForEach(includeSelf: Boolean = true, function: View.() -> Unit) {
    if (includeSelf) function()
    forEach {
        it.apply {
            (this as? ViewGroup)?.apply { deepForEach(includeSelf, function) }

Determine Pixel Length of String in Javascript/jQuery?

Based on vSync's answer, the pure javascript method is lightning fast for large amount of objects. Here is the Fiddle:

[1]: "JSFiddle"

I received favorable tests for the 3rd method proposed, that uses the native javascript vs HTML Canvas

Google was pretty competive for option 1 and 3, 2 bombed.

FireFox 48:
Method 1 took 938.895 milliseconds.
Method 2 took 1536.355 milliseconds.
Method 3 took 135.91499999999996 milliseconds.

Edge 11 Method 1 took 4895.262839793865 milliseconds.
Method 2 took 6746.622271896686 milliseconds.
Method 3 took 1020.0315412885484 milliseconds.

Google Chrome: 52
Method 1 took 336.4399999999998 milliseconds.
Method 2 took 2271.71 milliseconds.
Method 3 took 333.30499999999984 milliseconds.

Break when a value changes using the Visual Studio debugger

As Peter Mortensen wrote:

In the Visual Studio 2005 menu:

Debug -> New Breakpoint -> New Data Breakpoint

Enter: &myVariable

Additional information:

Obviously, the system must know which address in memory to watch. So - set a normal breakpoint to the initialisation of myVariable (or myClass.m_Variable) - run the system and wait till it stops at that breakpoint. - Now the Menu entry is enabled, and you can watch the variable by entering &myVariable, or the instance by entering &myClass.m_Variable. Now the addresses are well defined.

Sorry when I did things wrong by explaining an already given solution. But I could not add a comment, and there has been some comments regarding this.

How do I convert from a string to an integer in Visual Basic?

You can use the following to convert string to int:

  • CInt(String) for ints
  • CDec(String) for decimals

For details refer to Type Conversion Functions (Visual Basic).

Changing image sizes proportionally using CSS?

transform: scale(0.5);


<div class="scaled">Scaled</div>
div {
  width: 80px;
  height: 80px;
  background-color: skyblue;

.scaled {
  transform: scale(0.7); /* Equal to scaleX(0.7) scaleY(0.7) */
  background-color: pink;


.Net: How do I find the .NET version?

Here is the Power Shell script which I used by taking the reference of:

$Lookup = @{
    378389 = [version]'4.5'
    378675 = [version]'4.5.1'
    378758 = [version]'4.5.1'
    379893 = [version]'4.5.2'
    393295 = [version]'4.6'
    393297 = [version]'4.6'
    394254 = [version]'4.6.1'
    394271 = [version]'4.6.1'
    394802 = [version]'4.6.2'
    394806 = [version]'4.6.2'
    460798 = [version]'4.7'
    460805 = [version]'4.7'
    461308 = [version]'4.7.1'
    461310 = [version]'4.7.1'
    461808 = [version]'4.7.2'
    461814 = [version]'4.7.2'
    528040 = [version]'4.8'
    528049 = [version]'4.8'

# For One True framework (latest .NET 4x), change the Where-Oject match 
# to PSChildName -eq "Full":
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
  Get-ItemProperty -name Version, Release -EA 0 |
  Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
  Select-Object @{name = ".NET Framework"; expression = {$_.PSChildName}}, 
@{name = "Product"; expression = {$Lookup[$_.Release]}}, 
Version, Release

The above script makes use of the registry and gives us the Windows update number along with .Net Framework installed on a machine.


Here are the results for the same when running that script on two different machines

  1. Where .NET 4.7.2 was already installed:

enter image description here

  1. Where .NET 4.7.2 was not installed:

enter image description here

How can I make a clickable link in an NSAttributedString?

The quick answer is using UITextView instead of UILabel. You need to enable Selectable and disable Editable.

Then disable scroll indicators and bounces.

Screen Shot

Screen Shot

My solution using NSMutableAttributedString from html string NSHTMLTextDocumentType

NSString *s = @"<p><a href=''></a></p>";

NSMutableAttributedString *text = [[NSMutableAttributedString alloc]
                                           initWithData: [s dataUsingEncoding:NSUnicodeStringEncoding]
                                           options: @{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                           documentAttributes: nil
                                           error: nil

cell.content.attributedText = text;

Install a module using pip for specific python version

Alternatively, since pip itself is written in python, you can just call it with the python version you want to install the package for:

python2.7 -m pip install foo

How can I pass data from Flask to JavaScript in a template?

Some js files come from the web or library, they are not written by yourself. The code they get variable like this:

var queryString =;
var params = PDFViewerApplication.parseQueryString(queryString);
var file = 'file' in params ? params.file : DEFAULT_URL;

This method makes js files unchanged(keep independence), and pass variable correctly!

Excel - Sum column if condition is met by checking other column in same table

This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.

For example, if the Months are in cells A2:A100 and the amounts are in cells B2:B100, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}. You don't actually type the curly-braces though.

You could also do something like =SUM((A2:A100="January")*B2:B100). You'd still need to use the trick to get it to work correctly.

Ubuntu says "bash: ./program Permission denied"

Sounds like you don't have the execute flag set on the file permissions, try:

chmod u+x program_name

Execute stored procedure with an Output parameter?



How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
   public static void main(String arg[])
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(;
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
       System.out.println("The total is :"+total);

How to change the blue highlight color of a UITableViewCell?

Swift 3.0/4.0

If you have created your own custom cell you can change the selection color on awakeFromNib() for all of the cells:

 override func awakeFromNib() {

    let colorView = UIView()
    colorView.backgroundColor =

    self.selectedBackgroundView = colorView


How to insert strings containing slashes with sed?

add \ before special characters:



java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

You might have not copied the MySQL connector/J jar file into the lib folder and then this file has to be there in the classpath.

If you have not done so, please let me know I shall elaborate the answer

Change the default editor for files opened in the terminal? (e.g. set it to TextEdit/Coda/Textmate)

Use git config --global core.editor mate -w or git config --global core.editor open as @dmckee suggests in the comments.


How to install an npm package from GitHub directly?

The general form of the syntax is

<protocol>://[<user>[:<password>]@]<hostname>[:<port>][:][/]<path>[#<commit-ish> | #semver:<semver>]

which means for your case it will be

npm install git+ssh://[email protected]/visionmedia/express.git

From npmjs docs:

npm install :

Installs the package from the hosted git provider, cloning it with git. For a full git remote url, only that URL will be attempted.


| #semver:] is one of git, git+ssh, git+http, git+https, or git+file.

If # is provided, it will be used to clone exactly that commit. If the commit-ish has the format #semver:, can be any valid semver range or exact version, and npm will look for any tags or refs matching that range in the remote repository, much as it would for a registry dependency. If neither # or

semver: is specified, then master is used.

If the repository makes use of submodules, those submodules will be cloned as well.

If the package being installed contains a prepare script, its dependencies and devDependencies will be installed, and the prepare script will be run, before the package is packaged and installed.

The following git environment variables are recognized by npm and will be added to the environment when running git:


See the git man page for details.


npm install git+ssh://[email protected]:npm/npm.git#v1.0.27
npm install git+ssh://[email protected]:npm/npm#semver:^5.0
npm install git+https://[email protected]/npm/npm.git
npm install git://
GIT_SSH_COMMAND='ssh -i ~/.ssh/custom_ident' npm install git+ssh://[email protected]:npm/npm.git npm install

Installing pip packages to $HOME folder

While you can use a virtualenv, you don't need to. The trick is passing the PEP370 --user argument to the script. With the latest version of pip, one way to do it is:

pip install --user mercurial

This should result in the hg script being installed in $HOME/.local/bin/hg and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/.

Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local to $HOME/Library/Python. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg and $HOME/Library/Python/x.y/lib/python/site-packages.

How to make MySQL table primary key auto increment with some prefix

Here is PostgreSQL example without trigger if someone need it on PostgreSQL:

CREATE SEQUENCE messages_seq;

    id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
    name CHAR(30) NOT NULL,


How to get back to the latest commit after checking out a previous commit?

You can use one of the following git command for this:

git checkout master
git checkout branchname

How to include duplicate keys in HashMap?

Use Map<Integer, List<String>>:

Map<Integer, List<String>> map = new LinkedHashMap< Integer, List<String>>();

map.put(-1505711364, new ArrayList<>(Arrays.asList("4")));
map.put(294357273, new ArrayList<>(Arrays.asList("15", "71")));

To add a new key/value pair in this map:

public void add(Integer key, String newValue) {
    List<String> currentValue = map.get(key);
    if (currentValue == null) {
        currentValue = new ArrayList<String>();
        map.put(key, currentValue);

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->


all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

How to get only filenames within a directory using c#?

You can simply use linq

Directory.EnumerateFiles(LoanFolder).Select(file => Path.GetFileName(file));

Note: EnumeratesFiles is more efficient compared to Directory.GetFiles as you can start enumerating the collection of names before the whole collection is returned.

make: Nothing to be done for `all'

I think you missed a tab in 9th line. The line following all:hello must be a blank tab. Make sure that you have a blank tab in 9th line. It will make the interpreter understand that you want to use default recipe for makefile.

How to echo with different colors in the Windows command line

There is an accepted answer with more than 250 upvotes already. The reason I am still contributing is that the escape character required for echoing is not accepted by many editors (I am using, e.g., MS Code) and all other solutions require some third-party (non-Windows-default) pieces of software.

The work-around with using only plain batch commands is using PROMPT instead of ECHO. The PROMPT command accepts the escape character in an any-editor-friendly way as a $Echaracter sequence. (Simply replace the Esc in the ASCII Escape codes) with $E.

Here is a demo code:


    :: Do not pollute environment with the %prompt.bak% variable
    :: ! forgetting ENDLOCAL at the end of the batch leads to prompt corruption

    :: Old prompt settings backup
    SET prompt.bak=%PROMPT%

    :: Entering the "ECHO"-like section

        :: Forcing prompt to display after every command (see below)
        ECHO ON

        :: Setting the prompt using the ANSI Escape sequence(s)
        :: - Always start with $E[1A, otherwise the text would appear on a next line
        :: - Then the decorated text follows
        :: - And it all ends with $E30;40m, which makes the following command invisible
        ::   - assuming default background color of the screen
        @ PROMPT $E[1A$E[30;42mHELLO$E[30;40m

        :: An "empty" command that forces the prompt to display. 
        :: The word "rem" is displayed along with the prompt text but is made invisible

        :: Just another text to display
        @ PROMPT $E[1A$E[33;41mWORLD$E[30;40m

        :: Leaving the "ECHO"-like section
        @ECHO OFF

    :: Or a more readable version utilizing the cursor manipulation ASCII ESC sequences

        :: the initial sequence
        PROMPT $E[1A
        :: formating commands
        PROMPT %PROMPT%$E[32;44m
        :: the text
        PROMPT %PROMPT%This is an "ECHO"ed text...
        :: new line; 2000 is to move to the left "a lot"
        PROMPT %PROMPT%$E[1B$E[2000D
        :: formating commands fro the next line
        PROMPT %PROMPT%$E[33;47m
        :: the text (new line)
        PROMPT %PROMPT%...spreading over two lines
        :: the closing sequence
        PROMPT %PROMPT%$E[30;40m

        :: Looks like this without the intermediate comments:
        :: PROMPT $E[1A
        :: PROMPT %PROMPT%$E[32;44m
        :: PROMPT %PROMPT%This is an "ECHO"ed text...
        :: PROMPT %PROMPT%$E[1B$E[2000D
        :: PROMPT %PROMPT%$E[33;47m
        :: PROMPT %PROMPT%...spreading over two lines
        :: PROMPT %PROMPT%$E[30;40m

        :: show it all at once!
        ECHO ON
        @ECHO OFF

    :: End of "ECHO"-ing

    :: Setting prompt back to its original value
    :: - We prepend the settings with $E[37;40m in case
    ::   the original prompt settings do not specify color
    ::   (as they don't by default).
    :: - If they do, the $E[37;40m will become overridden, anyway.
    :: ! It is important to write this command 
    ::   as it is with `ENDLOCAL` and in the `&` form.
    ENDLOCAL & PROMPT $E[37;40m%prompt.bak%


NOTE: The only drawback is that this technique collides with user cmd color settings (color command or settings) if not known explicitly.

-- Hope this helps as thi is the only solution acceptable for me for the reasons mentioned at the beginning. --


Based on comments, I am enclosing another snippet inspired by @Jeb. It:

  • Shows how to obtain and use the "Esc" character runtime (rather than entering it to an editor) (Jeb's solution)
  • Uses "native" ECHO command(s)
  • So it does not affect local PROMPT value
  • Demonstrates that coloring the ECHO output inevitably affect PROMPT color so the color must be reset, anyway

    :: ! To observe color effects on prompt below in this script
    ::   run the script from a fresh cmd window with no custom
    ::   prompt settings

    :: Only not to pollute the environment with the %\e% variable (see below)
    :: Not needed because of the `PROMPT` variable

        :: Parsing the `escape` character (ASCII 27) to a %\e% variable
        :: Use %\e% in place of `Esc` in the []
        FOR /F "delims=#" %%E IN ('"prompt #$E# & FOR %%E IN (1) DO rem"') DO SET "\e=%%E"

        :: Demonstrate that prompt did not get corrupted by the previous FOR
        ECHO ON
        rem : After for
        @ECHO OFF

        :: Some fancy ASCII ESC staff
        ECHO [          ]
        FOR /L %%G IN (1,1,10) DO (
            TIMEOUT /T 1 > NUL
            ECHO %\e%[1A%\e%[%%GC%\e%[31;43m.
            ECHO %\e%[1A%\e%[11C%\e%[37;40m]

        :: ECHO another decorated text
        :: - notice the `%\e%[30C` cursor positioning sequence
        ::   for the sake of the "After ECHO" test below
        ECHO %\e%[1A%\e%[13C%\e%[32;47mHELLO WORLD%\e%[30C

        :: Demonstrate that prompt did not get corrupted by ECHOing
        :: neither does the cursor positioning take effect.
        :: ! But the color settings do.
        ECHO ON
        rem : After ECHO
        @ECHO OFF


    :: Demonstrate that color settings do not reset
    :: even when out of the SETLOCAL scope
    rem : After ENDLOCAL

    :: Reset the `PROMPT` color
    :: - `PROMPT` itself is untouched so we did not need to backup it.
    :: - Still ECHOING in color apparently collide with user color cmd settings (if any).
    :: ! Resetting `PROMPT` color this way extends the `PROMPT`
    ::   by the initial `$E[37;40m` sequence every time the script runs.
    :: - Better solution then would be to end every (or last) `ECHO` command
    ::   with the `%\e%[37;40m` sequence and avoid setting `PROMPT` altogether.
    ::   which makes this technique preferable to the previous one (before EDIT)
    :: - I am keeping it this way only to be able to
    ::   demonstrate the `ECHO` color effects on the `PROMPT` above.
    PROMPT $E[37;40m%PROMPT%

    rem : After PROMPT color reset


Apache POI error loading XSSFWorkbook class

commons-collections4-x.x.jar definitely solve this problem but Apache has removed the Interface ListValuedMap from commons-Collections4-4.0.jar so use updated version 4.1 it has the required classes and Interfaces.

Refer here if you want to read Excel (2003 or 2007+) using java code.

Handling NULL values in Hive

Try using isnull(a), isnotnull(a), nvl(), etc. On some versions(potentially in conjunction with the server settings - atleast with the one I am working on) of hive the 'IS NULL' and 'IS NOT NULL' syntax does not execute the logic when it is compiled. Check here for more information.

how to loop through each row of dataFrame in pyspark


tupleList = [{name:x["name"], age:x["age"], city:x["city"]} 

should be

tupleList = [{'name':x["name"], 'age':x["age"], 'city':x["city"]} 

for name, age, and city are not variables but simply keys of the dictionary.

How to run docker-compose up -d at system start up?

Use restart: always in your docker compose file.

Docker-compose up -d will launch container from images again. Use docker-compose start to start the stopped containers, it never launches new containers from images.

    restart: always   
    image: nginx   
      - "80:80"
      - "443:443"   links:
      - other_container:other_container

Also you can write the code up in the docker file so that it gets created first, if it has the dependency of other containers.

How to fix Subversion lock error

Just Right Click on Project

  1. Click on Team

  2. Click Refresh/Cleaup

this will remove all the current lock files created by SVN

hope this will help !!!!

How to set the value for Radio Buttons When edit?

For those who might be in need for a solution in pug template engine and NodeJs back-end, you can use this:

If values are not boolean(IE: true or false), code below works fine:

input(type='radio' name='sex' value='male' checked=( ==='male') || ( === 'newvalue') )
input(type='radio' name='sex' value='female' checked=( ==='female) || ( === 'newvalue'))

If values are boolean(ie: true or false), use this instead:

input(type='radio' name='isInsurable' value='true' checked=singleModel.isInsurable || (singleModel.isInsurable === 'true') )
input(type='radio' name='isInsurable' value='false' checked=!singleModel.isInsurable || (singleModel.isInsurable === 'false'))

the reason for this || operator is to re-display new values if editing fails due to validation error and you have a logic to send back the new values to your front-end

The executable gets signed with invalid entitlements in Xcode

I had the same problem in XCode 5. This helped me anyway.

XCode > Preferences > Location tab > DerivedData

Press a little left arrow to open DerivedData in Finder. Move to trash folder of your project and rebuild.


Calling one Bash script from another Script passing it arguments with quotes and spaces

I found following program works for me 
a=xxx $a

in you use $1 to refer variable a in

echo $1

The output would be xxx

Spring MVC Missing URI template variable

This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.

Example: Suppose you defined in the REST definition

@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")

Then during the definition of the function, it should be

public ResponseEntity<List> getData(@PathVariable String appId)

This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:

public ResponseEntity<List> getData(@PathVariable String ID)

Fully custom validation error message with Rails

In the custom validation method use:

errors.add(:base, "Custom error message")

as add_to_base has been deprecated.

errors.add_to_base("Custom error message")

SQLAlchemy create_all() does not create tables

If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:

Root     <-- file from which app will be run
--models      <-- file with "User" model    <-- file with "Order" model <-- file with database and "create_all" function declaration

Be careful about calling the "create_all" function from

This concept is explained better by the answer to this thread posted by @SuperShoot

Bootstrap 3 .col-xs-offset-* doesn't work?


  Include this after bootstrap.css

  Add a class of 'col-xs-offset-*' and 
  if you want to disable the offset at a larger size add in 'col-*-offset-0'

  All display sizes (xs,sm,md,lg) have an offset of 1
  <div class="col-xs-11 col-xs-offset-1 col-sm-3">

  xs has an offset of 1
  <div class="col-xs-11 col-xs-offset-1 col-sm-offset-0 col-sm-3">

  xs and sm have an offset of 1
  <div class="col-xs-11 col-xs-offset-1 col-md-offset-0 col-sm-3">

  xs, sm and md will have an offset of 1
  <div class="col-xs-11 col-xs-offset-1 col-lg-offset-0 col-sm-3">


.col-xs-offset-12 {
    margin-left: 100%;
.col-xs-offset-11 {
    margin-left: 91.66666666666666%;
.col-xs-offset-10 {
    margin-left: 83.33333333333334%;
.col-xs-offset-9 {
    margin-left: 75%;
.col-xs-offset-8 {
    margin-left: 66.66666666666666%;
.col-xs-offset-7 {
    margin-left: 58.333333333333336%;
.col-xs-offset-6 {
    margin-left: 50%;
.col-xs-offset-5 {
    margin-left: 41.66666666666667%;
.col-xs-offset-4 {
    margin-left: 33.33333333333333%;
.col-xs-offset-3 {
    margin-left: 25%;
.col-xs-offset-2 {
    margin-left: 16.666666666666664%;
.col-xs-offset-1 {
    margin-left: 8.333333333333332%;
.col-xs-offset-0 {
    margin-left: 0;

/* Ensure that all of the zero offsets are available - recent SASS version did not include .col-sm-offset-0 */
@media (min-width: 768px) {
    .col-lg-offset-0 {
        margin-left: 0;

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

I solved the problem by changing the StartupType of the ssh-agent to Manual via Set-Service ssh-agent -StartupType Manual.

Then I was able to start the service via Start-Service ssh-agent or just ssh-agent.exe.

jQuery callback for multiple ajax calls

It's worth noting that since $.when expects all of the ajax requests as sequential arguments (not an array) you'll commonly see $.when used with .apply() like so:

// Save all requests in an array of jqXHR objects
var requests = {
    return $.ajax({
        method: 'GET',
        url: 'thing/' +

$.when.apply(this, requests).then(function(resp1, resp2/*, ... */) {
    // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
    var responseArgsArray =, arguments);


Using the Spread syntax, you can now write this code like so:

$.when(...requests).then((...responses) => {
    // do something with responses

This is because $.when accepts args like this

$.when(ajaxRequest1, ajaxRequest2, ajaxRequest3);

And not like this:

$.when([ajaxRequest1, ajaxRequest2, ajaxRequest3]);

Pass react component as props

Using this.props.children is the idiomatic way to pass instantiated components to a react component

const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>

When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div or span):

const Label = props => <span>{props.children}</span>
const Button = props => {
    const Inner = props.inner; // Note: variable name _must_ start with a capital letter 
    return <button><Inner>Foo</Inner></button>
const Page = () => <Button inner={Label}/>

If what you want to do is to pass a children-like parameter as a prop, you can do that:

const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />

After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.

How to make Twitter bootstrap modal full screen

The following class will make a full-screen modal in Bootstrap:

.full-screen {
    width: 100%;
    height: 100%;
    margin: 0;
    top: 0;
    left: 0;

I'm not sure how the inner content of your modal is structured, this may have an effect on the overall height depending on the CSS that is associated with it.

Render HTML in React Native

I found this component.

This component takes HTML content and renders it as native views, with customisable style and handling of links, etc.

Browser detection

    private void BindDataBInfo()
        System.Web.HttpBrowserCapabilities browser = Request.Browser;
        Literal1.Text = "<table border=\"1\" cellspacing=\"3\" cellpadding=\"2\">";
        foreach (string key in browser.Capabilities.Keys)
            Literal1.Text += "<tr><td>" + key + "</td><td>" + browser[key] + "</tr>";
        Literal1.Text += "</table>";
        browser = null;

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.

How to change package name in android studio?

It can be done very easily in one step. You don't have to touch AndroidManifest. Instead do the following:

  1. right click on the root folder of your project.
  2. Click "Open Module Setting".
  3. Go to the Flavours tab.
  4. Change the applicationID to whatever package name you want. Press OK.

Add image in pdf using jspdf

The above code not worked for me. I found new solution :

 var pdf = new jsPDF();
 var img = new Image;
 img.onload = function() {
     pdf.addImage(this, 10, 10);"test.pdf");
 img.crossOrigin = "";  
 img.src = "assets/images/logo.png";

Preventing multiple clicks on button

Disable pointer events in the first line of your callback, and then resume them on the last line.

element.on('click', function() {
  element.css('pointer-events', 'none'); 
  //do all of your stuff
  element.css('pointer-events', 'auto');   

Javascript Click on Element by Class

If you want to click on all elements selected by some class, you can use this example (used on on the Loved tracks page to Unlove all).

var divs = document.querySelectorAll(''); 

for (i = 0; i < divs.length; ++i) {

With ES6 and Babel (cannot be run in the browser console directly)

   .forEach(div => {; })

Can I pass column name as input parameter in SQL stored Procedure

First Run;

CREATE PROCEDURE sp_First @columnname NVARCHAR(128)--128 = SQL Server Maximum Column Name Length


    SET @query = 'SELECT ' + @columnname + ' FROM Table_1'



Second Run;

EXEC sp_First 'COLUMN_Name'

How to convert POJO to JSON and vice versa?

Use GSON for converting POJO to JSONObject. Refer here.

For converting JSONObject to POJO, just call the setter method in the POJO and assign the values directly from the JSONObject.

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

IIS was the main offender for me. My IIS was running and it restrains any new socket connections from opening. The problem resolved for me by stopping IIS by running the command "iisreset -stop"

Failed to load ApplicationContext from Unit Test: FileNotFound

I faced the same error and realized that pom.xml had java 1.7 and STS compiler pointed to Java 1.8. Upon changing compiler to 1.7 and rebuild fixed the issue.

PS: This answer is not related to actual question posted but applies to similar error for app Context not loading

Conversion failed when converting the nvarchar value ... to data type int

I use the latest version of SSMS or sql server management studio. I have a SQL script (in query editor) which has about 100 lines of code. This is error I got in the query:

Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the nvarchar value 'abcd' to data type int.

Solution - I had seen this kind of error before when I forgot to enclose a number (in varchar column) in single quotes.

As an aside, the error message is misleading. The actual error on line number 70 in the query editor and not line 2 as the error says!

Terminating a Java Program

Calling System.exit(0) (or any other value for that matter) causes the Java virtual machine to exit, terminating the current process. The parameter you pass will be the return value that the java process will return to the operating system. You can make this call from anywhere in your program - and the result will always be the same - JVM terminates. As this is simply calling a static method in System class, the compiler does not know what it will do - and hence does not complain about unreachable code.

return statement simply aborts execution of the current method. It literally means return the control to the calling method. If the method is declared as void (as in your example), then you do not need to specify a value, as you'd need to return void. If the method is declared to return a particular type, then you must specify the value to return - and this value must be of the specified type.

return would cause the program to exit only if it's inside the main method of the main class being execute. If you try to put code after it, the compiler will complain about unreachable code, for example:

public static void main(String... str) {

will not compile with most compiler - producing unreachable code error pointing to the second System.out.println call.

SQL Server equivalent to MySQL enum data type?

The best solution I've found in this is to create a lookup table with the possible values as a primary key, and create a foreign key to the lookup table.

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

I have the same error only on the production build. In development was all right, no warning.

The problem was a comment line


return ( // comment


// comment
return (

Add new attribute (element) to JSON object using JavaScript

You can also dynamically add attributes with variables directly in an object literal.

const amountAttribute = 'amount';
const foo = {
                [amountAttribute]: 1
foo[amountAttribute + "__more"] = 2;

Results in:

    amount: 1, 
    amount__more: 2

Node.js for() loop returning the same values at each loop

I would suggest doing this in a more functional style :P

function CreateMessageboard(BoardMessages) {
  var htmlMessageboardString = BoardMessages
   .map(function(BoardMessage) {
     return MessageToHTMLString(BoardMessage);

Try this

How exactly does __attribute__((constructor)) work?

This page provides great understanding about the constructor and destructor attribute implementation and the sections within within ELF that allow them to work. After digesting the information provided here, I compiled a bit of additional information and (borrowing the section example from Michael Ambrus above) created an example to illustrate the concepts and help my learning. Those results are provided below along with the example source.

As explained in this thread, the constructor and destructor attributes create entries in the .ctors and .dtors section of the object file. You can place references to functions in either section in one of three ways. (1) using either the section attribute; (2) constructor and destructor attributes or (3) with an inline-assembly call (as referenced the link in Ambrus' answer).

The use of constructor and destructor attributes allow you to additionally assign a priority to the constructor/destructor to control its order of execution before main() is called or after it returns. The lower the priority value given, the higher the execution priority (lower priorities execute before higher priorities before main() -- and subsequent to higher priorities after main() ). The priority values you give must be greater than100 as the compiler reserves priority values between 0-100 for implementation. Aconstructor or destructor specified with priority executes before a constructor or destructor specified without priority.

With the 'section' attribute or with inline-assembly, you can also place function references in the .init and .fini ELF code section that will execute before any constructor and after any destructor, respectively. Any functions called by the function reference placed in the .init section, will execute before the function reference itself (as usual).

I have tried to illustrate each of those in the example below:

#include <stdio.h>
#include <stdlib.h>

/*  test function utilizing attribute 'section' ".ctors"/".dtors"
    to create constuctors/destructors without assigned priority.
    (provided by Michael Ambrus in earlier answer)

#define SECTION( S ) __attribute__ ((section ( S )))

void test (void) {
printf("\n\ttest() utilizing -- (.section .ctors/.dtors) w/o priority\n");

void (*funcptr1)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;

/*  functions constructX, destructX use attributes 'constructor' and
    'destructor' to create prioritized entries in the .ctors, .dtors
    ELF sections, respectively.

    NOTE: priorities 0-100 are reserved
void construct1 () __attribute__ ((constructor (101)));
void construct2 () __attribute__ ((constructor (102)));
void destruct1 () __attribute__ ((destructor (101)));
void destruct2 () __attribute__ ((destructor (102)));

/*  init_some_function() - called by elf_init()
int init_some_function () {
    printf ("\n  init_some_function() called by elf_init()\n");
    return 1;

/*  elf_init uses inline-assembly to place itself in the ELF .init section.
int elf_init (void)
    __asm__ (".section .init \n call elf_init \n .section .text\n");

    if(!init_some_function ())
        exit (1);

    printf ("\n    elf_init() -- (.section .init)\n");

    return 1;

    function definitions for constructX and destructX
void construct1 () {
    printf ("\n      construct1() constructor -- (.section .ctors) priority 101\n");

void construct2 () {
    printf ("\n      construct2() constructor -- (.section .ctors) priority 102\n");

void destruct1 () {
    printf ("\n      destruct1() destructor -- (.section .dtors) priority 101\n\n");

void destruct2 () {
    printf ("\n      destruct2() destructor -- (.section .dtors) priority 102\n");

/* main makes no function call to any of the functions declared above
main (int argc, char *argv[]) {

    printf ("\n\t  [ main body of program ]\n");

    return 0;


init_some_function() called by elf_init()

    elf_init() -- (.section .init)

    construct1() constructor -- (.section .ctors) priority 101

    construct2() constructor -- (.section .ctors) priority 102

        test() utilizing -- (.section .ctors/.dtors) w/o priority

        test() utilizing -- (.section .ctors/.dtors) w/o priority

        [ main body of program ]

        test() utilizing -- (.section .ctors/.dtors) w/o priority

    destruct2() destructor -- (.section .dtors) priority 102

    destruct1() destructor -- (.section .dtors) priority 101

The example helped cement the constructor/destructor behavior, hopefully it will be useful to others as well.

Curl error: Operation timed out

Your curl gets timed out. Probably the url you are trying that requires more that 30 seconds.

If you are running the script through browser, then set the set_time_limit to zero for infinite seconds.


Increase the curl's operation time limit using this option CURLOPT_TIMEOUT

curl_setopt($ch, CURLOPT_TIMEOUT,500); // 500 seconds

It can also happen for infinite redirection from the server. To halt this try to run the script with follow location disabled.

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

Why aren't python nested functions called closures?

def nested1(num1): 
    print "nested1 has",num1
    def nested2(num2):
        print "nested2 has",num2,"and it can reach to",num1
        return num1+num2    #num1 referenced for reading here
    return nested2


In [17]: my_func=nested1(8)
nested1 has 8

In [21]: my_func(5)
nested2 has 5 and it can reach to 8
Out[21]: 13

This is an example of what a closure is and how it can be used.

Append data to a POST NSURLRequest

 NSURL *url= [NSURL URLWithString:@""];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
[request setHTTPMethod:@"POST"];
 NSString *postString = @"userId=2323";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

Nested jQuery.each() - continue/break

Confirm in API documentation say:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

and this is my example

        var i=0,
             if($('#mytext').val()=='continue')return true;
                 return false;
        alert('Iterazione : '+i+' to '+all);

How to Git stash pop specific stash in 1.8.3?

On Windows Powershell I run this:

git stash apply "stash@{1}"

Javascript Regexp dynamic generation from variables?

You have to use RegExp:

str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));

When I'm concatenating strings, all slashes are gone.

If you have a backslash in your pattern to escape a special regex character, (like \(), you have to use two backslashes in the string (because \ is the escape character in a string): new RegExp('\\(') would be the same as /\(/.

So your patterns have to become:

var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';

Python Pandas Replacing Header with Top Row

The dataframe can be changed by just doing

df.columns = df.iloc[0]
df = df[1:]


df.to_csv(path, index=False) 

Should do the trick.

How to download an entire directory and subdirectories using wget?

You can use this in a shell:

wget -r -nH --cut-dirs=7 --reject="index.html*" \

The Parameters are:

-r recursively download

-nH (--no-host-directories) cuts out hostname 

--cut-dirs=X (cuts out X directories)

Warning: mysqli_real_escape_string() expects exactly 2 parameters, 1 given... what I do wrong?

There is slight change in mysql_real_escape_string mysqli_real_escape_string. below syntax

mysql_real_escape_string syntax will be mysql_real_escape_string($_POST['sample_var'])

mysqli_real_escape_string syntax will be mysqli_real_escape_string($conn,$_POST['sample_var'])

What are Java command line options to set to allow JVM to be remotely debugged?

I have this article bookmarked on setting this up for Java 5 and below.

Basically run it with:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044

For Java 5 and above, run it with:


How to create a TextArea in Android

Defining an Android Mulitline EditText Field is done via the inputType=”textMultiline”. Unfortunately the text looks strangely aligned. To solve that also use the gravity=”left|top” attribute.

   android:inputType="textMultiLine" >

   <requestFocus />

check this vogella blog

Can lambda functions be templated?

In C++20 this is possible using the following syntax:

auto lambda = []<typename T>(T t){
    // do something

What is a regular expression for a MAC Address?

to match both 48-bit EUI-48 and 64-bit EUI-64 MAC addresses:


where \h is a character in [0-9a-fA-F]



this allows '-' or ':' or no separator to be used

What's the difference between subprocess Popen and call (how can I use them)?

The other answer is very complete, but here is a rule of thumb:

  • call is blocking:

    print('hello')  # only executed when notepad is closed
  • Popen is non-blocking:

    print('hello')  # immediately executed

A process crashed in windows .. Crash dump location

a core dump is usually only made when the Windows kernel crashes (aka blue screen). A servicecrash will most of the times only leave some logging behind (in the event viewer probably).

If it is the bluescreen crash dump you are looking for, look in C:\Windows\Minidump or C:\windows\MEMORY.DMP

How do I get bit-by-bit data from an integer value in C?

Here's a very simple way to do it;

int main()
    int s=7,l=1;
    vector <bool> v;
    while (l <= 4)
        s /= 2;
    for (l=(v.size()-1); l >= 0; l--)
        cout<<v[l]<<" ";
    return 0;

Most efficient way to see if an ArrayList contains an object in Java

I would say the simplest solution would be to wrap the object and delegate the contains call to a collection of the wrapped class. This is similar to the comparator but doesn't force you to sort the resulting collection, you can simply use ArrayList.contains().

public class Widget {
        private String name;
        private String desc;

        public String getName() {
            return name;

        public void setName(String name) {
   = name;

        public String getDesc() {
            return desc;

        public void setDesc(String desc) {
            this.desc = desc;

    public abstract class EqualsHashcodeEnforcer<T> {

        protected T wrapped;

        public T getWrappedObject() {
            return wrapped;

        public boolean equals(Object obj) {
            return equalsDelegate(obj);

        public int hashCode() {
            return hashCodeDelegate();

        protected abstract boolean equalsDelegate(Object obj);

        protected abstract int hashCodeDelegate();

    public class WrappedWidget extends EqualsHashcodeEnforcer<Widget> {

        protected boolean equalsDelegate(Object obj) {
            if (obj == null) {
                return false;
            if (obj == getWrappedObject()) {
                return true;
            if (obj.getClass() != getWrappedObject().getClass()) {
                return false;
            Widget rhs = (Widget) obj;

            return new EqualsBuilder().append(getWrappedObject().getName(),

        protected int hashCodeDelegate() {

            return new HashCodeBuilder(121, 991).append(


Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)


data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

Merge PDF files

You can use PyPdf2s PdfMerger class.

File Concatenation

You can simply concatenate files by using the append method.

from PyPDF2 import PdfFileMerger

pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf']

merger = PdfFileMerger()

for pdf in pdfs:


You can pass file handles instead file paths if you want.

File Merging

If you want more fine grained control of merging there is a merge method of the PdfMerger, which allows you to specify an insertion point in the output file, meaning you can insert the pages anywhere in the file. The append method can be thought of as a merge where the insertion point is the end of the file.


merger.merge(2, pdf)

Here we insert the whole pdf into the output but at page 2.

Page Ranges

If you wish to control which pages are appended from a particular file, you can use the pages keyword argument of append and merge, passing a tuple in the form (start, stop[, step]) (like the regular range function).


merger.append(pdf, pages=(0, 3))    # first 3 pages
merger.append(pdf, pages=(0, 6, 2)) # pages 1,3, 5

If you specify an invalid range you will get an IndexError.

Note: also that to avoid files being left open, the PdfFileMergers close method should be called when the merged file has been written. This ensures all files are closed (input and output) in a timely manner. It's a shame that PdfFileMerger isn't implemented as a context manager, so we can use the with keyword, avoid the explicit close call and get some easy exception safety.

You might also want to look at the pdfcat script provided as part of pypdf2. You can potentially avoid the need to write code altogether.

The PyPdf2 github also includes some example code demonstrating merging.

In C#, should I use string.Empty or String.Empty or "" to intitialize a string?

I use the third, but of the other two the first seems less odd. string is an alias for String, but seeing them across an assignment feels off.

Xcode Product -> Archive disabled

Select active scheme to Generic iOs Device.

select to Generic iOs Device

Conversion hex string into ascii in bash command line

Make a script like this:


echo $((0x$1)).$((0x$2)).$((0x$3)).$((0x$4))


sh c0 a8 00 0b


The differences between initialize, define, declare a variable

For C, at least, per C11 6.7.5:

A declaration specifies the interpretation and attributes of a set of identifiers. A definition of an identifier is a declaration for that identifier that:

  • for an object, causes storage to be reserved for that object;

  • for a function, includes the function body;

  • for an enumeration constant, is the (only) declaration of the identifier;

  • for a typedef name, is the first (or only) declaration of the identifier.

Per C11

An initializer specifies the initial value stored in an object ... if an object that has automatic storage is not initialized explicitly, its value is indeterminate.

So, broadly speaking, a declaration introduces an identifier and provides information about it. For a variable, a definition is a declaration which allocates storage for that variable.

Initialization is the specification of the initial value to be stored in an object, which is not necessarily the same as the first time you explicitly assign a value to it. A variable has a value when you define it, whether or not you explicitly give it a value. If you don't explicitly give it a value, and the variable has automatic storage, it will have an initial value, but that value will be indeterminate. If it has static storage, it will be initialized implicitly depending on the type (e.g. pointer types get initialized to null pointers, arithmetic types get initialized to zero, and so on).

So, if you define an automatic variable without specifying an initial value for it, such as:

int myfunc(void) {
    int myvar;

You are defining it (and therefore also declaring it, since definitions are declarations), but not initializing it. Therefore, definition does not equal declaration plus initialization.

How to convert object array to string array in Java

Easily change without any headche Convert any object array to string array Object drivex[] = {1,2};

    for(int i=0; i<drive.length ; i++)
            Str[i]= drivex[i].toString();

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Check Safari developer reference on Touch class.

According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX and not PageX

How to make child element higher z-index than parent?

This is impossible as a child's z-index is set to the same stacking index as its parent.

You have already solved the problem by removing the z-index from the parent, keep it like this or make the element a sibling instead of a child.

Center icon in a div - horizontally and vertically

Horizontal centering is as easy as:

text-align: center

Vertical centering when the container is a known height:

height: 100px;
line-height: 100px;
vertical-align: middle

Vertical centering when the container isn't a known height AND you can set the image in the background:

background: url(someimage) no-repeat center center;

How should I load files into my Java application?

What are you loading the files for - configuration or data (like an input file) or as a resource?

  • If as a resource, follow the suggestion and example given by Will and Justin
  • If configuration, then you can use a ResourceBundle or Spring (if your configuration is more complex).
  • If you need to read a file in order to process the data inside, this code snippet may help BufferedReader file = new BufferedReader(new FileReader(filename)) and then read each line of the file using file.readLine(); Don't forget to close the file.

SQL update fields of one table from fields of another one

you can build and execute dynamic sql to do this, but its really not ideal

Table header to stay fixed at the top when user scrolls it out of view with jQuery

div.wrapper {_x000D_
table.scroll thead {_x000D_
    width: 100%;_x000D_
    background: #FC6822;_x000D_
table.scroll thead tr:after {_x000D_
    content: '';_x000D_
    overflow-y: scroll;_x000D_
    visibility: hidden;_x000D_
table.scroll thead th {_x000D_
    flex: 1 auto;_x000D_
    display: block;_x000D_
    color: #fff;_x000D_
table.scroll tbody {_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
    overflow-y: auto;_x000D_
    height: auto;_x000D_
    max-height: 200px;_x000D_
table.scroll thead tr,_x000D_
table.scroll tbody tr {_x000D_
    display: flex;_x000D_
table.scroll tbody tr td {_x000D_
    flex: 1 auto;_x000D_
    word-wrap: break;_x000D_
table.scroll thead tr th,_x000D_
table.scroll tbody tr td {_x000D_
    width: 25%;_x000D_
    padding: 5px;_x000D_
    border-bottom: 1px solid rgba(0,0,0,0.3);_x000D_
<div class="wrapper">_x000D_
    <table border="0" cellpadding="0" cellspacing="0" class="scroll">_x000D_

Demo: css fixed table header demo

How to compile LEX/YACC files on Windows?

Go for the full installation of Git for windows (with Unix tool), and bison and flex would come with it in the bin folder.

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

How can I generate Unix timestamps?

The unix 'date' command is surprisingly versatile.

date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"

Takes the output of date, which will be in the format defined by -f, and then prints it out (-j says don't attempt to set the date) in the form +%s, seconds since epoch.

Creating a JavaScript cookie on a domain and reading it across sub domains

You want:

document.cookie = cookieName +"=" + cookieValue + ";;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka

Sort a list by multiple attributes?

There is a operator < between lists e.g.:

[12, 'tall', 'blue', 1] < [4, 'tall', 'blue', 13]

will give


How to add a local repo and treat it as a remote repo

You have your arguments to the remote add command reversed:

git remote add <NAME> <PATH>


git remote add bak /home/sas/dev/apps/smx/repo/bak/ontologybackend/.git

See git remote --help for more information.

Remove an entire column from a data.frame in R

The posted answers are very good when working with data.frames. However, these tasks can be pretty inefficient from a memory perspective. With large data, removing a column can take an unusually long amount of time and/or fail due to out of memory errors. Package data.table helps address this problem with the := operator:

> dt <- data.table(a = 1, b = 1, c = 1)
> dt[,a:=NULL]
     b c
[1,] 1 1

I should put together a bigger example to show the differences. I'll update this answer at some point with that.

Difference between "managed" and "unmanaged"

Managed Code

Managed code is what Visual Basic .NET and C# compilers create. It runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. So, think of it as, "My code is managed by the CLR."

Visual Basic and C# can only produce managed code, so, if you're writing an application in one of those languages you are writing an application managed by the CLR. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it's optional.

Unmanaged Code

Unmanaged code compiles straight to machine code. So, by that definition all code compiled by traditional C/C++ compilers is 'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.

No free memory management or anything else the CLR provides.

Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.

Mixing the two

Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application. This blurs the line between the two and complicates the definition, but it's worth mentioning just so you know that you can still have memory leaks if, for example, you're using a third party library with some badly written unmanaged code.

Here's an example I found by googling:

#using <mscorlib.dll>
using namespace System;

#include "stdio.h"

void ManagedFunction()
    printf("Hello, I'm managed in this section\n");

#pragma unmanaged
    printf("Hello, I am unmanaged through the wonder of IJW!\n");

#pragma managed
int main()
    return 0;

Static Classes In Java

A static method means that it can be accessed without creating an object of the class, unlike public:

public class MyClass {
   // Static method
   static void myStaticMethod() {
      System.out.println("Static methods can be called without creating objects");

  // Public method
  public void myPublicMethod() {
      System.out.println("Public methods must be called by creating objects");

  // Main method
  public static void main(String[ ] args) {
      myStaticMethod(); // Call the static method
    // myPublicMethod(); This would output an error

    MyClass myObj = new MyClass(); // Create an object of MyClass
    myObj.myPublicMethod(); // Call the public method

Git asks for username every time I push

I faced this issue today. If you are facing this issue in November 2020 then you need to update your git version. I received an email telling me about this. Here is what exactly was the email by github team.

We have detected that you recently attempted to authenticate to GitHub using an older version of Git for Windows. GitHub has changed how users authenticate when using Git for Windows, and now requires the use of a web browser to authenticate to GitHub. To be able to login via web browser, users need to update to the latest version of Git for Windows. You can download the latest version at:

If you cannot update Git for Windows to the latest version please see the following link for more information and suggested workarounds:

If you have any questions about these changes or require any assistance, please reach out to GitHub Support and we’ll be happy to assist further.

Thanks, The GitHub Team

how to set JAVA_OPTS for Tomcat in Windows?


set JAVA_OPTS=%JAVA_OPTS% -Xms512M -Xmx1024M

Chrome says my extension's manifest file is missing or unreadable

My problem was slightly different.

By default Eclipse saved my manifest.json as an ANSI encoded text file.


  • Open in Notepad
  • File -> Save As
  • select UTF-8 from the encoding drop-down in the bottom left.
  • Save

Creating a simple login form

edited @Asraful Haque answer with a bit of js to show and hide the box

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
    /* Basics */
    html, body {
        width: 100%;
        height: 100%;
        font-family: "Helvetica Neue", Helvetica, sans-serif;
        color: #444;
        -webkit-font-smoothing: antialiased;
        background: #f0f0f0;
    #container {
        position: fixed;
        width: 340px;
        height: 280px;
        top: 50%;
        left: 50%;
        margin-top: -140px;
        margin-left: -170px;
        background: #fff;
        border-radius: 3px;
        border: 1px solid #ccc;
        box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
        display: none;
    form {
        margin: 0 auto;
        margin-top: 20px;
    label {
        color: #555;
        display: inline-block;
        margin-left: 18px;
        padding-top: 10px;
        font-size: 14px;
    p a {
        font-size: 11px;
        color: #aaa;
        float: right;
        margin-top: -13px;
        margin-right: 20px;
     -webkit-transition: all .4s ease;
        -moz-transition: all .4s ease;
        transition: all .4s ease;
    p a:hover {
        color: #555;
    input {
        font-family: "Helvetica Neue", Helvetica, sans-serif;
        font-size: 12px;
        outline: none;
    input[type=password] ,input[type=time]{
        color: #777;
        padding-left: 10px;
        margin: 10px;
        margin-top: 12px;
        margin-left: 18px;
        width: 290px;
        height: 35px;
        border: 1px solid #c7d0d2;
        border-radius: 2px;
        box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
        -webkit-transition: all .4s ease;
        -moz-transition: all .4s ease;
        transition: all .4s ease;
    input[type=password]:hover,input[type=time]:hover {
        border: 1px solid #b6bfc0;
        box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
    input[type=password]:focus,input[type=time]:focus {
        border: 1px solid #a8c9e4;
        box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
    #lower {
        background: #ecf2f5;
        width: 100%;
        height: 69px;
        margin-top: 20px;
          box-shadow: inset 0 1px 1px #fff;
        border-top: 1px solid #ccc;
        border-bottom-right-radius: 3px;
        border-bottom-left-radius: 3px;
    input[type=checkbox] {
        margin-left: 20px;
        margin-top: 30px;
    .check {
        margin-left: 3px;
        font-size: 11px;
        color: #444;
        text-shadow: 0 1px 0 #fff;
    input[type=submit] {
        float: right;
        margin-right: 20px;
        margin-top: 20px;
        width: 80px;
        height: 30px;
        font-size: 14px;
        font-weight: bold;
        color: #fff;
        background-color: #acd6ef; /*IE fallback*/
        background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
        background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
        background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
        border-radius: 30px;
        border: 1px solid #66add6;
        box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
        cursor: pointer;
    input[type=submit]:hover {
        background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
        background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
        background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
    input[type=submit]:active {
        background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
        background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
        background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
    function clicker () {
        var login = document.getElementById("container");"block";

    <a href="#" id="link" onClick="clicker();">login</a>
    <!-- Begin Page Content -->
    <div id="container">
        <form action="login_process.php" method="post">
            <label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php  echo @$_GET['msg'];?></label>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password">
            <div id="lower">
                <input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
                <input type="submit" value="Login">
            </div><!--/ lower-->
    </div><!--/ container-->
    <!-- End Page Content -->

Two Divs on the same row and center align both of them

I would vote against display: inline-block since its not supported across browsers, IE < 8 specifically.

.wrapper {
    width:500px; /* Adjust to a total width of both .left and .right */
    margin: 0 auto;
.left {
    float: left;
    width: 49%; /* Not 50% because of 1px border. */
    border: 1px solid #000;
.right {
    float: right;
    width: 49%; /* Not 50% because of 1px border. */
    border: 1px solid #F00;

<div class="wrapper">
    <div class="left">Div 1</div>
    <div class="right">Div 2</div>

EDIT: If no spacing between the cells is desired just change both .left and .right to use float: left;

Get Today's date in Java at midnight time

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");

Why not use tables for layout in HTML?

Obvious answer: See CSS Zen Garden. If you tell me that you can easily do the same with a table-based layout (remember - the HTML isn't changing) then by all means use tables for layout.

Two other important things are accessibility and SEO.

Both care about in what order information is presented. You cannot easily present your navigation at the top of the page if your table-based layout puts it in the 3rd cell of the 2nd row of the 2nd nested table on the page.

So your answers are maintainability, accessibility and SEO.

Don't be lazy. Do things the right and proper way even if they are a bit harder to learn.

Is there an alternative sleep function in C to milliseconds?

You can use this cross-platform function:

#ifdef WIN32
#include <windows.h>
#elif _POSIX_C_SOURCE >= 199309L
#include <time.h>   // for nanosleep
#include <unistd.h> // for usleep

void sleep_ms(int milliseconds){ // cross-platform sleep function
#ifdef WIN32
#elif _POSIX_C_SOURCE >= 199309L
    struct timespec ts;
    ts.tv_sec = milliseconds / 1000;
    ts.tv_nsec = (milliseconds % 1000) * 1000000;
    nanosleep(&ts, NULL);
    if (milliseconds >= 1000)
      sleep(milliseconds / 1000);
    usleep((milliseconds % 1000) * 1000);

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

How can I convert radians to degrees with Python?

Python convert radians to degrees or degrees to radians:

What are Radians and what problem does it solve?:

Radians and degrees are two separate units of measure that help people express and communicate precise changes in direction. Wikipedia has some great intuition with their infographics on how one Radian is defined relative to degrees:

Conversion from radians to degrees

Python examples using libraries calculating degrees from radians:

>>> import math
>>> math.degrees(0)                       #0 radians == 0 degrees
>>> math.degrees(math.pi/2)               #pi/2 radians is 90 degrees
>>> math.degrees(math.pi)                 #pi radians is 180 degrees
>>> math.degrees(math.pi+(math.pi/2))     #pi+pi/2 radians is 270 degrees
>>> math.degrees(math.pi+math.pi)         #2*pi radians is 360 degrees

Python examples using libraries calculating radians from degrees:

>>> import math
>>> math.radians(0)           #0 degrees == 0 radians
>>> math.radians(90)          #90 degrees is pi/2 radians
>>> math.radians(180)         #180 degrees is pi radians
>>> math.radians(270)         #270 degrees is pi+(pi/2) radians
>>> math.radians(360)         #360 degrees is 2*pi radians


The mathematical notation:

Mathematical notation of degrees and radians

You can do degree/radian conversion without libraries:

If you roll your own degree/radian converter, you have to write your own code to handle edge cases.

Mistakes here are easy to make, and will hurt just like it hurt the developers of the 1999 mars orbiter who sunk $125m dollars crashing it into Mars because of non intuitive edge cases here.

Lets crash that orbiter and Roll our own Radians to Degrees:

Invalid radians as input return garbage output.

>>> 0 * 180.0 / math.pi                         #0 radians is 0 degrees
>>> (math.pi/2) * 180.0 / math.pi               #pi/2 radians is 90 degrees
>>> (math.pi) * 180.0 / math.pi                 #pi radians is 180 degrees
>>> (math.pi+(math.pi/2)) * 180.0 / math.pi     #pi+(pi/2) radians is 270 degrees
>>> (2 * math.pi) * 180.0 / math.pi             #2*pi radians is 360 degrees

Degrees to radians:

>>> 0 * math.pi / 180.0              #0 degrees in radians
>>> 90 * math.pi / 180.0             #90 degrees in radians
>>> 180 * math.pi / 180.0            #180 degrees in radians
>>> 270 * math.pi / 180.0            #270 degrees in radians
>>> 360 * math.pi / 180.0            #360 degrees in radians

Expressing multiple rotations with degrees and radians

Single rotation valid radian values are between 0 and 2*pi. Single rotation degree values are between 0 and 360. However if you want to express multiple rotations, valid radian and degree values are between 0 and infinity.

>>> import math
>>> math.radians(360)                 #one complete rotation
>>> math.radians(360+360)             #two rotations
>>> math.degrees(12.566370614359172)  #math.degrees and math.radians preserve the
720.0                                 #number of rotations

Collapsing multiple rotations:

You can collapse multiple degree/radian rotations into a single rotation by modding against the value of one rotation. For degrees you mod by 360, for radians you modulus by 2*pi.

>>> import math
>>> math.radians(720+90)        #2 whole rotations plus 90 is 14.14 radians
>>> math.radians((720+90)%360)  #14.1 radians brings you to 
1.5707963267948966              #the end point as 1.57 radians.

>>> math.degrees((2*math.pi)+(math.pi/2))            #one rotation plus a quarter 
450.0                                                #rotation is 450 degrees.
>>> math.degrees(((2*math.pi)+(math.pi/2))%(2*math.pi)) #one rotation plus a quarter
90.0                                                    #rotation brings you to 90.


Khan academy has some excellent content to solidify intuition around trigonometry and angular mathematics:

How do I export (and then import) a Subversion repository?

The tool to do that would be

svnadmin dump

But for this to work, you need filesystem-access to the repository. And once you have that (and provided the repository is in FSFS format), you can just copy the repository to its new location (if it's in BDB format, dump/load is strongly recommended).

If you do not have filesystem access, you would have to ask your repository provider to provide the dump for you (and make them delete their repository - and hope they comply)

Exception: "URI formats are not supported"

I solved the same error with the Path.Combine(MapPath()) to get the physical file path instead of the http:/// www one.

Is there a method for String conversion to Title Case?

It seems none of the answers format it in the actual title case: "How to Land Your Dream Job", "To Kill a Mockingbird", etc. so I've made my own method. Works best for English languages texts.

private final static Set<Character> TITLE_CASE_DELIMITERS = new HashSet<>();

  static {

  private final static Set<String> TITLE_SMALLCASED_WORDS = new HashSet<>();

  static {

  public static String toCapitalizedWord(String oneWord) {
    if (oneWord.length() < 1) {
      return oneWord.toUpperCase();
    return "" + Character.toTitleCase(oneWord.charAt(0)) + oneWord.substring(1).toLowerCase();

  public static String toTitledWord(String oneWord) {
    if (TITLE_SMALLCASED_WORDS.contains(oneWord.toLowerCase())) {
      return oneWord.toLowerCase();
    return toCapitalizedWord(oneWord);

  public static String toTitleCase(String str) {
    StringBuilder result = new StringBuilder();
    StringBuilder oneWord = new StringBuilder();

    char previousDelimiter = 'x';
    /* on start, always move to upper case */
    for (char c : str.toCharArray()) {
      if (TITLE_CASE_DELIMITERS.contains(c)) {
        if (previousDelimiter == '-' || previousDelimiter == 'x') {
        } else {
        previousDelimiter = c;
      } else {
    if (previousDelimiter == '-' || previousDelimiter == 'x') {
    } else {
    return result.toString();

  public static void main(String[] args) {
    System.out.println(toTitleCase("one year in paris"));
    System.out.println(toTitleCase("How to Land Your Dream Job"));

Pandas: rolling mean by time interval

In the meantime, a time-window capability was added. See this link.

In [1]: df = DataFrame({'B': range(5)})

In [2]: df.index = [Timestamp('20130101 09:00:00'),
   ...:             Timestamp('20130101 09:00:02'),
   ...:             Timestamp('20130101 09:00:03'),
   ...:             Timestamp('20130101 09:00:05'),
   ...:             Timestamp('20130101 09:00:06')]

In [3]: df
2013-01-01 09:00:00  0
2013-01-01 09:00:02  1
2013-01-01 09:00:03  2
2013-01-01 09:00:05  3
2013-01-01 09:00:06  4

In [4]: df.rolling(2, min_periods=1).sum()
2013-01-01 09:00:00  0.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  3.0
2013-01-01 09:00:05  5.0
2013-01-01 09:00:06  7.0

In [5]: df.rolling('2s', min_periods=1).sum()
2013-01-01 09:00:00  0.0
2013-01-01 09:00:02  1.0
2013-01-01 09:00:03  3.0
2013-01-01 09:00:05  3.0
2013-01-01 09:00:06  7.0

How to convert DateTime to VarChar

You did not say which database, but with mysql here is an easy way to get a date from a timestamp (and the varchar type conversion should happen automatically):

mysql> select date(now());
| date(now()) |
| 2008-09-16  | 
1 row in set (0.00 sec)

Create a sample login page using servlet and JSP?

You aren't really using the doGet() method. When you're opening the page, it issues a GET request, not POST.

Try changing doPost() to service() instead... then you're using the same method to handle GET and POST requests.


C# DateTime.ParseExact

It's probably the same problem with cultures as presented in this related SO-thread: Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

You already specified the culture, so try escaping the slashes.

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.


Mailbox unavailable. The server response was: 5.7.1 Unable to relay Error

I use Windows Server 2012 for hosting for a long time and it just stop working after a more than years without any problem. My solution was to add public IP address of the server to list of relays and enabled Windows Integrated Authentication.

I just made two changes and I don't which help.

Go to IIS 6 Manager

Go to IIS 6 Manager

Select properties of SMTP server

Select properties of SMTP server

On tab Access, select Relays

On tab Access, select Relays

Add your public IP address

Add your public IP address

Close the dialog and on the same tab click to Authentication button.

Add Integrated Windows Authentication

Add Integrated Windows Authentication

Maybe some step is not needed, but it works.

Bootstrap 3 Collapse show state with Chevron icon

Improvement on Bludream's answer:

You can definitely use FontAwesome!

Make sure to include "collapsed" along with "panel-heading" class. The "collapsed" class is not included until you click on the panel so you want to include the "collapsed" class in order to display the correct chevron (i.e., chevron-right is displayed when collapsed and chevron-down when open).


<div class="panel panel-default">
    <div class="panel-heading collapsed" data-toggle="collapse" data-target="#collapseOrderItems1">Products 1 <i class="chevron fa fa-fw" ></i></div>
    <div class="collapse" id="collapseOrderItems1">
        <p>Lorem ipsum...</p>


.panel-heading .chevron:after {
    content: "\f078";   
.panel-heading.collapsed .chevron:after {
    content: "\f054";   

Also, it is a good practice to create a new class instead of using an existing class.

See Codepen for example:

How to find unused/dead code in java projects

We've started to use Find Bugs to help identify some of the funk in our codebase's target-rich environment for refactorings. I would also consider Structure 101 to identify spots in your codebase's architecture that are too complicated, so you know where the real swamps are.

How do I delete all messages from a single queue using the CLI?

IMPORTANT NOTE: This will delete all users and config.



I don't suggest this answer until unless you want to delete data from all of the queues, including users and configs. Just Reset it !!!

rabbitmqctl stop_app
rabbitmqctl reset
rabbitmqctl start_app

Is there a better alternative than this to 'switch on type'?

You can use pattern matching in C# 7 or above:

switch (foo.GetType())
    case var type when type == typeof(Player):
    case var type when type == typeof(Address):
    case var type when type == typeof(Department):
    case var type when type == typeof(ContactType):

Convert Current date to integer

Your Problem is because of getTime() . it always return following.

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Because the max integer value is less then the return value by getTime() that why is showing wrong result.

Converting String to "Character" array in Java

I hope the code below will help you.

String s="Welcome to Java Programming";
char arr[]=s.toCharArray();
for(int i=0;i<arr.length;i++){
    System.out.println("Data at ["+i+"]="+arr[i]);

It's working and the output is:

Data at [0]=W
Data at [1]=e
Data at [2]=l
Data at [3]=c
Data at [4]=o
Data at [5]=m
Data at [6]=e
Data at [7]= 
Data at [8]=t
Data at [9]=o
Data at [10]= 
Data at [11]=J
Data at [12]=a
Data at [13]=v
Data at [14]=a
Data at [15]= 
Data at [16]=P
Data at [17]=r
Data at [18]=o
Data at [19]=g
Data at [20]=r
Data at [21]=a
Data at [22]=m
Data at [23]=m
Data at [24]=i
Data at [25]=n
Data at [26]=g

Android lollipop change navigation bar color

You can add the following line in the values-v21/style.xml folder:

<item name="android:navigationBarColor">@color/theme_color</item>

Spring - download response as a file

It's working for me :

  • Spring controller :

    package com.mycompany.myapp.controller;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import com.mycompany.myapp.exception.TechnicalException;
    public class DownloadController {
        private final Logger log = LoggerFactory.getLogger(DownloadController.class);
        @RequestMapping(value = "/download", method = RequestMethod.GET)
        public void download(@RequestParam ("name") String name, final HttpServletRequest request, final HttpServletResponse response) throws TechnicalException {
            log.trace("name : {}", name);
            File file = new File ("src/main/resources/" + name);
            log.trace("Write response...");
            try (InputStream fileInputStream = new FileInputStream(file);
                    OutputStream output = response.getOutputStream();) {
                response.setContentLength((int) (file.length()));
                response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
                IOUtils.copyLarge(fileInputStream, output);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
  • AngularJs Service : download.service.js

    (function() {
        'use strict';
        var downloadModule = angular.module('components.donwload', []);
        downloadModule.factory('downloadService', ['$q', '$timeout', '$window',
            function($q, $timeout, $window) {
                return {
                    download: function(name) {
                        var defer = $q.defer();
                        $timeout(function() {
                                $window.location = 'download?name=' + name;
                            }, 1000)
                            .then(function() {
                            }, function() {
                        return defer.promise;
  • AngularJs config : app.js

    (function() {
        'use strict';
        var myApp = angular.module('myApp', ['components.donwload']);
       /* myApp.config([function () {
        }]);[function () {
  • AngularJs controller : download.controller.js

    (function() {
        'use strict';
            .controller('DownloadSampleCtrl', ['downloadService', function(downloadService) {
       = function(fileName) {
                        .then(function(success) {
                            console.log('success : ' + success);
                        }, function(error) {
                            console.log('error : ' + error);
  • index.html

    <!DOCTYPE html>
    <html ng-app="myApp">
        <title>My App</title>
        <link rel="stylesheet" href="bower_components/normalize.css/normalize.css" />
        <link rel="stylesheet" href="assets/styles/main.css" />
        <link rel="icon" href="favicon.ico">
        <div ng-controller="DownloadSampleCtrl as ctrl">
            <button ng-click="'fileName.txt')">Download</button>
        <script src="bower_components/angular/angular.min.js"></script>
        <!-- App config -->
        <script src="scripts/app/app.js"></script>
        <!-- Download Feature -->
        <script src="scripts/app/download/download.controller.js"></script>
        <!-- Components -->
        <script src="scripts/components/download/download.service.js"></script>

Failed to connect to, reason: errno:111 Connection refused

I solved that simply by entering sudo mongo after mongod command.

How do I set up the database.yml file in Rails?

At first I would use

And database.yml is place where you put setup for database your application use - username, password, host - for each database. With new application you dont need to change anything - simply use default sqlite setup.