Programs & Examples On #Delayed job

A Ruby library to queue and defer processing of slow methods like sending email and image resizing.

getaddrinfo: nodename nor servname provided, or not known

I got the same error when I check the localhost is set in hosts file it is somehow not set. Setting localhost to solved it.

sudo vi /etc/hosts
>>       localhost

git command to move a folder inside another

One of the nicest things about git is that you don't need to track file renames explicitly. Git will figure it out by comparing the contents of the files.

So, in your case, don't work so hard:

$ mkdir include
$ mv common include
$ git rm -r common
$ git add include/common

Running git status should show you something like this:

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#   renamed:    common/file.txt -> include/common/file.txt

Is there a color code for transparent in HTML?

All you need is this:


Here the ffffff is the color and 00 is the transparency

Also, if you want 50% transparent color, then sure you can do... #ffffff80

Where 80 is the hexadecimal equivalent of 50%. Since the scale is 0-255 in RGB Colors, the half would be 255/2 = 128, which when converted to hex becomes 80

And since in transparent we want 0 opacity, we write 00

HTML img onclick Javascript

This might work for you...

<script type="text/javascript">
function image(img) {
    var src = img.src;;
<img src="pond1.jpg" height="150" size="150" alt="Johnson Pond" onclick="image(this)">

What is the difference between Collection and List in Java?

Collection is the Super interface of List so every Java list is as well an instance of collection. Collections are only iterable sequentially (and in no particular order) whereas a List allows access to an element at a certain position via the get(int index) method.

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)


  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog


  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers


Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).

In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

Fastest way to zero out a 2d array in C?

How was your 2D array declared?

If it something like:

int arr[20][30];

You can zero it by doing:

memset(arr, sizeof(int)*20*30);

JFrame in full screen Java

You only need this:

JFrame frame = new JFrame();

When you use the MAXIMIZED_BOTH modifier, it will max all the way across the window (height and width).

There are some that suggested using this:


I won't recommend it, because your window won't have a header, thus no close/restore/minimize button.

How to Rotate a UIImage 90 degrees?

A thread safe rotation function is the following (it works much better):

-(UIImage*)imageByRotatingImage:(UIImage*)initImage fromImageOrientation:(UIImageOrientation)orientation
CGImageRef imgRef = initImage.CGImage;

CGFloat width = CGImageGetWidth(imgRef);
CGFloat height = CGImageGetHeight(imgRef);

CGAffineTransform transform = CGAffineTransformIdentity;
CGRect bounds = CGRectMake(0, 0, width, height);
CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));
CGFloat boundHeight;
UIImageOrientation orient = orientation;
switch(orient) {

    case UIImageOrientationUp: //EXIF = 1
        return initImage;

    case UIImageOrientationUpMirrored: //EXIF = 2
        transform = CGAffineTransformMakeTranslation(imageSize.width, 0.0);
        transform = CGAffineTransformScale(transform, -1.0, 1.0);

    case UIImageOrientationDown: //EXIF = 3
        transform = CGAffineTransformMakeTranslation(imageSize.width, imageSize.height);
        transform = CGAffineTransformRotate(transform, M_PI);

    case UIImageOrientationDownMirrored: //EXIF = 4
        transform = CGAffineTransformMakeTranslation(0.0, imageSize.height);
        transform = CGAffineTransformScale(transform, 1.0, -1.0);

    case UIImageOrientationLeftMirrored: //EXIF = 5
        boundHeight = bounds.size.height;
        bounds.size.height = bounds.size.width;
        bounds.size.width = boundHeight;
        transform = CGAffineTransformMakeTranslation(imageSize.height, imageSize.width);
        transform = CGAffineTransformScale(transform, -1.0, 1.0);
        transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);

    case UIImageOrientationLeft: //EXIF = 6
        boundHeight = bounds.size.height;
        bounds.size.height = bounds.size.width;
        bounds.size.width = boundHeight;
        transform = CGAffineTransformMakeTranslation(0.0, imageSize.width);
        transform = CGAffineTransformRotate(transform, 3.0 * M_PI / 2.0);

    case UIImageOrientationRightMirrored: //EXIF = 7
        boundHeight = bounds.size.height;
        bounds.size.height = bounds.size.width;
        bounds.size.width = boundHeight;
        transform = CGAffineTransformMakeScale(-1.0, 1.0);
        transform = CGAffineTransformRotate(transform, M_PI / 2.0);

    case UIImageOrientationRight: //EXIF = 8
        boundHeight = bounds.size.height;
        bounds.size.height = bounds.size.width;
        bounds.size.width = boundHeight;
        transform = CGAffineTransformMakeTranslation(imageSize.height, 0.0);
        transform = CGAffineTransformRotate(transform, M_PI / 2.0);

        [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];

// Create the bitmap context
CGContextRef    context = NULL;
void *          bitmapData;
int             bitmapByteCount;
int             bitmapBytesPerRow;

// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow   = (bounds.size.width * 4);
bitmapByteCount     = (bitmapBytesPerRow * bounds.size.height);
bitmapData = malloc( bitmapByteCount );
if (bitmapData == NULL)
    return nil;

// Create the bitmap context. We want pre-multiplied ARGB, 8-bits
// per component. Regardless of what the source image format is
// (CMYK, Grayscale, and so on) it will be converted over to the format
// specified here by CGBitmapContextCreate.
CGColorSpaceRef colorspace = CGImageGetColorSpace(imgRef);
context = CGBitmapContextCreate (bitmapData,bounds.size.width,bounds.size.height,8,bitmapBytesPerRow,
                                 colorspace, kCGBitmapAlphaInfoMask & kCGImageAlphaPremultipliedLast);

if (context == NULL)
    // error creating context
    return nil;

CGContextScaleCTM(context, -1.0, -1.0);
CGContextTranslateCTM(context, -bounds.size.width, -bounds.size.height);

CGContextConcatCTM(context, transform);

// Draw the image to the bitmap context. Once we draw, the memory
// allocated for the context for rendering will then contain the
// raw image data in the specified color space.
CGContextDrawImage(context, CGRectMake(0,0,width, height), imgRef);

CGImageRef imgRef2 = CGBitmapContextCreateImage(context);
UIImage * image = [UIImage imageWithCGImage:imgRef2 scale:initImage.scale orientation:UIImageOrientationUp];
return image;

What are good examples of genetic algorithms/genetic programming solutions?

I used genetic algorithms (as well as some related techniques) to determine the best settings for a risk management system that tried to keep gold farmers from using stolen credit cards to pay for MMOs. The system would take in several thousand transactions with "known" values (fraud or not) and figure out what the best combination of settings was to properly identify the fraudulent transactions without having too many false positives.

We had data on several dozen (boolean) characteristics of a transaction, each of which was given a value and totalled up. If the total was higher than a threshold, the transaction was fraud. The GA would create a large number of random sets of values, evaluate them against a corpus of known data, select the ones that scored the best (on both fraud detection and limiting the number of false positives), then cross breed the best few from each generation to produce a new generation of candidates. After a certain number of generations the best scoring set of values was deemed the winner.

Creating the corpus of known data to test against was the Achilles' heel of the system. If you waited for chargebacks, you were several months behind when trying to respond to the fraudsters, so someone would have to manually review large numbers of transactions to build up that corpus of data without having to wait too long.

This ended up identifying the vast majority of the fraud that came in, but couldn't quite get it below 1% on the most fraud-prone items (given that 90% of incoming transactions could be fraud, that was doing pretty well).

I did all this using perl. One run of the software on a fairly old linux box would take 1-2 hours to run (20 minutes to load data over a WAN link, the rest of the time spent crunching). The size of any given generation was limited by available RAM. I'd run it over and over with slight changes to the parameters, looking for an especially good result set.

All in all it avoided some of the gaffes that came with manually trying to tweak the relative values of dozens of fraud indicators, and consistently came up with better solutions than I could create by hand. AFAIK, it's still in use (about 3 years after I wrote it).

Interface naming in Java

Following good OO principles, your code should (as far as practical/possible) depend on abstractions rather than concrete classes. For example, it is generally better to write a method like this:

public void doSomething(Collection someStuff) {

than this:

public void doSomething(Vector someStuff) {

If you follow this idea, then I maintain that your code will be more readable if you give interfaces names like "User" and "BankAccount" (for example), rather than "IUser", "UserInterface", or other variations.

The only bits of code that should care about the actual concrete classes are the places where the concrete classes are constructed. Everything else should be written using the interfaces.

If you do this, then the "ugly" concrete class names like "UserImpl" should be safely hidden from the rest of the code, which can merrily go on using the "nice" interface names.

Add two textbox values and display the sum in a third textbox automatically

i didn't find who made elegant answer , that's why let me say :

).map(e => parseInt(e.value) || 0) // to avoid NaN
.reduce((a, b) => a+b, 0)

window.sum= () => _x000D_
 document.getElementById('result').innerHTML=    _x000D_
<input type="text" id="txt1" onkeyup="sum()"/>_x000D_
<input type="text" id="txt2" onkeyup="sum()"  style="margin-right:10px;"/><span id="result"></span>

Replace Multiple String Elements in C#

this will be more efficient:

public static class StringExtension
    public static string clean(this string s)
        return new StringBuilder(s)
              .Replace("&", "and")
              .Replace(",", "")
              .Replace("  ", " ")
              .Replace(" ", "-")
              .Replace("'", "")
              .Replace(".", "")
              .Replace("eacute;", "é")

Post-increment and Pre-increment concept?

All four answers so far are incorrect, in that they assert a specific order of events.

Believing that "urban legend" has led many a novice (and professional) astray, to wit, the endless stream of questions about Undefined Behavior in expressions.


For the built-in C++ prefix operator,


increments x and produces (as the expression's result) x as an lvalue, while


increments x and produces (as the expression's result) the original value of x.

In particular, for x++ there is no no time ordering implied for the increment and production of original value of x. The compiler is free to emit machine code that produces the original value of x, e.g. it might be present in some register, and that delays the increment until the end of the expression (next sequence point).

Folks who incorrectly believe the increment must come first, and they are many, often conclude from that certain expressions must have well defined effect, when they actually have Undefined Behavior.

javascript filter array multiple conditions

A clean and functional solution

const combineFilters = (...filters) => (item) => {
    return => filter(item)).every((x) => x === true);

then you use it like so:

const filteredArray = arr.filter(combineFilters(filterFunc1, filterFunc2));

and filterFunc1 for example might look like this:

const filterFunc1 = (item) => {
  return item === 1 ? true : false;

How to npm install to a specified directory?

I am using a powershell build and couldn't get npm to run without changing the current directory.

Ended up using the start command and just specifying the working directory:

start "npm" -ArgumentList "install --warn" -wo $buildFolder

C++ class forward declaration

The problem is that tick() needs to know the definition of tile_tree_apple, but all it has is a forward declaration of it. You should separate the declarations and definitions like so:


#ifndef TILE_TREE_H
#define TILE_TREE_H
#include "tile.h"

class tile_tree : public tile
    tile onDestroy();
    tile tick();
    void onCreate();



tile tile_tree::onDestroy() {
    return *new tile_grass;

tile tile_tree::tick() {
     if (rand() % 20 == 0)
         return *new tile_tree_apple;

void tile_tree::onCreate() {
    health = rand() % 5 + 4;
    type = TILET_TREE;

Except you have a major problem: you’re allocating memory (with new), then copying the allocated object and returning the copy. This is called a memory leak, because there’s no way for your program to free the memory it uses. Not only that, but you’re copying a tile_tree into a tile, which discards the information that makes a tile_tree different from a tile; this is called slicing.

What you want is to return a pointer to a new tile, and make sure you call delete at some point to free the memory:

tile* tile_tree::tick() {
     if (rand() % 20 == 0)
         return new tile_tree_apple;

Even better would be to return a smart pointer that will handle the memory management for you:

#include <memory>

std::shared_ptr<tile> tile_tree::tick() {
     if (rand() % 20 == 0)
         return std::make_shared<tile_tree_apple>();

How to run travis-ci locally

Travis-ci offers a new container-based infrastructure that uses docker. This can be very useful if you're trying to troubleshoot a travis-ci build by reproducing it locally. This is taken from Travis CI's documentation.

Troubleshooting Locally in a Docker Image

If you're having trouble tracking down the exact problem in a build it often helps to run the build locally. To do this you need to be using our container based infrastructure (ie, have sudo: false in your .travis.yml), and to know which Docker image you are using on Travis CI.

Running a Container Based Docker Image Locally

  1. Download and install the Docker Engine.
  2. Select an image from Docker Hub. If you're not using a language-specific image pick ci-ruby. Open a terminal and start an interactive Docker session using the image URL:

    docker run -it travisci/ubuntu-ruby:18.04 /bin/bash
  3. Switch to the travis user:

    su - travis
  4. Clone your git repository into the / folder of the image.
  5. Manually install any dependencies.
  6. Manually run your Travis CI build command.

How to Remove Line Break in String

Private Sub Form_Load()
    Dim s As String

    s = "test" & vbCrLf & "this" & vbCrLf & vbCrLf
    Debug.Print (s & Len(s))

    s = Left(s, Len(s) - Len(vbCrLf))
    Debug.Print (s & Len(s))
End Sub

How to convert all tables from MyISAM into InnoDB?


// Convert all MyISAM tables to INNODB tables in all non-special databases.
// Note: With MySQL less than 5.6, tables with a fulltext search index cannot be converted to INNODB and will be skipped.

if($argc < 4)
    exit("Usage: {$argv[0]} <host> <username> <password>\n");
$host = $argv[1];
$username = $argv[2];
$password = $argv[3];

// Connect to the database.
if(!mysql_connect($host, $username, $password))
    exit("Error opening database. " . mysql_error() . "\n");

// Get all databases except special ones that shouldn't be converted.
$databases = mysql_query("SHOW databases WHERE `Database` NOT IN ('mysql', 'information_schema', 'performance_schema')");
if($databases === false)
    exit("Error showing databases. " . mysql_error() . "\n");

while($db = mysql_fetch_array($databases))
    // Select the database.
        exit("Error selecting database: {$db[0]}. " . mysql_error() . "\n");
    printf("Database: %s\n", $db[0]);

    // Get all MyISAM tables in the database.
    $tables = mysql_query("SHOW table status WHERE Engine = 'MyISAM'");
    if($tables === false)
        exit("Error showing tables. " . mysql_error() . "\n");

    while($tbl = mysql_fetch_array($tables))
        // Convert the table to INNODB.
        printf("--- Converting %s\n", $tbl[0]);
        if(mysql_query("ALTER TABLE `{$tbl[0]}` ENGINE = INNODB") === false)
            printf("--- --- Error altering table: {$tbl[0]}. " . mysql_error() . "\n");



File upload along with other object in Jersey restful web service

You can access the Image File and data from a form using MULTIPART FORM DATA By using the below code.

public Response updateProfile(
    @FormDataParam("file") InputStream fileInputStream,
    @FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
    @FormDataParam("ProfileInfo") String ProfileInfo,
    @FormDataParam("registrationId") String registrationId) {

    String filePath= "/filepath/"+contentDispositionHeader.getFileName();

    OutputStream outputStream = null;
    try {
        int read = 0;
        byte[] bytes = new byte[1024];
        outputStream = new FileOutputStream(new File(filePath));

        while ((read = != -1) {
            outputStream.write(bytes, 0, read);

    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    } finally {
        if (outputStream != null) { 
            try {
            } catch(Exception ex) {}

Javascript / Chrome - How to copy an object from the webkit inspector as code

  1. Right-click an object in Chrome's console and select Store as Global Variable from the context menu. It will return something like temp1 as the variable name.

  2. Chrome also has a copy() method, so copy(temp1) in the console should copy that object to your clipboard.

Copy Javascript Object in Chrome DevTools

Note on Recursive Objects: If you're trying to copy a recursive object, you will get [object Object]. The way out is to copy(JSON.stringify(temp1)) , the object will be fully copied to your clipboard as a valid JSON, so you'd be able to format it as you wish, using one of many resources.

node.js http 'get' request with query string parameters

No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:

const requestUrl = url.parse(url.format({
    protocol: 'https',
    hostname: '',
    pathname: '/the/path',
    query: {
        key: value

Then make the request with the formatted url. requestUrl.path will include the query parameters.

const req = https.get({
    hostname: requestUrl.hostname,
    path: requestUrl.path,
}, (res) => {
   // ...

How to replace comma (,) with a dot (.) using java

in the java src you can add a new tool like this:

public static String remplaceVirguleParpoint(String chaine) {
       return chaine.replaceAll(",", "\\.");

Change Oracle port from port 8080

I assume you're talking about the Apache server that Oracle installs. Look for the file httpd.conf.

Open this file in a text editor and look for the line
Listen 8080
Listen {ip address}:8080

Change the port number and either restart the web server or just reboot the machine.

The import javax.persistence cannot be resolved

If you are using Hibernate as a JPA implementation and you are not using Maven/Gradle, the easier way is to download whole bundle instead of jar file one by one.

Go and download the latest library, extract the jar from the required folder.

Maven: The packaging for this project did not assign a file to the build artifact

This worked for me when I got the same error message...

mvn install deploy

Combine Points with lines with ggplot2

You may find that using the `group' aes will help you get the result you want. For example:

tu <- expand.grid(Land       = gl(2, 1, labels = c("DE", "BB")),
                  Altersgr   = gl(5, 1, labels = letters[1:5]),
                  Geschlecht = gl(2, 1, labels = c('m', 'w')),
                  Jahr       = 2000:2009)

tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)

ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) + 
  geom_point() + geom_line() + 
  facet_grid(Geschlecht ~ Land)

Which produces the plot found here:

enter image description here

xcopy file, rename, suppress "Does xxx specify a file name..." message

I suggest robocopy instead of copy or xcopy. Used as command or in GUI on clients or servers. Tolerant of network pauses and you can choose to ignore file attributes when copying of copy by file attributes. Oh, and it supports multi-core machines so files are copied much faster in "parallel" with each other instead of sequentially. robocopy can be found on MS TechNet.

Get underlined text with Markdown

Both <ins>text</ins> and <span style="text-decoration:underline">text</span> work perfectly in Joplin, although I agree with @nfm that underlined text looks like a link and can be misleading in Markdown.

Returning JSON from PHP to JavaScript?

$msg="You Enter Wrong Username OR Password"; $responso=json_encode($msg);

echo "{\"status\" : \"400\", \"responce\" : \"603\", \"message\" : \"You Enter Wrong Username OR Password\", \"feed\":".str_replace("<p>","",$responso). "}";

What is difference between XML Schema and DTD?

Differences between an XML Schema Definition (XSD) and Document Type Definition (DTD) include:

  • XML schemas are written in XML while DTD are derived from SGML syntax.
  • XML schemas define datatypes for elements and attributes while DTD doesn't support datatypes.
  • XML schemas allow support for namespaces while DTD does not.
  • XML schemas define number and order of child elements, while DTD does not.
  • XML schemas can be manipulated on your own with XML DOM but it is not possible in case of DTD.
  • using XML schema user need not to learn a new language but working with DTD is difficult for a user.
  • XML schema provides secure data communication i.e sender can describe the data in a way that receiver will understand, but in case of DTD data can be misunderstood by the receiver.
  • XML schemas are extensible while DTD is not extensible.

Not all these bullet points are 100% accurate, but you get the gist.

On the other hand:

  • DTD lets you define new ENTITY values for use in your XML file.
  • DTD lets you extend it local to an individual XML file.

Can't find the 'libpq-fe.h header when trying to install pg gem

On CentOS,I installed libpq-dev package using below command

yum install postgresql-devel

Executing gem install pg returned the same error as "No pg_config... trying anyway. If building fails, please try again with --with-pg-config=/path/to/pg_config".

Installing the gem as below solved my problem

gem install pg -- --with-pg-config=/usr/pgsql-x.x/bin/pg_config

nginx: connect() failed (111: Connection refused) while connecting to upstream

I don't think that solution would work anyways because you will see some error message in your error log file.

The solution was a lot easier than what I thought.

simply, open the following path to your php5-fpm

sudo nano /etc/php5/fpm/pool.d/www.conf

or if you're the admin 'root'

nano /etc/php5/fpm/pool.d/www.conf

Then find this line and uncomment it:

listen.allowed_clients =

This solution will make you be able to use listen = in your vhost blocks

like this: fastcgi_pass;

after you make the modifications, all you need is to restart or reload both Nginx and Php5-fpm


sudo service php5-fpm restart


sudo service php5-fpm reload


sudo service nginx restart


sudo service nginx reload

From the comments:

Also comment

;listen = /var/run/php5-fpm.sock 

and add

listen = 9000

Can RDP clients launch remote applications and not desktops

This is called "seamless" mode. rdesktop, the RDP client for Unix, is capable of this. From the manpage:

   -A     Enable SeamlessRDP. In this mode, rdesktop creates a X11 window for each window on the server
          side.  This  mode  requires  the  SeamlessRDP  server side component, which is available from
  When using this option, you  should  specify  a  startup
          shell which launches the desired application through SeamlessRDP.

See mentioned Cendio website for more information.

Permutations in JavaScript?

The following very efficient algorithm uses Heap's method to generate all permutations of N elements with runtime complexity in O(N!):

function permute(permutation) {_x000D_
  var length = permutation.length,_x000D_
      result = [permutation.slice()],_x000D_
      c = new Array(length).fill(0),_x000D_
      i = 1, k, p;_x000D_
  while (i < length) {_x000D_
    if (c[i] < i) {_x000D_
      k = i % 2 && c[i];_x000D_
      p = permutation[i];_x000D_
      permutation[i] = permutation[k];_x000D_
      permutation[k] = p;_x000D_
      i = 1;_x000D_
    } else {_x000D_
      c[i] = 0;_x000D_
  return result;_x000D_
console.log(permute([1, 2, 3]));

The same algorithm implemented as a generator with space complexity in O(N):

function* permute(permutation) {_x000D_
  var length = permutation.length,_x000D_
      c = Array(length).fill(0),_x000D_
      i = 1, k, p;_x000D_
  yield permutation.slice();_x000D_
  while (i < length) {_x000D_
    if (c[i] < i) {_x000D_
      k = i % 2 && c[i];_x000D_
      p = permutation[i];_x000D_
      permutation[i] = permutation[k];_x000D_
      permutation[k] = p;_x000D_
      i = 1;_x000D_
      yield permutation.slice();_x000D_
    } else {_x000D_
      c[i] = 0;_x000D_
// Memory efficient iteration through permutations:_x000D_
for (var permutation of permute([1, 2, 3])) console.log(permutation);_x000D_
// Simple array conversion:_x000D_
var permutations = [...permute([1, 2, 3])];

Performance comparison

Feel free to add your implementation to the following benchmark.js test suite:

function permute_SiGanteng(input) {_x000D_
  var permArr = [],_x000D_
    usedChars = [];_x000D_
  function permute(input) {_x000D_
    var i, ch;_x000D_
    for (i = 0; i < input.length; i++) {_x000D_
      ch = input.splice(i, 1)[0];_x000D_
      if (input.length == 0) {_x000D_
      input.splice(i, 0, ch);_x000D_
    return permArr_x000D_
  return permute(input);_x000D_
function permute_delimited(inputArr) {_x000D_
  var results = [];_x000D_
  function permute(arr, memo) {_x000D_
    var cur, memo = memo || [];_x000D_
    for (var i = 0; i < arr.length; i++) {_x000D_
      cur = arr.splice(i, 1);_x000D_
      if (arr.length === 0) {_x000D_
      permute(arr.slice(), memo.concat(cur));_x000D_
      arr.splice(i, 0, cur[0]);_x000D_
    return results;_x000D_
  return permute(inputArr);_x000D_
function permute_monkey(inputArray) {_x000D_
  return inputArray.reduce(function permute(res, item, key, arr) {_x000D_
    return res.concat(arr.length > 1 && arr.slice(0, key).concat(arr.slice(key + 1)).reduce(permute, []).map(function(perm) {_x000D_
      return [item].concat(perm);_x000D_
    }) || item);_x000D_
  }, []);_x000D_
function permute_Oriol(input) {_x000D_
  var permArr = [],_x000D_
    usedChars = [];_x000D_
  return (function main() {_x000D_
    for (var i = 0; i < input.length; i++) {_x000D_
      var ch = input.splice(i, 1)[0];_x000D_
      if (input.length == 0) {_x000D_
      input.splice(i, 0, ch);_x000D_
    return permArr;_x000D_
function permute_MarkusT(input) {_x000D_
  function permutate(array, callback) {_x000D_
      function p(array, index, callback) {_x000D_
          function swap(a, i1, i2) {_x000D_
              var t = a[i1];_x000D_
              a[i1] = a[i2];_x000D_
              a[i2] = t;_x000D_
          if (index == array.length - 1) {_x000D_
              return 1;_x000D_
          } else {_x000D_
              var count = p(array, index + 1, callback);_x000D_
              for (var i = index + 1; i < array.length; i++) {_x000D_
                  swap(array, i, index);_x000D_
                  count += p(array, index + 1, callback);_x000D_
                  swap(array, i, index);_x000D_
              return count;_x000D_
      if (!array || array.length == 0) {_x000D_
          return 0;_x000D_
      return p(array, 0, callback);_x000D_
  var result = [];_x000D_
  permutate(input, function(a) {_x000D_
  return result;_x000D_
function permute_le_m(permutation) {_x000D_
  var length = permutation.length,_x000D_
    result = [permutation.slice()],_x000D_
      c = new Array(length).fill(0),_x000D_
      i = 1, k, p;_x000D_
  while (i < length) {_x000D_
    if (c[i] < i) {_x000D_
      k = i % 2 && c[i],_x000D_
      p = permutation[i];_x000D_
      permutation[i] = permutation[k];_x000D_
      permutation[k] = p;_x000D_
      i = 1;_x000D_
    } else {_x000D_
      c[i] = 0;_x000D_
  return result;_x000D_
function permute_Urielzen(arr) {_x000D_
    var finalArr = [];_x000D_
    var iterator = function (arrayTaken, tree) {_x000D_
        for (var i = 0; i < tree; i++) {_x000D_
            var temp = arrayTaken.slice();_x000D_
            temp.splice(tree - 1 - i, 0, temp.splice(tree - 1, 1)[0]);_x000D_
            if (tree >= arr.length) {_x000D_
            } else { iterator(temp, tree + 1); }_x000D_
    iterator(arr, 1); return finalArr;_x000D_
function permute_Taylor_Hakes(arr) {_x000D_
  var permutations = [];_x000D_
  if (arr.length === 1) {_x000D_
    return [ arr ];_x000D_
  for (var i = 0; i <  arr.length; i++) { _x000D_
    var subPerms = permute_Taylor_Hakes(arr.slice(0, i).concat(arr.slice(i + 1)));_x000D_
    for (var j = 0; j < subPerms.length; j++) {_x000D_
  return permutations;_x000D_
var Combinatorics = (function () {_x000D_
    'use strict';_x000D_
    var version = "0.5.2";_x000D_
    /* combinatory arithmetics */_x000D_
    var P = function(m, n) {_x000D_
        var p = 1;_x000D_
        while (n--) p *= m--;_x000D_
        return p;_x000D_
    var C = function(m, n) {_x000D_
        if (n > m) {_x000D_
            return 0;_x000D_
        return P(m, n) / P(n, n);_x000D_
    var factorial = function(n) {_x000D_
        return P(n, n);_x000D_
    var factoradic = function(n, d) {_x000D_
        var f = 1;_x000D_
        if (!d) {_x000D_
            for (d = 1; f < n; f *= ++d);_x000D_
            if (f > n) f /= d--;_x000D_
        } else {_x000D_
            f = factorial(d);_x000D_
        var result = [0];_x000D_
        for (; d; f /= d--) {_x000D_
            result[d] = Math.floor(n / f);_x000D_
            n %= f;_x000D_
        return result;_x000D_
    /* common methods */_x000D_
    var addProperties = function(dst, src) {_x000D_
        Object.keys(src).forEach(function(p) {_x000D_
            Object.defineProperty(dst, p, {_x000D_
                value: src[p],_x000D_
                configurable: p == 'next'_x000D_
    var hideProperty = function(o, p) {_x000D_
        Object.defineProperty(o, p, {_x000D_
            writable: true_x000D_
    var toArray = function(f) {_x000D_
        var e, result = [];_x000D_
        while (e = result.push(f ? f(e) : e);_x000D_
        return result;_x000D_
    var common = {_x000D_
        toArray: toArray,_x000D_
        map: toArray,_x000D_
        forEach: function(f) {_x000D_
            var e;_x000D_
            while (e = f(e);_x000D_
        filter: function(f) {_x000D_
            var e, result = [];_x000D_
            while (e = if (f(e)) result.push(e);_x000D_
            return result;_x000D_
        lazyMap: function(f) {_x000D_
            this._lazyMap = f;_x000D_
            return this;_x000D_
        lazyFilter: function(f) {_x000D_
            Object.defineProperty(this, 'next', {_x000D_
                writable: true_x000D_
            if (typeof f !== 'function') {_x000D_
       = this._next;_x000D_
            } else {_x000D_
                if (typeof (this._next) !== 'function') {_x000D_
                    this._next =;_x000D_
                var _next = this._next.bind(this);_x000D_
       = (function() {_x000D_
                    var e;_x000D_
                    while (e = _next()) {_x000D_
                        if (f(e))_x000D_
                            return e;_x000D_
                    return e;_x000D_
            Object.defineProperty(this, 'next', {_x000D_
                writable: false_x000D_
            return this;_x000D_
    /* power set */_x000D_
    var power = function(ary, fun) {_x000D_
        var size = 1 << ary.length,_x000D_
            sizeOf = function() {_x000D_
                return size;_x000D_
            that = Object.create(ary.slice(), {_x000D_
                length: {_x000D_
                    get: sizeOf_x000D_
        hideProperty(that, 'index');_x000D_
        addProperties(that, {_x000D_
            valueOf: sizeOf,_x000D_
            init: function() {_x000D_
                that.index = 0;_x000D_
            nth: function(n) {_x000D_
                if (n >= size) return;_x000D_
                var i = 0,_x000D_
                    result = [];_x000D_
                for (; n; n >>>= 1, i++) if (n & 1) result.push(this[i]);_x000D_
                return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;_x000D_
            next: function() {_x000D_
                return this.nth(this.index++);_x000D_
        addProperties(that, common);_x000D_
        return (typeof (fun) === 'function') ? : that;_x000D_
    /* combination */_x000D_
    var nextIndex = function(n) {_x000D_
        var smallest = n & -n,_x000D_
            ripple = n + smallest,_x000D_
            new_smallest = ripple & -ripple,_x000D_
            ones = ((new_smallest / smallest) >> 1) - 1;_x000D_
        return ripple | ones;_x000D_
    var combination = function(ary, nelem, fun) {_x000D_
        if (!nelem) nelem = ary.length;_x000D_
        if (nelem < 1) throw new RangeError;_x000D_
        if (nelem > ary.length) throw new RangeError;_x000D_
        var first = (1 << nelem) - 1,_x000D_
            size = C(ary.length, nelem),_x000D_
            maxIndex = 1 << ary.length,_x000D_
            sizeOf = function() {_x000D_
                return size;_x000D_
            that = Object.create(ary.slice(), {_x000D_
                length: {_x000D_
                    get: sizeOf_x000D_
        hideProperty(that, 'index');_x000D_
        addProperties(that, {_x000D_
            valueOf: sizeOf,_x000D_
            init: function() {_x000D_
                this.index = first;_x000D_
            next: function() {_x000D_
                if (this.index >= maxIndex) return;_x000D_
                var i = 0,_x000D_
                    n = this.index,_x000D_
                    result = [];_x000D_
                for (; n; n >>>= 1, i++) {_x000D_
                    if (n & 1) result[result.length] = this[i];_x000D_
                this.index = nextIndex(this.index);_x000D_
                return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;_x000D_
        addProperties(that, common);_x000D_
        return (typeof (fun) === 'function') ? : that;_x000D_
    /* permutation */_x000D_
    var _permutation = function(ary) {_x000D_
        var that = ary.slice(),_x000D_
            size = factorial(that.length);_x000D_
        that.index = 0;_x000D_ = function() {_x000D_
            if (this.index >= size) return;_x000D_
            var copy = this.slice(),_x000D_
                digits = factoradic(this.index, this.length),_x000D_
                result = [],_x000D_
                i = this.length - 1;_x000D_
            for (; i >= 0; --i) result.push(copy.splice(digits[i], 1)[0]);_x000D_
            return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;_x000D_
        return that;_x000D_
    // which is really a permutation of combination_x000D_
    var permutation = function(ary, nelem, fun) {_x000D_
        if (!nelem) nelem = ary.length;_x000D_
        if (nelem < 1) throw new RangeError;_x000D_
        if (nelem > ary.length) throw new RangeError;_x000D_
        var size = P(ary.length, nelem),_x000D_
            sizeOf = function() {_x000D_
                return size;_x000D_
            that = Object.create(ary.slice(), {_x000D_
                length: {_x000D_
                    get: sizeOf_x000D_
        hideProperty(that, 'cmb');_x000D_
        hideProperty(that, 'per');_x000D_
        addProperties(that, {_x000D_
            valueOf: function() {_x000D_
                return size;_x000D_
            init: function() {_x000D_
                this.cmb = combination(ary, nelem);_x000D_
                this.per = _permutation(;_x000D_
            next: function() {_x000D_
                var result =;_x000D_
                if (!result) {_x000D_
                    var cmb =;_x000D_
                    if (!cmb) return;_x000D_
                    this.per = _permutation(cmb);_x000D_
                return (typeof (that._lazyMap) === 'function')?that._lazyMap(result):result;_x000D_
        addProperties(that, common);_x000D_
        return (typeof (fun) === 'function') ? : that;_x000D_
    /* export */_x000D_
    var Combinatorics = Object.create(null);_x000D_
    addProperties(Combinatorics, {_x000D_
        C: C,_x000D_
        P: P,_x000D_
        factorial: factorial,_x000D_
        factoradic: factoradic,_x000D_
        permutation: permutation,_x000D_
    return Combinatorics;_x000D_
function permute_Technicalbloke(inputArray) {_x000D_
  if (inputArray.length === 1) return inputArray;_x000D_
  return inputArray.reduce( function(accumulator,_,index){_x000D_
    return accumulator;_x000D_
var suite = new Benchmark.Suite;_x000D_
var input = [0, 1, 2, 3, 4];_x000D_
suite.add('permute_SiGanteng', function() {_x000D_
  .add('permute_delimited', function() {_x000D_
  .add('permute_monkey', function() {_x000D_
  .add('permute_Oriol', function() {_x000D_
  .add('permute_MarkusT', function() {_x000D_
  .add('permute_le_m', function() {_x000D_
  .add('permute_Urielzen', function() {_x000D_
  .add('permute_Taylor_Hakes', function() {_x000D_
  .add('permute_Combinatorics', function() {_x000D_
  .add('permute_Technicalbloke', function() {_x000D_
  .on('cycle', function(event) {_x000D_
  .on('complete', function() {_x000D_
    console.log('Fastest is ' + this.filter('fastest').map('name'));_x000D_
  .run({async: true});
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<script src=""></script>

Run-time results for Chrome 48:

How to return a value from pthread threads in C?

You've returned a pointer to a local variable. That's bad even if threads aren't involved.

The usual way to do this, when the thread that starts is the same thread that joins, would be to pass a pointer to an int, in a location managed by the caller, as the 4th parameter of pthread_create. This then becomes the (only) parameter to the thread's entry-point. You can (if you like) use the thread exit value to indicate success:

#include <pthread.h>
#include <stdio.h>

int something_worked(void) {
    /* thread operation might fail, so here's a silly example */
    void *p = malloc(10);
    return p ? 1 : 0;

void *myThread(void *result)
   if (something_worked()) {
       *((int*)result) = 42;
   } else {

int main()
   pthread_t tid;
   void *status = 0;
   int result;

   pthread_create(&tid, NULL, myThread, &result);
   pthread_join(tid, &status);

   if (status != 0) {
   } else {
       printf("thread failed\n");

   return 0;

If you absolutely have to use the thread exit value for a structure, then you'll have to dynamically allocate it (and make sure that whoever joins the thread frees it). That's not ideal, though.

SSL InsecurePlatform error when using Requests package

For me no work i need upgrade pip....


install dependencies

sudo apt-get install libpython-dev libssl-dev libffi-dev

upgrade pip and install packages

sudo pip install -U pip
sudo pip install -U pyopenssl ndg-httpsclient pyasn1

If you want remove dependencies

sudo apt-get remove --purge libpython-dev libssl-dev libffi-dev
sudo apt-get autoremove

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Another easy way to circumvent google's check is to use another compression algorithm with tar, like bz2:

tar -cvjf my.tar.bz2 dir/

Note that 'j' (for bz2 compression) is used above instead of 'z' (gzip compression).

Sum across multiple columns with dplyr

If you want to sum certain columns only, I'd use something like this:

df %>% select(x3:x5) %>% rowSums(na.rm=TRUE) -> df$

This way you can use dplyr::select's syntax.

What is a constant reference? (not a reference to a constant)

First I think int&const icr=i; is just int& icr = i, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).

const int x = 10;
// int& const y = x; // Compiler error here

Second, constant reference just means you cannot change the value of variable through reference.

const int x = 10;
const int& y = x;
//y = 20; // Compiler error here

Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.

float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340

Path.Combine absolute with relative path strings

For windows universal apps Path.GetFullPath() is not available, you can use the System.Uri class instead:

 Uri uri = new Uri(Path.Combine(@"C:\blah\",@"..\bling"));

What is an undefined reference/unresolved external symbol error and how do I fix it?

Failure to link against appropriate libraries/object files or compile implementation files

Commonly, each translation unit will generate an object file that contains the definitions of the symbols defined in that translation unit. To use those symbols, you have to link against those object files.

Under gcc you would specify all object files that are to be linked together in the command line, or compile the implementation files together.

g++ -o test objectFile1.o objectFile2.o -lLibraryName

The libraryName here is just the bare name of the library, without platform-specific additions. So e.g. on Linux library files are usually called but you'd only write -lfoo. On Windows that same file might be called foo.lib, but you'd use the same argument. You might have to add the directory where those files can be found using -L‹directory›. Make sure to not write a space after -l or -L.

For XCode: Add the User Header Search Paths -> add the Library Search Path -> drag and drop the actual library reference into the project folder.

Under MSVS, files added to a project automatically have their object files linked together and a lib file would be generated (in common usage). To use the symbols in a separate project, you'd need to include the lib files in the project settings. This is done in the Linker section of the project properties, in Input -> Additional Dependencies. (the path to the lib file should be added in Linker -> General -> Additional Library Directories) When using a third-party library that is provided with a lib file, failure to do so usually results in the error.

It can also happen that you forget to add the file to the compilation, in which case the object file won't be generated. In gcc you'd add the files to the command line. In MSVS adding the file to the project will make it compile it automatically (albeit files can, manually, be individually excluded from the build).

In Windows programming, the tell-tale sign that you did not link a necessary library is that the name of the unresolved symbol begins with __imp_. Look up the name of the function in the documentation, and it should say which library you need to use. For example, MSDN puts the information in a box at the bottom of each function in a section called "Library".

Passing an array as an argument to a function in C

Arrays in C are converted, in most of the cases, to a pointer to the first element of the array itself. And more in detail arrays passed into functions are always converted into pointers.

Here a quote from K&R2nd:

When an array name is passed to a function, what is passed is the location of the initial element. Within the called function, this argument is a local variable, and so an array name parameter is a pointer, that is, a variable containing an address.


void arraytest(int a[])

has the same meaning as writing:

void arraytest(int *a)

So despite you are not writing it explicitly it is as you are passing a pointer and so you are modifying the values in the main.

For more I really suggest reading this.

Moreover, you can find other answers on SO here

How to import a single table in to mysql database using command line

All of these options are fine, if you have the option to re-export the data.

But if you need to use an existing SQL file, and use a specific table from it, then this perl script in the TimeSheet blog, with enable you to extract the table to a separate SQL file, and then import it.

The original link is dead, so it is a good thing that someone has put it instead of the author, Jared Cheney, on GitHub, in this link.

How can I expand and collapse a <div> using javascript?

Take a look at toggle() jQuery function :

Also, innerHTML jQuery Function is .html().

How to add a Java Properties file to my Java Project in Eclipse

If you are working with core java, create your file(.properties) by right clicking your project. If the file is present inside your package or src folder it will throw an file not found error

How to correct TypeError: Unicode-objects must be encoded before hashing?

Please take a look first at that answer.

Now, the error message is clear: you can only use bytes, not Python strings (what used to be unicode in Python < 3), so you have to encode the strings with your preferred encoding: utf-32, utf-16, utf-8 or even one of the restricted 8-bit encodings (what some might call codepages).

The bytes in your wordlist file are being automatically decoded to Unicode by Python 3 as you read from the file. I suggest you do:


so that the encoded data pushed to the md5 algorithm are encoded exactly like the underlying file.

npm - how to show the latest version of a package

There is also another easy way to check the latest version without going to NPM if you are using VS Code.

In package.json file check for the module you want to know the latest version. Remove the current version already present there and do CTRL + space or CMD + space(mac).The VS code will show the latest versions

image shows the latest versions of modules in vscode

How to get start and end of previous month in VB

Just to add something to what @Fionnuala Said, The below functions can be used. These even work for leap years.

'If you pass #2016/20/01# you get #2016/31/01#
Public Function GetLastDate(tempDate As Date) As Date
    GetLastDate = DateSerial(Year(tempDate), Month(tempDate) + 1, 0)
End Function

'If you pass #2016/20/01# you get 31
Public Function GetLastDay(tempDate As Date) As Integer
    GetLastDay = Day(DateSerial(Year(tempDate), Month(tempDate) + 1, 0))
End Function

Import cycle not allowed

Here is an illustration of your first import cycle problem.

                     ^                    \    
                    /                      \
                   /                        \ 
                  /                         \/
         project/components/mux <--- project/controllers/base

As you can see with my bad ASCII chart is that you are creating an import cycle when project/components/mux imports project/controllers/account. Since Go does not support circular dependencies you get the import cycle not allowed error during compile time.

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:


To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

Where can I find the Java SDK in Linux after installing it?

This is the best way which worked for me Execute this Command:-

$(dirname $(readlink $(which javac)))/java_home

Ruby objects and JSON serialization (without Rails)

Jbuilder is a gem built by rails community. But it works well in non-rails environments and have a cool set of features.

# suppose we have a sample object as below #=> foo
sampleObj.last_name #=> bar

# using jbuilder we can convert it to json:
Jbuilder.encode do |json|
  json.last_name sampleObj.last_name
end #=> "{:\"name\" => \"foo\", :\"last_name\" => \"bar\"}"

The service cannot accept control messages at this time

I killed related w3wp.exe (on a friends' advise) at task manager and it worked.

Note: Use at your own risk. Be careful picking which one to kill.

How to find a value in an excel column by vba code Cells.Find

Just use

Dim Cell As Range
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If cell Is Nothing Then
    'do it something

    'do it another thing
End If

how to get the base url in javascript

Should you want what is exactly specified in the web page, just use:

document.querySelector('head base')['href']

ASP.NET MVC View Engine Comparison

ASP.NET MVC View Engines (Community Wiki)

Since a comprehensive list does not appear to exist, let's start one here on SO. This can be of great value to the ASP.NET MVC community if people add their experience (esp. anyone who contributed to one of these). Anything implementing IViewEngine (e.g. VirtualPathProviderViewEngine) is fair game here. Just alphabetize new View Engines (leaving WebFormViewEngine and Razor at the top), and try to be objective in comparisons.


Design Goals:

A view engine that is used to render a Web Forms page to the response.


  • ubiquitous since it ships with ASP.NET MVC
  • familiar experience for ASP.NET developers
  • IntelliSense
  • can choose any language with a CodeDom provider (e.g. C#, VB.NET, F#, Boo, Nemerle)
  • on-demand compilation or precompiled views


  • usage is confused by existence of "classic ASP.NET" patterns which no longer apply in MVC (e.g. ViewState PostBack)
  • can contribute to anti-pattern of "tag soup"
  • code-block syntax and strong-typing can get in the way
  • IntelliSense enforces style not always appropriate for inline code blocks
  • can be noisy when designing simple templates


<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
    <% foreach(var p in model){%>
    <p>No products available</p>


Design Goals:


  • Compact, Expressive, and Fluid
  • Easy to Learn
  • Is not a new language
  • Has great Intellisense
  • Unit Testable
  • Ubiquitous, ships with ASP.NET MVC


  • Creates a slightly different problem from "tag soup" referenced above. Where the server tags actually provide structure around server and non-server code, Razor confuses HTML and server code, making pure HTML or JS development challenging (see Con Example #1) as you end up having to "escape" HTML and / or JavaScript tags under certain very common conditions.
  • Poor encapsulation+reuseability: It's impractical to call a razor template as if it were a normal method - in practice razor can call code but not vice versa, which can encourage mixing of code and presentation.
  • Syntax is very html-oriented; generating non-html content can be tricky. Despite this, razor's data model is essentially just string-concatenation, so syntax and nesting errors are neither statically nor dynamically detected, though VS.NET design-time help mitigates this somewhat. Maintainability and refactorability can suffer due to this.
  • No documented API,

Con Example #1 (notice the placement of "string[]..."):

    <h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
    foreach (var person in teamMembers)


Design goals:

  • Respect HTML as first-class language as opposed to treating it as "just text".
  • Don't mess with my HTML! The data binding code (Bellevue code) should be separate from HTML.
  • Enforce strict Model-View separation


Design Goals:

The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework. For an introduction to Brail, see the documentation on the Castle project website.


  • modeled after "wrist-friendly python syntax"
  • On-demand compiled views (but no precompilation available)


  • designed to be written in the language Boo


     <p>The following items are in the list:</p>  
     <ul><%for element in list:    output "<li>${element}</li>"%></ul>
     <p>I hope that you would like Brail</p>    


Hasic uses VB.NET's XML literals instead of strings like most other view engines.


  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular VB.NET code
  • Unit testable


  • Performance: Builds the whole DOM before sending it to client.


Protected Overrides Function Body() As XElement
    Return _
        <h1>Hello, World</h1>
End Function


Design Goals:

NDjango is an implementation of the Django Template Language on the .NET platform, using the F# language.



Design Goals:

.NET port of Rails Haml view engine. From the Haml website:

Haml is a markup language that's used to cleanly and simply describe the XHTML of any web document, without the use of inline code... Haml avoids the need for explicitly coding XHTML into the template, because it is actually an abstract description of the XHTML, with some code to generate dynamic content.


  • terse structure (i.e. D.R.Y.)
  • well indented
  • clear structure
  • C# Intellisense (for VS2008 without ReSharper)


  • an abstraction from XHTML rather than leveraging familiarity of the markup
  • No Intellisense for VS2010


- if(model.Any())
    - foreach (var p in model)
      %li= p.Name
- else
  %p No products available

NVelocityViewEngine (MvcContrib)

Design Goals:

A view engine based upon NVelocity which is a .NET port of the popular Java project Velocity.


  • easy to read/write
  • concise view code


  • limited number of helper methods available on the view
  • does not automatically have Visual Studio integration (IntelliSense, compile-time checking of views, or refactoring)


#foreach ($p in $viewdata.Model)
    <p>No products available</p>


Design Goals:

SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).


  • familiar to Java developers
  • XML-style code blocks


  • ...


<c:if test="${not fn:empty(Page.Tiles)}">
  <p class="note">
    <fmt:message key="page.tilesSupport"/>

Spark View Engine

Design Goals:

The idea is to allow the html to dominate the flow and the code to fit seamlessly.


  • Produces more readable templates
  • C# Intellisense (for VS2008 without ReSharper)
  • SparkSense plug-in for VS2010 (works with ReSharper)
  • Provides a powerful Bindings feature to get rid of all code in your views and allows you to easily invent your own HTML tags


  • No clear separation of template logic from literal markup (this can be mitigated by namespace prefixes)


<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
    <li each="var p in products">${p.Name}</li>
    <p>No products available</p>

<Form style="background-color:olive;">
    <Label For="username" />
    <TextBox For="username" />
    <ValidationMessage For="username" Message="Please type a valid username." />

StringTemplate View Engine MVC

Design Goals:

  • Lightweight. No page classes are created.
  • Fast. Templates are written to the Response Output stream.
  • Cached. Templates are cached, but utilize a FileSystemWatcher to detect file changes.
  • Dynamic. Templates can be generated on the fly in code.
  • Flexible. Templates can be nested to any level.
  • In line with MVC principles. Promotes separation of UI and Business Logic. All data is created ahead of time, and passed down to the template.


  • familiar to StringTemplate Java developers


  • simplistic template syntax can interfere with intended output (e.g. jQuery conflict)

Wing Beats

Wing Beats is an internal DSL for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for its capability of creating XHTML.


  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular F# code
  • Unit testable


  • You don't really write HTML but code that represents HTML in a DSL.

XsltViewEngine (MvcContrib)

Design Goals:

Builds views from familiar XSLT


  • widely ubiquitous
  • familiar template language for XML developers
  • XML-based
  • time-tested
  • Syntax and element nesting errors can be statically detected.


  • functional language style makes flow control difficult
  • XSLT 2.0 is (probably?) not supported. (XSLT 1.0 is much less practical).

Given a URL to a text file, what is the simplest way to read the contents of the text file?

For me, none of the above responses worked straight ahead. Instead, I had to do the following (Python 3):

from urllib.request import urlopen

data = urlopen("[your url goes here]").read().decode('utf-8')

# Do what you need to do with the data.

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

In Typescript with relative path to the icon:

import path from 'path';

route.get('/favicon.ico', (_req, res) => res.sendFile(path.join(__dirname, '../static/myicon.png')));

How to publish a website made by Node.js to Github Pages?

I was able to set up github actions to automatically commit the results of a node build command (yarn build in my case but it should work with npm too) to the gh-pages branch whenever a new commit is pushed to master.

While not completely ideal as i'd like to avoid committing the built files, it seems like this is currently the only way to publish to github pages.

I based my workflow off of this guide for a different react library, and had to make the following changes to get it to work for me:

  • updated the "setup node" step to use the version found here since the one from the sample i was basing it off of was throwing errors because it could not find the correct action.
  • remove the line containing yarn export because that command does not exist and it doesn't seem to add anything helpful (you may also want to change the build line above it to suit your needs)
  • I also added an env directive to the yarn build step so that I can include the SHA hash of the commit that generated the build inside my app, but this is optional

Here is my full github action:

name: github pages

        - master

        runs-on: ubuntu-18.04
        - uses: actions/checkout@v2

        - name: Setup Node
            uses: actions/setup-node@v2-beta
            node-version: '12'

        - name: Get yarn cache
            id: yarn-cache
            run: echo "::set-output name=dir::$(yarn cache dir)"

        - name: Cache dependencies
            uses: actions/cache@v2
            path: ${{ steps.yarn-cache.outputs.dir }}
            key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
            restore-keys: |
                ${{ runner.os }}-yarn-
        - run: yarn install --frozen-lockfile
        - run: yarn build
            REACT_APP_GIT_SHA: ${{ github.SHA }}

        - name: Deploy
            uses: peaceiris/actions-gh-pages@v3
            github_token: ${{ secrets.GITHUB_TOKEN }}
            publish_dir: ./build

Alternative solution

The docs for next.js also provides instructions for setting up with Vercel which appears to be a hosting service for node.js apps similar to github pages. I have not tried this though and so cannot speak to how well it works.

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:


Java parsing XML document gives "Content not allowed in prolog." error

The document looks fine to me but I suspect that it contains invisible characters. Open it in a hex editor to check that there really isn't anything before the very first "<". Make sure the spaces in the XML header are spaces. Maybe delete the space before "?>". Check which line breaks are used.

Make sure the document is proper UTF-8. Some windows editors save the document as UTF-16 (i.e. every second byte is 0).

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Instead of casting the model in the RenderPartial call, and since you're using razor, you can modify the first line in your view from

@model dynamic


@model YourNamespace.YourModelType

This has the advantage of working on every @Html.Partial call you have in the view, and also gives you intellisense for the properties.

How can I get the image url in a Wordpress theme?

src="<?php bloginfo('template_url'); ?>/image_dir/img.ext"
worked for me for wordpress 3.6 i used it to get header logo using as

<img src="<?php bloginfo('template_url'); ?>/images/logo.jpg">

PHP: Get key from array?

$array = array(0 => 100, "color" => "red");

UIView Hide/Show with animation

Swift 4 Transition

    UIView.transition(with: view, duration: 3, options: .transitionCurlDown,
                      animations: {
                        // Animations
                        view.isHidden = hidden
                      completion: { finished in
                        // Compeleted

If you use the approach for older swift versions you'll get an error :

Cannot convert value of type '(_) -> ()' to expected argument type '(() -> Void)?'

Useful reference.

Defining a `required` field in Bootstrap

Update 2018

Since the original answer HTML5 validation is now supported in all modern browsers. Now the easiest way to make a field required is simply using the required attibute.

<input type="email" class="form-control" id="exampleInputEmail1" required>

or in compliant HTML5:

<input type="email" class="form-control" id="exampleInputEmail1" required="true">

Read more on Bootstrap 4 validation

In Bootstrap 3, you can apply a "validation state" class to the parent element:

For example has-error will show a red border around the input. However, this will have no impact on the actual validation of the field. You'd need to add some additional client (javascript) or server logic to make the field required.


Get pandas.read_csv to read empty values as empty string instead of nan

I was still confused after reading the other answers and comments. But the answer now seems simpler, so here you go.

Since Pandas version 0.9 (from 2012), you can read your csv with empty cells interpreted as empty strings by simply setting keep_default_na=False:

pd.read_csv('test.csv', keep_default_na=False)

This issue is more clearly explained in

That was fixed on on Aug 19, 2012 for Pandas version 0.9 in

How to get HTTP response code for a URL in Java?


URL url = new URL("");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();

int code = connection.getResponseCode();

This is by no means a robust example; you'll need to handle IOExceptions and whatnot. But it should get you started.

If you need something with more capability, check out HttpClient.

Converting a pointer into an integer

I came across this question while studying the source code of SQLite.

In the sqliteInt.h, there is a paragraph of code defined a macro convert between integer and pointer. The author made a very good statement first pointing out it should be a compiler dependent problem and then implemented the solution to account for most of the popular compilers out there.

#if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
# define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
#elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
# define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
# define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
#elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
# define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
#else                          /* Generates a warning - but it always works     */
# define SQLITE_INT_TO_PTR(X)  ((void*)(X))
# define SQLITE_PTR_TO_INT(X)  ((int)(X))

And here is a quote of the comment for more details:

** The following macros are used to cast pointers to integers and
** integers to pointers.  The way you do this varies from one compiler
** to the next, so we have developed the following set of #if statements
** to generate appropriate macros for a wide range of compilers.
** The correct "ANSI" way to do this is to use the intptr_t type.
** Unfortunately, that typedef is not available on all compilers, or
** if it is available, it requires an #include of specific headers
** that vary from one machine to the next.
** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
** So we have to define the macros in different ways depending on the
** compiler.

Credit goes to the committers.

Shortcut key for commenting out lines of Python code in Spyder

While the other answers got it right when it comes to add comments, in my case only the following worked.

  • Multi-line comment

    select the lines to be commented + Ctrl + 4

  • Multi-line uncomment

    select the lines to be uncommented + Ctrl + 1

CMake is not able to find BOOST libraries

I just want to point out that the FindBoost macro might be looking for an earlier version, for instance, 1.58.0 when you might have 1.60.0 installed. I suggest popping open the FindBoost macro from whatever it is you are attempting to build, and checking if that's the case. You can simply edit it to include your particular version. (This was my problem.)

Easiest way to open a download window without navigating away from the page

How about:

<meta http-equiv="refresh" content="5;url=">

This way works on all browsers (i think) and let you put a message like: "If the download doesn't start in five seconds, click here."

If you need it to be with javascript.. well...

document.write('<meta http-equiv="refresh" content="5;url=">');


Release generating .pdb files, why?

PDB can be generated for Release as well as for Debug. This is set at (in VS2010 but in VS2005 must be similar):

Project ? Properties ? Build ? Advanced ? Debug Info

Just change it to None.

How can I count the occurrences of a string within a file?

I'm taking some guesses here, because I don't quite understand what you're asking.

I think that what you want is a count of the number of lines on which the pattern 'echo' appears in the given file.

I've pasted your sample text into a file called 6741967.

First, grep finds the matches:

james@Brindle:tmp$grep echo 6741967 
    echo "Preparing to add a new user..."
echo "1. Add user"
echo "2. Exit"
echo "Enter your choice: "

Second, use wc -l to count the lines

james@Brindle:tmp$grep echo 6741967  | wc -l

Create WordPress Page that redirects to another URL

Alternately, use a filter.

Create an empty page in your WordPress blog, named appropriately to what you need it to be. Take note of the post_id. Then create a filter that alters its permalink.

function my_permalink_redirect($permalink) {
    global $post;
    if ($post->ID == your_post_id_here) {
        $permalink = '';
    return $permalink;

This way the url will show up correctly in the page no funny redirects are required.

If you need to do this a lot, then think about using the custom postmeta fields to define a postmeta value for "offsite_url" or something like that, then you can create pages as needed, enter the "offsite_url" value and then use a filter like the one above to instead of checking the post_id you check to see if it has the postmeta required and alter the permalink as needed.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), which gives the possibility to name the result of an expression, we can use a list comprehension to replicate what other languages call fold/foldleft/reduce operations:

Given a list, a reducing function and an accumulator:

items = [1, 2, 3, 4, 5]
f = lambda acc, x: acc * x
accumulator = 1

we can fold items with f in order to obtain the resulting accumulation:

[accumulator := f(accumulator, x) for x in items]
# accumulator = 120

or in a condensed formed:

acc = 1; [acc := acc * x for x in [1, 2, 3, 4, 5]]
# acc = 120

Note that this is actually also a "scanleft" operation as the result of the list comprehension represents the state of the accumulation at each step:

acc = 1
scanned = [acc := acc * x for x in [1, 2, 3, 4, 5]]
# scanned = [1, 2, 6, 24, 120]
# acc = 120

jQuery Select first and second td

You can just pick the next td:

$(".location table tbody tr td:first-child").next("td").addClass("black");

How do I simulate a hover with a touch in touch enabled browsers?

My personal taste is to attribute the :hover styles to the :focus state as well, like:

p {
    color: red;

p:hover, p:focus {
    color: blue;

Then with the following HTML:

<p id="some-p-tag" tabindex="-1">WOOOO</p>

And the following JavaScript:

$("#some-p-tag").on("touchstart", function(e){
    var $elem = $(this);

    if($":focus")) {
        //this can be registered as a "click" on a mobile device, as it's a double tap
    else {

Max tcp/ip connections on Windows Server 2008

How many thousands of users?

I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here:

Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: and here: These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

Edited to add details from the comment below...

If you're already thinking of multiple servers I'd take the following approach.

  1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

  2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here:

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

Vendor code 17002 to connect to SQLDeveloper

I encountered same problem with ORACLE 11G express on Windows. After a long time waiting I got the same error message.

My solution is to make sure the hostname in tnsnames.ora (usually it's not "localhost") and the default hostname in sql developer(usually it's "localhost") same. You can either do this by changing it in the tnsnames.ora, or filling up the same in the sql developer.

Oh, of course you need to reboot all the oracle services (just to be safe).

Hope it helps.

I came across the similar problem again on another machine, but this time above solution doesn't work. After some trying, I found restarting all the oracle related services can fix the problem. Originally when the installation is done, connection can be made. Somehow after several reboot of computer, there is problem. I change all the oracle services with start time as auto. And once I could not connect, I restart them all over again (the core service should be restarted at last order), and works fine.

Some article says it might be due to the MTS problem. Microsoft's problem. Maybe!

Count items in a folder with PowerShell

I finally found this link:

Well, it turns out that this is a quirk caused precisely because there was only one file in the directory. Some searching revealed that in this case, PowerShell returns a scalar object instead of an array. This object doesn’t have a count property, so there isn’t anything to retrieve.

The solution -- force PowerShell to return an array with the @ symbol:

Write-Host @( Get-ChildItem c:\MyFolder ).Count;

Algorithm for solving Sudoku

Not gonna write full code, but I did a sudoku solver a long time ago. I found that it didn't always solve it (the thing people do when they have a newspaper is incomplete!), but now think I know how to do it.

  • Setup: for each square, have a set of flags for each number showing the allowed numbers.
  • Crossing out: just like when people on the train are solving it on paper, you can iteratively cross out known numbers. Any square left with just one number will trigger another crossing out. This will either result in solving the whole puzzle, or it will run out of triggers. This is where I stalled last time.
  • Permutations: there's only 9! = 362880 ways to arrange 9 numbers, easily precomputed on a modern system. All of the rows, columns, and 3x3 squares must be one of these permutations. Once you have a bunch of numbers in there, you can do what you did with the crossing out. For each row/column/3x3, you can cross out 1/9 of the 9! permutations if you have one number, 1/(8*9) if you have 2, and so forth.
  • Cross permutations: Now you have a bunch of rows and columns with sets of potential permutations. But there's another constraint: once you set a row, the columns and 3x3s are vastly reduced in what they might be. You can do a tree search from here to find a solution.

How can I read input from the console using the Scanner class in Java?

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] arguments){
        Scanner input = new Scanner(;

        String username;
        double age;
        String gender;
        String marital_status;
        int telephone_number;

        // Allows a person to enter his/her name   
        Scanner one = new Scanner(;
        System.out.println("Enter Name:" );  
        username =;
        System.out.println("Name accepted " + username);

        // Allows a person to enter his/her age   
        Scanner two = new Scanner(;
        System.out.println("Enter Age:" );  
        age = two.nextDouble();
        System.out.println("Age accepted " + age);

        // Allows a person to enter his/her gender  
        Scanner three = new Scanner(;
        System.out.println("Enter Gender:" );  
        gender =;
        System.out.println("Gender accepted " + gender);

        // Allows a person to enter his/her marital status
        Scanner four = new Scanner(;
        System.out.println("Enter Marital status:" );  
        marital_status =;
        System.out.println("Marital status accepted " + marital_status);

        // Allows a person to enter his/her telephone number
        Scanner five = new Scanner(;
        System.out.println("Enter Telephone number:" );  
        telephone_number = five.nextInt();
        System.out.println("Telephone number accepted " + telephone_number);

How to get the Parent's parent directory in Powershell?

You can split it at the backslashes, and take the next-to-last one with negative array indexing to get just the grandparent directory name.

($scriptpath -split '\\')[-2]

You have to double the backslash to escape it in the regex.

To get the entire path:

($path -split '\\')[0..(($path -split '\\').count -2)] -join '\'

And, looking at the parameters for split-path, it takes the path as pipeline input, so:

$rootpath = $scriptpath | split-path -parent | split-path -parent

JavaScript DOM: Find Element Index In Container

For just elements this can be used to find the index of an element amongst it's sibling elements:

function getElIndex(el) {
    for (var i = 0; el = el.previousElementSibling; i++);
    return i;

Note that previousElementSibling isn't supported in IE<9.

Python - Module Not Found

All modules in Python have to have a certain directory structure. You can find details here.

Create an empty file called under the model directory, such that your directory structure would look something like that:

+-- project
    +-- src
        +-- model

Also in your file change the import statement to the following:

from model.order import SellOrder

That should fix it

P.S.: If you are placing your model directory in some other location (not in the same directory branch), you will have to modify the python path using sys.path.

Django database query: How to get object by id?

I got here for the same problem, but for a different reason:


This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected:


Tail of the traceback for the get() method:

File "django/db/models/", line 197, in get_models
File "django/db/models/", line 72, in _populate
    self.load_app(app_name, True)
File "django/db/models/", line 94, in load_app
    app_module = import_module(app_name)
File "django/utils/", line 35, in import_module
ImportError: No module named myapp

Reading the code inside Django's, I came to the conclusion that my had a bad path to my app which contains my Class model definition. All I had to do was correct the path to the app and the get() method executed fine.

Here is my with the corrected path:

    # ...


All the confusion was caused because I am using Django's ORM as a standalone, so the namespace had to reflect that.

Using Font Awesome icon for bullet points, with a single list item element

@Tama, you may want to check this answer: Using Font Awesome icons as bullets

Basically you can accomplish this by using only CSS without the need for the extra markup as suggested by FontAwesome and the other answers here.

In other words, you can accomplish what you need using the same basic markup you mentioned in your initial post:



gpg failed to sign the data fatal: failed to write commit object [Git 2.10.0]

If you don't want to deal with brew to install gpg, which seems to run into problems from time to time, just download gpg tools from GPG Tools.

As you go through the wizard, click on customize install and deselect the mail plugin (unless you want to use it). These tools seem to work without running into any problems, plus it remembers your passphrase after the first time you sign you commit. No extra configuration needed, other then telling git about which key to use.

At least that has been my experience.

Convert string to variable name in JavaScript

As far as eval vs. global variable solutions...

I think there are advantages to each but this is really a false dichotomy. If you are paranoid of the global namespace just create a temporary namespace & use the same technique.

var tempNamespace = {};
var myString = "myVarProperty";

tempNamespace[myString] = 5;

Pretty sure you could then access as tempNamespace.myVarProperty (now 5), avoiding using window for storage. (The string could also be put directly into the brackets)

Google Maps API v2: How to make markers clickable?

setTag(position) while adding marker to map.

Marker marker =  map.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude)));

getTag() on setOnMarkerClickListener listener

map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                public boolean onMarkerClick(Marker marker) {
                    int position = (int)(marker.getTag());
                   //Using position get Value from arraylist 
                    return false;

CakePHP find method with JOIN

        $services = $this->Service->find('all', array(
            'limit' =>4,
            'fields' => array('Service.*','ServiceImage.*'),
            'joins' => array(
                        'table' => 'services_images',
                        'alias' => 'ServiceImage',
                        'type' => 'INNER',
                        'conditions' => array(
                        'ServiceImage.service_id' =>''

It goges to array is null.

Travel/Hotel API's?

I've used the TripAdvisor API before and its suited me well. It returns, per destination, a list of top-rated hotels, along with options to retrieve reviews, photos, nearby restaurants and a couple other useful things.

From the API page (available API content) :

* Hotel, attraction and restaurant ratings and reviews
* Top 10 lists of hotels, attractions and restaurants in a destination
* Traveler photos of a destination
* Travelers' Choice award badges for hotels and destinations

To expand upon @nstehr's answer, you could also use Yahoo Pipes to facilitate a more granular local search. Go to and do a search for existing hotel pipes and you'll get the idea..

Javascript - Track mouse position

Here's a solution, based on jQuery and a mouse event listener (which is far better than a regular polling) on the body:

$("body").mousemove(function(e) {
    document.Form1.posx.value = e.pageX;
    document.Form1.posy.value = e.pageY;

Mockito matcher and array of primitives

You can use Mockito.any() when arguments are arrays also. I used it like this:

verify(myMock, times(0)).setContents(any(), any());

Trigger change event of dropdown

Try this:

$(document).ready(function(event) {
         // put code here

Define the change event, and trigger it immediately. This ensures the event handler is defined before calling it.

Might be late to answer the original poster, but someone else might benefit from the shorthand notation, and this follows jQuery's chaining, etc

jquery chaining

How do I authenticate a WebClient request?

You need to give the WebClient object the credentials. Something like this...

 WebClient client = new WebClient();
 client.Credentials = new NetworkCredential("username", "password");

Default values and initialization in Java

Read your reference more carefully:

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

The following chart summarizes the default values for the above data types.

. . .

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Email address validation using ASP.NET MVC data type attributes

if you aren't yet using .net 4.5:

/// <summary>
/// </summary>
public class EmailAnnotation : RegularExpressionAttribute
    static EmailAnnotation()
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAnnotation), typeof(RegularExpressionAttributeAdapter));

    /// <summary>
    /// from:
    /// </summary>
    public EmailAnnotation()
        : base(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
            + "@"
            + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$") { }

    public override string FormatErrorMessage(string name)
        return "E-mail is not valid";

Then you can do this:

    public class ContactEmailAddressDto
        public int ContactId { get; set; }
        [Display(Name = "New Email Address")]
        [EmailAnnotation] //**<----- Nifty.**
        public string EmailAddressToAdd { get; set; }

How do I check whether a file exists without exceptions?

You can use os.listdir to check if a file is in a certain directory.

import os
if 'file.ext' in os.listdir('dirpath'):

How to set index.html as root file in Nginx?

According to the documentation Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. Important

an internal redirect to the uri specified in the last parameter is made.

So in last parameter you should add your page or code if first two parameters returns false.

location / {
  try_files $uri $uri/index.html index.html;

How to get response body using HttpURLConnection, when code other than 2xx is returned?

This is an easy way to get a successful response from the server like PHP echo otherwise an error message.

BufferedReader br = null;
if (conn.getResponseCode() == 200) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
    String strCurrentLine;
        while ((strCurrentLine = br.readLine()) != null) {

How to create JSON object using jQuery

A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.

If you want to convert your javascript object to a json string, use JSON.stringify(yourObject);

If you want to create a javascript object, simply do it like this :

var yourObject = {
          test:'test 1',
          testData: [ 
                {testName: 'do',testId:''}

Implement Validation for WPF TextBoxes

When it comes to DiSaSteR's answer, I noticed a different behavior. textBox.Text shows the text in the TextBox as it was before the user entered a new character, while e.Text shows the single character the user just entered. One challenge is that this character might not get appended to the end, but it will be inserted at the carret position:

private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e){
  Regex regex = new Regex ( "[^0-9]+" );

  string text;
  if (textBox.CaretIndex==textBox.Text.Length) {
    text = textBox.Text + e.Text;
  } else {
    text = textBox.Text.Substring(0, textBox.CaretIndex)  + e.Text + textBox.Text.Substring(textBox.CaretIndex);


UIButton action in table view cell

As Apple DOC

Returns the target object that responds to an action.

You can't use that method to set target for UIButton.
Try addTarget(_:action:forControlEvents:) method

Call parent method from child class c#

To follow up on the comment by suhendri to Rory McCrossan answer. Here is an Action delegate example:

In child add:

public Action UpdateProgress;  // In place of event handler declaration
                               // declare an Action delegate
private LoadData() {
    this.UpdateProgress();    // call to Action delegate - MyMethod in
                              // parent

In parent add:

// The 3 lines in the parent becomes:
ChildClass child = new ChildClass();
child.UpdateProgress = this.MyMethod;  // assigns MyMethod to child delegate

Amazon S3 - HTTPS/SSL - Is it possible?

This is a response I got from their Premium Services


This is actually a issue with the way SSL validates names containing a period, '.', > character. We've documented this behavior here:

The only straight-forward fix for this is to use a bucket name that does not contain that character. You might instead use a bucket named 'furniture-retailcatalog-us'. This would allow you use HTTPS with

You could, of course, put a CNAME DNS record to make that more friendly. For example, IN CNAME

Hope that helps. Let us know if you have any other questions.

Amazon Web Services

Unfortunately your "friendly" CNAME will cause host name mismatch when validating the certificate, therefore you cannot really use it for a secure connection. A big missing feature of S3 is accepting custom certificates for your domains.

UPDATE 10/2/2012

From @mpoisot:

The link Amazon provided no longer says anything about https. I poked around in the S3 docs and finally found a small note about it on the Virtual Hosting page:

UPDATE 6/17/2013

From @Joseph Lust:

Just got it! Check it out and sign up for an invite:

Programmatically stop execution of python script?

You want sys.exit(). From Python's docs:

>>> import sys
>>> print sys.exit.__doc__

Exit the interpreter by raising SystemExit(status).
If the status is omitted or None, it defaults to zero (i.e., success).
If the status is numeric, it will be used as the system exit status.
If it is another kind of object, it will be printed and the system
exit status will be one (i.e., failure).

So, basically, you'll do something like this:

from sys import exit

# Code!

exit(0) # Successful exit

Angular 4.3 - HttpClient set params

This solutions working for me,

let params = new HttpParams(); Object.keys(data).forEach(p => { params = params.append(p.toString(), data[p].toString()); });

bash script read all the files in directory

To write it with a while loop you can do:

ls -f /var | while read -r file; do cmd $file; done

The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

  • You can also use the file extension to check for the filetype.
  • More simpler way would be to do something as given below inside add :

    add : function (e,data){
       var extension = data.originalFiles[0].name.substr( 
       (data.originalFiles[0].name.lastIndexOf('.') +1) );
                    case 'csv':
                    case 'xls':
                    case 'xlsx':
                        data.url = <Your URL>; 
                        alert("File type not accepted");

Java - JPA - @Version annotation

Every time an entity is updated in the database the version field will be increased by one. Every operation that updates the entity in the database will have appended WHERE version = VERSION_THAT_WAS_LOADED_FROM_DATABASE to its query.

In checking affected rows of your operation the jpa framework can make sure there was no concurrent modification between loading and persisting your entity because the query would not find your entity in the database when it's version number has been increased between load and persist.

Difference between numpy dot() and Python 3.5+ matrix multiplication @

The answer by @ajcr explains how the dot and matmul (invoked by the @ symbol) differ. By looking at a simple example, one clearly sees how the two behave differently when operating on 'stacks of matricies' or tensors.

To clarify the differences take a 4x4 array and return the dot product and matmul product with a 3x4x2 'stack of matricies' or tensor.

import numpy as np
fourbyfour = np.array([

threebyfourbytwo = np.array([

print('4x4*3x4x2 dot:\n {}\n'.format(,threebyfourbytwo)))
print('4x4*3x4x2 matmul:\n {}\n'.format(np.matmul(fourbyfour,threebyfourbytwo)))

The products of each operation appear below. Notice how the dot product is,

...a sum product over the last axis of a and the second-to-last of b

and how the matrix product is formed by broadcasting the matrix together.

4x4*3x4x2 dot:
 [[[232 152]
  [125 112]
  [125 112]]

 [[172 116]
  [123  76]
  [123  76]]

 [[442 296]
  [228 226]
  [228 226]]

 [[962 652]
  [465 512]
  [465 512]]]

4x4*3x4x2 matmul:
 [[[232 152]
  [172 116]
  [442 296]
  [962 652]]

 [[125 112]
  [123  76]
  [228 226]
  [465 512]]

 [[125 112]
  [123  76]
  [228 226]
  [465 512]]]

How can I use optional parameters in a T-SQL stored procedure?

Extend your WHERE condition:

    (FirstName = ISNULL(@FirstName, FirstName)
    OR COALESCE(@FirstName, FirstName, '') = '')
AND (LastName = ISNULL(@LastName, LastName)
    OR COALESCE(@LastName, LastName, '') = '')
AND (Title = ISNULL(@Title, Title)
    OR COALESCE(@Title, Title, '') = '')

i. e. combine different cases with boolean conditions.

does linux shell support list data structure?

It supports lists, but not as a separate data structure (ignoring arrays for the moment).

The for loop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:

for i in 1 2 3; do
    echo "$i"

or via parameter expansion:

listVar="1 2 3"
for i in $listVar; do
    echo "$i"

or command substitution:

for i in $(echo 1; echo 2; echo 3); do
    echo "$i"

An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:

array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do   # The quotes are necessary here
    echo "$i"

list='"item 1" "item 2" "item 3"'
for i in $list; do
    echo $i
for i in "$list"; do
    echo $i
for i in ${array[@]}; do
    echo $i

Could not load file or assembly '***.dll' or one of its dependencies

I ran into this recently. It turned out that the old DLL was compiled with a previous version (Visual Studio 2008) and was referencing that version of the dynamic runtime libraries. I was trying to run it on a system that only had .NET 4.0 on it and I'd never installed any dynamic runtime libraries. The solution? I recompiled the DLL to link the static runtime libraries.

Check your application error log in Event Viewer (EVENTVWR.EXE). It will give you more information on the error and will probably point you at the real cause of the problem.

How to use string.substr() function?

If I am correct, the second parameter of substr() should be the length of the substring. How about

b = a.substr(i,2);


Is it possible to have placeholders in strings.xml for runtime values?

Supplemental Answer

When I first saw %1$s and %2$d in the accepted answer, it made no sense. Here is a little more explanation.

They are called format specifiers. In the xml string they are in the form of

  • %: The percent sign marks the beginning of the format specifier.
  • parameter index: This is a number followed by a dollar sign. If you had three parameters that you wanted to insert into the string, then they would be called 1$, 2$, and 3$. The order you place them in the resource string doesn't matter, only the order that you supply the parameters.
  • format type: There are a lot of ways that you can format things (see the documentation). Here are some common ones:

    • s string
    • d decimal integer
    • f floating point number


We will create the following formatted string where the gray parts are inserted programmatically.

My sister Mary is 12 years old.


<string name="my_xml_string">My sister %1$s is %2$d years old.</string>

String myString = "Mary";
int myInt = 12;
String formatted = getString(R.string.my_xml_string, myString, myInt);


  • I could use getString because I was in an Activity. You can use context.getResources().getString(...) if it is not available.
  • String.format() will also format a String.
  • The 1$ and 2$ terms don't need to be used in that order. That is, 2$ can come before 1$. This is useful when internationalizing an app for languages that use a different word order.
  • You can use a format specifier like %1$s multiple times in the xml if you want to repeat it.
  • Use %% to get the actual % character.
  • For more details read the following helpful tutorial: Android SDK Quick Tip: Formatting Resource Strings

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

Try to remove any trace of cocoapods pods using pod deintegrate then Run pod install

Executing JavaScript without a browser?

Well there is JavaScript as OSA, an extension that provides JavaScript as an alternative to appleScript. I've been using that about 10 years ago, don't know if it's still working with current OS versions

Find if a String is present in an array

If you can organize the values in the array in sorted order, then you can use Arrays.binarySearch(). Otherwise you'll have to write a loop and to a linear search. If you plan to have a large (more than a few dozen) strings in the array, consider using a Set instead.

Deserialize JSON into C# dynamic object?

To get an ExpandoObject:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

Container container = JsonConvert.Deserialize<Container>(jsonAsString, new ExpandoObjectConverter());

window.onload vs document.onload

window.onload however they are often the same thing. Similarly body.onload becomes window.onload in IE.

How to remove new line characters from a string?

I know this is an old post, however I thought I'd share the method I use to remove new line characters.

s.Replace(Environment.NewLine, "");


MSDN String.Replace Method and MSDN Environment.NewLine Property

How do you Encrypt and Decrypt a PHP String?

Historical Note: This was written at the time of PHP4. This is what we call "legacy code" now.

I have left this answer for historical purposes - but some of the methods are now deprecated, DES encryption method is not a recommended practice, etc.

I have not updated this code for two reasons: 1) I no longer work with encryption methods by hand in PHP, and 2) this code still serves the purpose it was intended for: to demonstrate the minimum, simplistic concept of how encryption can work in PHP.

If you find a similarly simplistic, "PHP encryption for dummies" kind of source that can get people started in 10-20 lines of code or less, let me know in comments.

Beyond that, please enjoy this Classic Episode of early-era PHP4 minimalistic encryption answer.

Ideally you have - or can get - access to the mcrypt PHP library, as its certainly popular and very useful a variety of tasks. Here's a run down of the different kinds of encryption and some example code: Encryption Techniques in PHP

//Listing 3: Encrypting Data Using the mcrypt_ecb Function 

echo("<h3> Symmetric Encryption </h3>"); 
$key_value = "KEYVALUE"; 
$plain_text = "PLAINTEXT"; 
$encrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $plain_text, MCRYPT_ENCRYPT); 
echo ("<p><b> Text after encryption : </b>"); 
echo ( $encrypted_text ); 
$decrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text, MCRYPT_DECRYPT); 
echo ("<p><b> Text after decryption : </b>"); 
echo ( $decrypted_text ); 

A few warnings:

1) Never use reversible, or "symmetric" encryption when a one-way hash will do.

2) If the data is truly sensitive, like credit card or social security numbers, stop; you need more than any simple chunk of code will provide, but rather you need a crypto library designed for this purpose and a significant amount of time to research the methods necessary. Further, the software crypto is probably <10% of security of sensitive data. It's like rewiring a nuclear power station - accept that the task is dangerous and difficult and beyond your knowledge if that's the case. The financial penalties can be immense, so better to use a service and ship responsibility to them.

3) Any sort of easily implementable encryption, as listed here, can reasonably protect mildly important information that you want to keep from prying eyes or limit exposure in the case of accidental/intentional leak. But seeing as how the key is stored in plain text on the web server, if they can get the data they can get the decryption key.

Be that as it may, have fun :)

Listing information about all database files in SQL Server

You can also try this.

 select db_name(dbid) dbname, filename from sys.sysaltfiles

Get a filtered list of files in a directory

import glob

jpgFilenamesList = glob.glob('145592*.jpg')

See glob in python documenttion

How can I pass an argument to a PowerShell script?

You can also define a variable directly in the PowerShell command line and then execute the script. The variable will be defined there, too. This helped me in a case where I couldn't modify a signed script.


 PS C:\temp> $stepsize = 30
 PS C:\temp> .\itunesForward.ps1

with iTunesForward.ps1 being

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $stepsize

How to change the default collation of a table?

may need to change the SCHEMA not only table

ALTER SCHEMA `<database name>`  DEFAULT CHARACTER SET utf8mb4  DEFAULT COLLATE utf8mb4_unicode_ci (as Rich said - utf8mb4);

(mariaDB 10)

How to get file path from OpenFileDialog and FolderBrowserDialog?

Your choofdlog holds a FileName and FileNames (for multi-selection) containing the file paths, after the ShowDialog() returns.

Calculating time difference in Milliseconds

No, it doesn't mean it's taking 0ms - it shows it's taking a smaller amount of time than you can measure with currentTimeMillis(). That may well be 10ms or 15ms. It's not a good method to call for timing; it's more appropriate for getting the current time.

To measure how long something takes, consider using System.nanoTime instead. The important point here isn't that the precision is greater, but that the resolution will be greater... but only when used to measure the time between two calls. It must not be used as a "wall clock".

Note that even System.nanoTime just uses "the most accurate timer on your system" - it's worth measuring how fine-grained that is. You can do that like this:

public class Test {
    public static void main(String[] args) throws Exception {

        long[] differences = new long[5];
        long previous = System.nanoTime();
        for (int i = 0; i < 5; i++) {
            long current;
            while ((current = System.nanoTime()) == previous) {
                // Do nothing...
            differences[i] = current - previous;
            previous = current;            

        for (long difference : differences) {

On my machine that shows differences of about 466 nanoseconds... so I can't possibly expect to measure the time taken for something quicker than that. (And other times may well be roughly multiples of that amount of time.)

Is it possible to specify a different ssh port when using rsync?

Your command line should look like this:

rsync -rvz -e 'ssh -p 2222' --progress ./dir user@host:/path

this works fine - I use it all the time without needing any new firewall rules - just note the SSH command itself is enclosed in quotes.

Unix epoch time to Java Date object


Using the java.time framework built into Java 8 and later.

import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;

long epoch = Long.parseLong("1081157732");
Instant instant = Instant.ofEpochSecond(epoch);
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); # ZonedDateTime = 2004-04-05T09:35:32Z[UTC]

In this case you should better use ZonedDateTime to mark it as date in UTC time zone because Epoch is defined in UTC in Unix time used by Java.

ZoneOffset contains a handy constant for the UTC time zone, as seen in last line above. Its superclass, ZoneId can be used to adjust into other time zones.

ZoneId zoneId = ZoneId.of( "America/Montreal" );

How do I get multiple subplots in matplotlib?

You might be interested in the fact that as of matplotlib version 2.1 the second code from the question works fine as well.

From the change log:

Figure class now has subplots method The Figure class now has a subplots() method which behaves the same as pyplot.subplots() but on an existing figure.


import matplotlib.pyplot as plt

fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)

Bootstrap with jQuery Validation Plugin

This makes up the fields

                debug: false,
                errorElement: "span",
                errorClass: "help-block",
                highlight: function (element, errorClass, validClass) {
                unhighlight: function (element, errorClass, validClass) {
                errorPlacement: function (error, element) {
                    if (element.parent('.input-group').length || element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
                    } else {
                // Specify the validation rules
                rules: {
                        'campo1[]': 'required',
                        'campo2[]': 'required',
                        'campo3[]': 'required',
                        'campo4[]': 'required',
                        'campo5[]': 'required'

                submitHandler: function (form) {

Explicitly select items from a list or tuple

What about this:

from operator import itemgetter
('foo', 'baz', 'quux')

How to change default format at created_at and updated_at value laravel

Laravel 4.x and 5.0

To change the time in the database use:

Providing A Custom Timestamp Format

If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:

class User extends Eloquent {

    protected function getDateFormat()
        return 'U';


Laravel 5.1+

If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:

class Flight extends Model
     * The storage format of the model's date columns.
     * @var string
    protected $dateFormat = 'U';

Convert bytes to bits in python

using python format string syntax

>>> mybyte = bytes.fromhex("0F") # create my byte using a hex string
>>> binary_string = "{:08b}".format(int(mybyte.hex(),16))
>>> print(binary_string)

The second line is where the magic happens. All byte objects have a .hex() function, which returns a hex string. Using this hex string, we convert it to an integer, telling the int() function that it's a base 16 string (because hex is base 16). Then we apply formatting to that integer so it displays as a binary string. The {:08b} is where the real magic happens. It is using the Format Specification Mini-Language format_spec. Specifically it's using the width and the type parts of the format_spec syntax. The 8 sets width to 8, which is how we get the nice 0000 padding, and the b sets the type to binary.

I prefer this method over the bin() method because using a format string gives a lot more flexibility.

ActionBarActivity: cannot be resolved to a type

There is a mistake in your 'andrroid-sdk' folder. You selected some features while creating new project which need some components to import. It is needed to download a special android library and place it in android-sdk folder. For me it works fine: 1-Create a folder with name extras in your android-sdk folder 2-Create a folder with name android in extras 3-Download this file.(In my case I need this library) 4-Unzip it and copy the content (support folder) in the current android folder 5-close Eclipse and start it again 6-create your project again

I hope it to work for you.

Convert from enum ordinal to enum type

This is almost certainly a bad idea. Certainly if the ordinal is de-facto persisted (e.g. because someone has bookmarked the URL) - it means that you must always preserve the enum ordering in future, which may not be obvious to code maintainers down the line.

Why not encode the enum using (and decode via ReportTypeEnum.valueOf(s)) instead?

Multi-key dictionary in c#?

I'm currently simply concatenating the keys into a single string as a workaround. Of course, this will not work on non-string keys. Would love to know the answer as well.

Excel is not updating cells, options > formula > workbook calculation set to automatic

I had this happen in a worksheet today. Neither F9 nor turning on Iterative Calculation made the cells in question update, but double-clicking the cell and pressing Enter did. I searched the Excel Help and found this in the help article titled Change formula recalculation, iteration, or precision:

Recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.

Check dependent formulas, and then recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.

So I tried CtrlShiftAltF9, and sure enough, all of my non-recalculating formulas finally recalculated!

getContext is not a function

I got the same error because I had accidentally used <div> instead of <canvas> as the element on which I attempt to call getContext.

Installing Apache Maven Plugin for Eclipse

m2eclipse has moved from sonatype to eclipse.

The correct update site is

If this is not working, one possibility is you have an older version of Eclipse (< 3.6). The other - if you see timeout related errors - could be that you are behind a proxy server.

Template not provided using create-react-app

After using this command:

yarn global upgrade create-react-app

I then tried:

yarn create-react-app my-app but it didn't work for me.

This worked though:

npx create-react-app my-app 

How to Diff between local uncommitted changes and origin

If you want to compare files visually you can use:

git difftool

It will start your diff app automatically for each changed file.

PS: If you did not set a diff app, you can do it like in the example below(I use Winmerge):

git config --global merge.tool winmerge
git config --replace --global mergetool.winmerge.cmd "\"C:\Program Files (x86)\WinMerge\WinMergeU.exe\" -e -u -dl \"Base\" -dr \"Mine\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""
git config --global mergetool.prompt false

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

You can make it a non-submitting button (<button type="button">) and hook something like window.location = '' into its onclick handler. This does not work without javascript enabled though.

Or you can make it a submit button, and do a redirect on the server, although this obviously requires some kind of server-side logic, but the upside is that is doesn't require javascript.

(actually, forget the second solution - if you can't use a form, the submit button is out)

Running powershell script within python script, how to make python print the powershell output while it is running

  1. Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this.

    Set-ExecutionPolicy RemoteSigned
  2. Run this python script on your powershell script

    # -*- coding: iso-8859-1 -*-
    import subprocess, sys
    p = subprocess.Popen(["powershell.exe", 

This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.

Hello World

Selecting Values from Oracle Table Variable / Array?


In Oracle these are created once and then when invoked the data is private to your session.

Oracle Documentation Link

Try something like this...

   ( number_column   NUMBER( 10, 0 )

   INSERT INTO temp_number
      ( number_column )
      ( select distinct sgbstdn_pidm 
          from sgbstdn 
         where sgbstdn_majr_code_1 = 'HS04' 
           and sgbstdn_program_1 = 'HSCOMPH' 

    FOR pidms_rec IN ( SELECT number_column FROM temp_number )
        -- Do something here
    END LOOP; 

How to run a method every X seconds

With Kotlin, we can now make a generic function for this!

object RepeatHelper {
    fun repeatDelayed(delay: Long, todo: () -> Unit) {
        val handler = Handler()
        handler.postDelayed(object : Runnable {
            override fun run() {
                handler.postDelayed(this, delay)
        }, delay)

And to use, just do:

val delay = 1000L
RepeatHelper.repeatDelayed(delay) {

Use Toast inside Fragment

When making a toast in fragment do as following:

Toast.makeText(getActivity(),"Message", Toast.LENGTH_SHORT).show();

When class is extending fragment it is necessary to use getActivity() since fragment is a subclass of activity.


Regular expression for only characters a-z, A-Z

This /[^a-z]/g solves the problem.

function pangram(str) {
    let regExp = /[^a-z]/g;
    let letters = str.toLowerCase().replace(regExp, '');
    document.getElementById('letters').innerHTML = letters;
pangram('GHV 2@# %hfr efg uor7 489(*&^% knt lhtkjj ngnm!@#$%^&*()_');
<h4 id="letters"></h4>

How to configure logging to syslog in Python?


# -*- coding: utf-8 -*-

Implements a new handler for the logging module which uses the pure syslog python module.

@author:  Luis Martin Gil
@year: 2013
import logging
import syslog

class SysLogLibHandler(logging.Handler):
    """A logging handler that emits messages to syslog.syslog."""
    FACILITY = [syslog.LOG_LOCAL0,
    def __init__(self, n):
        """ Pre. (0 <= n <= 7) """
            syslog.openlog(logoption=syslog.LOG_PID, facility=self.FACILITY[n])
        except Exception , err:
                syslog.openlog(syslog.LOG_PID, self.FACILITY[n])
            except Exception, err:
                    syslog.openlog('my_ident', syslog.LOG_PID, self.FACILITY[n])
        # We got it

    def emit(self, record):

if __name__ == '__main__':
    """ Lets play with the log class. """
    # Some variables we need
    _id = 'myproj_v2.0'
    logStr = 'debug'
    logFacilityLocalN = 1

    # Defines a logging level and logging format based on a given string key.
    LOG_ATTR = {'debug': (logging.DEBUG,
                          _id + ' %(levelname)-9s %(name)-15s %(threadName)-14s +%(lineno)-4d %(message)s'),
                'info': (logging.INFO,
                         _id + ' %(levelname)-9s %(message)s'),
                'warning': (logging.WARNING,
                            _id + ' %(levelname)-9s %(message)s'),
                'error': (logging.ERROR,
                          _id + ' %(levelname)-9s %(message)s'),
                'critical': (logging.CRITICAL,
                             _id + ' %(levelname)-9s %(message)s')}
    loglevel, logformat = LOG_ATTR[logStr]

    # Configuring the logger
    logger = logging.getLogger()

    # Clearing previous logs
    logger.handlers = []

    # Setting formaters and adding handlers.
    formatter = logging.Formatter(logformat)
    handlers = []
    for h in handlers:

    # Yep!
    logging.debug('test debug')'test info')
    logging.warning('test warning')
    logging.error('test error')
    logging.critical('test critical')

How do I assert an Iterable contains elements with a certain property?

Alternatively to hasProperty you can try hamcrest-more-matchers where matcher with extracting function. In your case it will look like:

import static com.github.seregamorph.hamcrest.MoreMatchers.where;

assertThat(myClass.getMyItems(), contains(
    where(MyItem::getName, is("foo")), 
    where(MyItem::getName, is("bar"))

The advantages of this approach are:

  • It is not always possible to verify by field if the value is computed in get-method
  • In case of mismatch there should be a failure message with diagnostics (pay attention to resolved method reference MyItem.getName:
Expected: iterable containing [Object that matches is "foo" after call
MyItem.getName, Object that matches is "bar" after call MyItem.getName]
     but: item 0: was "wrong-name"
  • It works in Java 8, Java 11 and Java 14

Why is Maven downloading the maven-metadata.xml every time?

It is possibly to use the flag -o,--offline "Work offline" to prevent that.

Like this:

maven compile -o

"echo -n" prints "-n"

Just for the most popular linux Ubuntu & it's bash:

  1. Check which shell are you using? Mostly below works, else see this:

    echo $0

  2. If above prints bash, then below will work:

    printf "hello with no new line printed at end"
    echo -n "hello with no new line printed at end"

PHP - Check if two arrays are equal

Compare them as other values:

if($array_a == $array_b) {
  //they are the same

You can read about all array operators here: Note for example that === also checks that the types and order of the elements in the arrays are the same.

JUnit Eclipse Plugin?

You should be able to add the Java Development Tools by selecting 'Help' -> 'Install New Software', there you select the 'Juno' update site, then 'Programming Languages' -> 'Eclipse Java Development Tools'.

After that, you will be able to run your JUnit tests with 'Right Click' -> 'Run as' -> 'JUnit test'.

JavaScript Number Split into individual digits

This is my short solution.. with sum of number

    function sum (num) {
    let sNumber = num
        .reduce((el1, el2) => {
            return Number(el1) + Number(el2)
        }, 0)
        return sNumber


How do I get the YouTube video ID from a URL?

videoId = videoUrl.split('v=')[1].substring(0,11);

What are the options for (keyup) in Angular2?

The keyCode is deprecated you can use key property in the KeyboardEvent

<textarea (keydown)=onKeydownEvent($event)></textarea>


onKeydownEvent($event: KeyboardEvent){

    // you can use the following for checkig enter key pressed or not
    if ($event.key === 'Enter') {
      console.log($event.key); // Enter

    if ($event.key === 'Enter' && event.shiftKey) {
           //This is 'Shift+Enter' 

How can I convert a long to int in Java?

Long x = 100L;
int y = x.intValue();

How to store image in SQL Server database tables column

give this a try,

insert into tableName (ImageColumn) 
SELECT BulkColumn 
FROM Openrowset( Bulk '', Single_Blob) as img


enter image description here


enter image description here

Can I set state inside a useEffect hook

useEffect can hook on a certain prop or state. so, the thing you need to do to avoid infinite loop hook is binding some variable or state to effect

For Example:

useEffect(myeffectCallback, [])

above effect will fire only once the component has rendered. this is similar to componentDidMount lifecycle

const [something, setSomething] = withState(0)
const [myState, setMyState] = withState(0)
useEffect(() => {
}, myState)

above effect will fire only my state has changed this is similar to componentDidUpdate except not every changing state will fire it.

You can read more detail though this link

ASP.NET Button to redirect to another page

You can either do a Response.Redirect("YourPage.aspx"); or a Server.Transfer("YourPage.aspx"); on your button click event. So it's gonna be like the following:

protected void btnConfirm_Click(object sender, EventArgs e)

wget: unable to resolve host address `http'

If using Vagrant try reloading your box. This solved my issue.

Sort JavaScript object by key

    (acc,curr) => ({...acc, [curr]:unordered[curr]})
    , {}

Export pictures from excel file into jpg using VBA

If i remember correctly, you need to use the "Shapes" property of your sheet.

Each Shape object has a TopLeftCell and BottomRightCell attributes that tell you the position of the image.

Here's a piece of code i used a while ago, roughly adapted to your needs. I don't remember the specifics about all those ChartObjects and whatnot, but here it is:

For Each oShape In ActiveSheet.Shapes
    strImageName = ActiveSheet.Cells(oShape.TopLeftCell.Row, 1).Value
    'Picture format initialization
    Selection.ShapeRange.PictureFormat.Contrast = 0.5: Selection.ShapeRange.PictureFormat.Brightness = 0.5: Selection.ShapeRange.PictureFormat.ColorType = msoPictureAutomatic: Selection.ShapeRange.PictureFormat.TransparentBackground = msoFalse: Selection.ShapeRange.Fill.Visible = msoFalse: Selection.ShapeRange.Line.Visible = msoFalse: Selection.ShapeRange.Rotation = 0#: Selection.ShapeRange.PictureFormat.CropLeft = 0#: Selection.ShapeRange.PictureFormat.CropRight = 0#: Selection.ShapeRange.PictureFormat.CropTop = 0#: Selection.ShapeRange.PictureFormat.CropBottom = 0#: Selection.ShapeRange.ScaleHeight 1#, msoTrue, msoScaleFromTopLeft: Selection.ShapeRange.ScaleWidth 1#, msoTrue, msoScaleFromTopLeft
    '/Picture format initialization
    Set oDia = ActiveSheet.ChartObjects.Add(0, 0, oShape.Width, oShape.Height)
    Set oChartArea = oDia.Chart
    With oChartArea
        .Export ("H:\Webshop_Zpider\Strukturbildene\" & strImageName & ".jpg")
    End With
    oDia.Delete 'oChartArea.Delete

How to distinguish between left and right mouse click with jQuery

there is also a way, to do it without JQuery!

check out this:

document.addEventListener("mousedown", function(evt) {
    switch(evt.buttons) {
      case 1: // left mouse
      case 2: // right mouse
      case 3: // middle mouse <- I didn't tested that, I just got a touchpad

Batch script loop

Here is a template script I will use.

@echo off
goto Loop

goto Loop


What this does is when it starts it turns off echo then after that it runs the "Loop" but in that place it keeps going to "Loop" (I hope this helps.)

How to open some ports on Ubuntu?

Ubuntu these days comes with ufw - Uncomplicated Firewall. ufw is an easy-to-use method of handling iptables rules.

Try using this command to allow a port

sudo ufw allow 1701

To test connectivity, you could try shutting down the VPN software (freeing up the ports) and using netcat to listen, like this:

nc -l 1701

Then use telnet from your Windows host and see what shows up on your Ubuntu terminal. This can be repeated for each port you'd like to test.

How to get the real and total length of char * (char array)?

You can find the length of a char* string like this:

char* mystring = "Hello World";
int length = sprintf(mystring, "%s", mystring);

sprintf() prints mystring onto itself, and returns the number of characters printed.

How to add a color overlay to a background image?

Try this, it's simple and clear. I have found it from here :

.tinted-image {

  width: 300px;
  height: 200px;

    /* top, transparent red */ 
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    /* bottom, image */

List method to delete last element in list as well as all elements

To delete the last element from the list just do this.

a = [1,2,3,4,5]
a = a[:-1]
#Output [1,2,3,4] 

Saving ssh key fails

For MacOS

Open terminal and make sure you have .ssh directory.

On your home(~) folder enter ls -hal and you will see all hidden directories and make sure you have .ssh directory, if not do mkdir .ssh

then enter this ssh-keygen -t rsa -C "[email protected]"

then you have: Generating public/private rsa key pair. Enter file in which to save the key (/Users/YOURUSERNAME/.ssh/id_rsa):

press Enter (you don't need to enter nothing if you agree with that path or you need to enter your path from root of volume)

then follow answer what is gonna ask press Enter.

Check it here

Convert js Array() to JSon object for use with JQuery .ajax

Don't make it an Array if it is not an Array, make it an object:

var saveData = {};
saveData.a = 2;
saveData.c = 1;

// equivalent to...
var saveData = {a: 2, c: 1}

// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;

Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.

curl : (1) Protocol https not supported or disabled in libcurl

Looks like there are so many Answers already but the issue I faced was with double quotes. There is a difference in between:



Changing the 1 st double quote to the second worked for me, below is the sample curl:

curl -X PUT -u xxx:xxx -T test.txt ""

Practical uses of git reset --soft?

While I really like the answers in this thread, I use git reset --soft for a slightly different, but a very practical scenario nevertheless.

I use an IDE for development which has a good diff tool for showing changes (staged and unstaged) after my last commit. Now, most of my tasks involve multiple commits. For example, let's say I make 5 commits to complete a particular task. I use the diff tool in the IDE during every incremental commit from 1-5 to look at my changes from the last commit. I find it a very helpful way to review my changes before committing.

But at the end of my task, when I want to see all my changes together (from before 1st commit), to do a self code-review before making a pull request, I would only see the changes from my previous commit (after commit 4) and not changes from all the commits of my current task.

So I use git reset --soft HEAD~4 to go back 4 commits. This lets me see all the changes together. When I am confident of my changes, I can then do git reset HEAD@{1} and push it to remote confidently.

How to generate a random integer number from within a range

Here is a formula if you know the max and min values of a range, and you want to generate numbers inclusive in between the range:

r = (rand() % (max + 1 - min)) + min

How to select current date in Hive SQL

To extract the year from current date


IBM Netezza

extract(year from now())



I want to execute shell commands from Maven's pom.xml

The problem here is that I don't know what is expected. With your current setup, invoking the plugin on the command line would just work:

$ mvn exec:exec
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Q3491937
[INFO]    task-segment: [exec:exec]
[INFO] ------------------------------------------------------------------------
[INFO] [exec:exec {execution: default-cli}]
[INFO] laptop
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------

The global configuration is used, the hostname command is executed (laptop is my hostname). In other words, the plugin works as expected.

Now, if you want a plugin to get executed as part of the build, you have to bind a goal on a specific phase. For example, to bind it on compile:


And then:

$ mvn compile
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building Q3491937
[INFO]    task-segment: [compile]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources {execution: default-resources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/pascal/Projects/Q3491937/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [exec:exec {execution: some-execution}]
[INFO] laptop
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------

Note that you can specify a configuration inside an execution.

Remove Identity from a column in a table

If you want to do this without adding and populating a new column, without reordering the columns, and with almost no downtime because no data is changing on the table, let's do some magic with partitioning functionality (but since no partitions are used you don't need Enterprise edition):

  1. Remove all foreign keys that point to this table
  2. Script the table to be created; rename everything e.g. 'MyTable2', 'MyIndex2', etc. Remove the IDENTITY specification.
  3. You should now have two "identical"-ish tables, one full, the other empty with no IDENTITY.
  4. Run ALTER TABLE [Original] SWITCH TO [Original2]
  5. Now your original table will be empty and the new one will have the data. You have switched the metadata for the two tables (instant).
  6. Drop the original (now-empty table), exec sys.sp_rename to rename the various schema objects back to the original names, and then you can recreate your foreign keys.

For example, given:

, Value NVARCHAR(300)
CREATE NONCLUSTERED INDEX IX_Original_Value ON Original (Value);

SELECT 'abcd'
SELECT 'defg';

You can do the following:

--create new table with no IDENTITY
, Value NVARCHAR(300)
CREATE NONCLUSTERED INDEX IX_Original_Value2 ON Original2 (Value);

--data before switch
SELECT 'Original', *
FROM Original
SELECT 'Original2', *
FROM Original2;

ALTER TABLE Original SWITCH TO Original2;

--data after switch
SELECT 'Original', *
FROM Original
SELECT 'Original2', *
FROM Original2;

--clean up 
EXEC sys.sp_rename 'Original2.IX_Original_Value2', 'IX_Original_Value', 'INDEX';
EXEC sys.sp_rename 'Original2', 'Original', 'OBJECT';

UPDATE Original
SET Id = Id + 1;

FROM Original;

Why is Spring's ApplicationContext.getBean considered bad?

I've only found two situations where getBean() was required:

Others have mentioned using getBean() in main() to fetch the "main" bean for a standalone program.

Another use I have made of getBean() are in situations where an interactive user configuration determines the bean makeup for a particular situation. So that, for instance, part of the boot system loops through a database table using getBean() with a scope='prototype' bean definition and then setting additional properties. Presumably, there is a UI that adjusts the database table that would be friendlier than attempting to (re)write the application context XML.

Can I have multiple primary keys in a single table?

A table can have multiple candidate keys. Each candidate key is a column or set of columns that are UNIQUE, taken together, and also NOT NULL. Thus, specifying values for all the columns of any candidate key is enough to determine that there is one row that meets the criteria, or no rows at all.

Candidate keys are a fundamental concept in the relational data model.

It's common practice, if multiple keys are present in one table, to designate one of the candidate keys as the primary key. It's also common practice to cause any foreign keys to the table to reference the primary key, rather than any other candidate key.

I recommend these practices, but there is nothing in the relational model that requires selecting a primary key among the candidate keys.

EL access a map value by Integer key

Initial answer (EL 2.1, May 2009)

As mentioned in this java forum thread:

Basically autoboxing puts an Integer object into the Map. ie:

map.put(new Integer(0), "myValue")

EL (Expressions Languages) evaluates 0 as a Long and thus goes looking for a Long as the key in the map. ie it evaluates:

map.get(new Long(0))

As a Long is never equal to an Integer object, it does not find the entry in the map.
That's it in a nutshell.

Update since May 2009 (EL 2.2)

Dec 2009 saw the introduction of EL 2.2 with JSP 2.2 / Java EE 6, with a few differences compared to EL 2.1.
It seems ("EL Expression parsing integer as long") that:

you can call the method intValue on the Long object self inside EL 2.2:

<c:out value="${map[(1).intValue()]}"/>

That could be a good workaround here (also mentioned below in Tobias Liefke's answer)

Original answer:

EL uses the following wrappers:

Terms                  Description               Type
null                   null value.               -
123                    int value.                java.lang.Long
123.00                 real value.               java.lang.Double
"string" ou 'string'   string.                   java.lang.String
true or false          boolean.                  java.lang.Boolean

JSP page demonstrating this:

 <%@ taglib prefix="c" uri=""%>

 <%@ page import="java.util.*" %>

 <h2> Server Info</h2>
Server info = <%= application.getServerInfo() %> <br>
Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
Java version = <%= System.getProperty("java.vm.version") %><br>
  Map map = new LinkedHashMap();
  map.put("2", "String(2)");
  map.put(new Integer(2), "Integer(2)");
  map.put(new Long(2), "Long(2)");
  map.put(42, "AutoBoxedNumber");

  pageContext.setAttribute("myMap", map);  
  Integer lifeInteger = new Integer(42);
  Long lifeLong = new Long(42);  
  <h3>Looking up map in JSTL - integer vs long </h3>

  This page demonstrates how JSTL maps interact with different types used for keys in a map.
  Specifically the issue relates to autoboxing by java using map.put(1, "MyValue") and attempting to display it as ${myMap[1]}
  The map "myMap" consists of four entries with different keys: A String, an Integer, a Long and an entry put there by AutoBoxing Java 5 feature.       

  <table border="1">
    <tr><th>Key</th><th>value</th><th>Key Class</th></tr>
    <c:forEach var="entry" items="${myMap}" varStatus="status">

    <h4> Accessing the map</h4>    
    Evaluating: ${"${myMap['2']}"} = <c:out value="${myMap['2']}"/><br>
    Evaluating: ${"${myMap[2]}"}   = <c:out value="${myMap[2]}"/><br>    
    Evaluating: ${"${myMap[42]}"}   = <c:out value="${myMap[42]}"/><br>    

    As you can see, the EL Expression for the literal number retrieves the value against the java.lang.Long entry in the map.
    Attempting to access the entry created by autoboxing fails because a Long is never equal to an Integer

    lifeInteger = <%= lifeInteger %><br/>
    lifeLong = <%= lifeLong %><br/>
    lifeInteger.equals(lifeLong) : <%= lifeInteger.equals(lifeLong) %> <br>

PostgreSQL function for last inserted ID

I had this issue with Java and Postgres. I fixed it by updating a new Connector-J version.

postgresql-9.2-1002.jdbc4.jar Version 42.2.12

Html table tr inside td

Just add a new table in the td you want. Example:

<table border="1">
      <table border="1">

Trying to fire the onload event on script tag

I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload instruction was immediately evaluated, and then the $ usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).

So, I referred to this article : and attached a event listener to my script object.

var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
    console.log("script loaded :)");
script.src = "";

For my needs, it works fine now. Hope this can help others :)

Converting String To Float in C#

You can double.Parse("41.00027357629127");

Error: Cannot find module html

Install ejs if it is not.

npm install ejs

Then after just paste below two lines in your main file. (like app.js, main.js)

app.set('view engine', 'html');

app.engine('html', require('ejs').renderFile);