Programs & Examples On #Appassembler

The Application Assembler Plugin is a Maven plugin for generating scripts for starting java applications.

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

CSS white space at bottom of page despite having both min-height and height tag

Try setting the height of the html element to 100% as well.

html {
    min-height: 100%;
    overflow-y: scroll;
}    
body {
     min-height: 100%;
}

Reference from this answer..

Warning :-Presenting view controllers on detached view controllers is discouraged

I have almost the same problem. The reason was that I tried to present "some" controller on another and after animation was completed I was setting presented controller as root. After this operation all further controllers presenting bring me to the warning: "Presenting view controllers on detached view controllers is discouraged". And I solve this warning just settings "some" controller as root without any presentation at the begin.

Removed:

[[self rootController] presentViewController:controller animated:YES completion:^{

       [self window].rootViewController = controller;

       [[self window] makeKeyAndVisible];}];

Just make as root without any presentation:

 [[self window] setRootViewController:controller];

Why doesn't Dijkstra's algorithm work for negative weight edges?

Try Dijkstra's algorithm on the following graph, assuming A is the source node and D is the destination, to see what is happening:

Graph

Note that you have to follow strictly the algorithm definition and you should not follow your intuition (which tells you the upper path is shorter).

The main insight here is that the algorithm only looks at all directly connected edges and it takes the smallest of these edge. The algorithm does not look ahead. You can modify this behavior , but then it is not the Dijkstra algorithm anymore.

HTML entity for check mark

There is HTML entity &#10003 but it doesn't work in some older browsers.

EditText onClickListener in Android

The keyboard seems to pop up when the EditText gains focus. To prevent this, set focusable to false:

<EditText
    ...
    android:focusable="false"
    ... />

This behavior can vary on different manufacturers' Android OS flavors, but on the devices I've tested I have found this to to be sufficient. If the keyboard still pops up, using hints instead of text seems to help as well:

myEditText.setText("My text");    // instead of this...
myEditText.setHint("My text");    // try this

Once you've done this, your on click listener should work as desired:

myEditText.setOnClickListener(new OnClickListener() {...});

Using Mockito to mock classes with generic parameters

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

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

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

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

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

Add A Year To Today's Date

You can create a new date object with todays date using the following code:

_x000D_
_x000D_
var d = new Date();_x000D_
    console.log(d);
_x000D_
_x000D_
_x000D_ // => Sun Oct 11 2015 14:46:51 GMT-0700 (PDT)

If you want to create a date a specific time, you can pass the new Date constructor arguments

_x000D_
_x000D_
 var d = new Date(2014);_x000D_
    console.log(d)
_x000D_
_x000D_
_x000D_

// => Wed Dec 31 1969 16:00:02 GMT-0800 (PST)

If you want to take todays date and add a year, you can first create a date object, access the relevant properties, and then use them to create a new date object

_x000D_
_x000D_
var d = new Date();_x000D_
    var year = d.getFullYear();_x000D_
    var month = d.getMonth();_x000D_
    var day = d.getDate();_x000D_
    var c = new Date(year + 1, month, day);_x000D_
    console.log(c);
_x000D_
_x000D_
_x000D_

// => Tue Oct 11 2016 00:00:00 GMT-0700 (PDT)

You can read more about the methods on the date object on MDN

Date Object

What is the difference between null and System.DBNull.Value?

Null is similar to zero pointer in C++. So it is a reference which not pointing to any value.

DBNull.Value is completely different and is a constant which is returned when a field value contains NULL.

Remove Android App Title Bar

It's obvious, but the App Theme selection in design is just for display a draft during layout edition, is not related to real app looking in cell phone.

Just change the manifest file (AndroidManifest.xml) is not enough because the style need to be predefined is styles.xml. Also is useless change the layout files.

All proposed solution in Java or Kotlin has failed for me. Some of them crash the app. And if one never (like me) uses the title bar in app, the static solution is cleaner.

For me the only solution that works in 2019 (Android Studio 3.4.1) is:

in styles.xml (under app/res/values) add the lines:

   <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

After in AndroidManifest.xml (under app/manifests)

Replace

android:theme="@style/AppTheme">

by

android:theme="@style/AppTheme.NoActionBar">

Groovy Shell warning "Could not open/create prefs root node ..."

This is actually a JDK bug. It has been reported several times over the years, but only in 8139507 was it finally taken seriously by Oracle.

The problem was in the JDK source code for WindowsPreferences.java. In this class, both nodes userRoot and systemRoot were declared static as in:

/**
 * User root node.
 */
static final Preferences userRoot =
     new WindowsPreferences(USER_ROOT_NATIVE_HANDLE, WINDOWS_ROOT_PATH);

/**
 * System root node.
 */
static final Preferences systemRoot =
    new WindowsPreferences(SYSTEM_ROOT_NATIVE_HANDLE, WINDOWS_ROOT_PATH);

This means that the first time the class is referenced both static variables would be initiated and by this the Registry Key for HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs (= system tree) will be attempted to be created if it doesn't already exist.

So even if the user took every precaution in his own code and never touched or referenced the system tree, then the JVM would actually still try to instantiate systemRoot, thus causing the warning. It is an interesting subtle bug.

There's a fix committed to the JDK source in June 2016 and it is part of Java9 onwards. There's also a backport for Java8 which is in u202.

What you see is really a warning from the JDK's internal logger. It is not an exception. I believe that the warning can be safely ignored .... unless the user code is indeed wanting the system preferences, but that is very rarely the case.

Bonus info

The bug did not reveal itself in versions prior to Java 1.7.21, because up until then the JRE installer would create Registry key HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs for you and this would effectively hide the bug. On the other hand you've never really been required to run an installer in order to have a JRE on your machine, or at least this hasn't been Sun/Oracle's intent. As you may be aware Oracle has been distributing the JRE for Windows in .tar.gz format for many years.

Angular 4 - Select default value in dropdown [Reactive Forms]

In your component -

Make sure to initialize the formControl name country with a value.

For instance: Assuming that your form group name is myForm and _fb is FormBuilder instance then,

....
this.myForm = this._fb.group({
  country:[this.default]
})

and also try replacing [value] with [ngValue].

EDIT 1: If you are unable to initialize the value when declaring then set the value when you have the value like this.

this.myForm.controls.country.controls.setValue(this.country) 

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.

The steps are :

  1. In the address bar, type "chrome://net-internals/#hsts".
  2. Type the domain name in the text field below "Delete domain".
  3. Click the "Delete" button.
  4. Type the domain name in the text field below "Query domain".
  5. Click the "Query" button.
  6. Your response should be "Not found".

You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers

Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.

Edit : you have to repeat the steps every time you will go on the production site.

Function or sub to add new row and data to table

Minor variation of phillfri's answer which was already a variation of Geoff's answer: I added the ability to handle completely empty tables that contain no data for the Array Code.

Sub AddDataRow(tableName As String, NewData As Variant)
    Dim sheet As Worksheet
    Dim table As ListObject
    Dim col As Integer
    Dim lastRow As Range

    Set sheet = Range(tableName).Parent
    Set table = sheet.ListObjects.Item(tableName)

    'First check if the last row is empty; if not, add a row
    If table.ListRows.Count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.Count).Range
        If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
            table.ListRows.Add
        End If
    End If

    'Iterate through the last row and populate it with the entries from values()
    If table.ListRows.Count = 0 Then 'If table is totally empty, set lastRow as first entry
        table.ListRows.Add Position:=1
        Set lastRow = table.ListRows(1).Range
    Else
        Set lastRow = table.ListRows(table.ListRows.Count).Range
    End If
    For col = 1 To lastRow.Columns.Count
        If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
    Next col
End Sub

How to get an HTML element's style values in javascript?

You can make function getStyles that'll take an element and other arguments are properties that's values you want.

const convertRestArgsIntoStylesArr = ([...args]) => {
    return args.slice(1);
}

const getStyles = function () {
    const args = [...arguments];
    const [element] = args;

    let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);

    const styles = window.getComputedStyle(element);
    const stylesObj = stylesProps.reduce((acc, v) => {
        acc[v] = styles.getPropertyValue(v);
        return acc;
    }, {});

    return stylesObj;
};

Now, you can use this function like this:

const styles = getStyles(document.body, "height", "width");

OR

const styles = getStyles(document.body, ["height", "width"]);

Understanding the difference between Object.create() and new SomeFunction()

This:

var foo = new Foo();

and

var foo = Object.create(Foo.prototype);

are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as

function Foo() {
    alert("This constructor does not run with Object.create");
}

Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.

How to sparsely checkout only one single file from a git repository?

In git you do not 'checkout' files before you update them - it seems like this is what you are after.

Many systems like clearcase, csv and so on require you to 'checkout' a file before you can make changes to it. Git does not require this. You clone a repository and then make changes in your local copy of repository.

Once you updated files you can do:

git status

To see what files have been modified. You add the ones you want to commit to index first with (index is like a list to be checked in):

git add .

or

git add blah.c

Then do git status will show you which files were modified and which are in index ready to be commited or checked in.

To commit files to your copy of repository do:

git commit -a -m "commit message here"

See git website for links to manuals and guides.

Get the cartesian product of a series of lists?

Although there are many answers already, I would like to share some of my thoughts:

Iterative approach

def cartesian_iterative(pools):
  result = [[]]
  for pool in pools:
    result = [x+[y] for x in result for y in pool]
  return result

Recursive Approach

def cartesian_recursive(pools):
  if len(pools) > 2:
    pools[0] = product(pools[0], pools[1])
    del pools[1]
    return cartesian_recursive(pools)
  else:
    pools[0] = product(pools[0], pools[1])
    del pools[1]
    return pools
def product(x, y):
  return [xx + [yy] if isinstance(xx, list) else [xx] + [yy] for xx in x for yy in y]

Lambda Approach

def cartesian_reduct(pools):
  return reduce(lambda x,y: product(x,y) , pools)

Wait for a void async method

The best solution is to use async Task. You should avoid async void for several reasons, one of which is composability.

If the method cannot be made to return Task (e.g., it's an event handler), then you can use SemaphoreSlim to have the method signal when it is about to exit. Consider doing this in a finally block.

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

The problem is the std namespace you are missing. cout is in the std namespace.
Add using namespace std; after the #include

MySQL: How to set the Primary Key on phpMyAdmin?

You can view the INDEXES column below where you find a default PRIMARY KEY is set. If it is not set or you want to set any other variable as a PRIMARY KEY then , there is a dialog box below to create an index which asks for a column number ,either way you can create a new one or edit an existing one.The existing one shows up a edit button whee you can go and edit it and you're done save it and you are ready to go

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

Adding three months to a date in PHP

Following should work

$d = strtotime("+1 months",strtotime("2015-05-25"));
echo   date("Y-m-d",$d); // This will print **2015-06-25** 

Returning a boolean value in a JavaScript function

You could wrap your return value in the Boolean function

Boolean([return value])

That'll ensure all falsey values are false and truthy statements are true.

Add text at the end of each line

  1. You can also achieve this using the backreference technique

    sed -i.bak 's/\(.*\)/\1:80/' foo.txt
    
  2. You can also use with awk like this

    awk '{print $0":80"}' foo.txt > tmp && mv tmp foo.txt
    

What is the Sign Off feature in Git for?

There are some nice answers on this question. I’ll try to add a more broad answer, namely about what these kinds of lines/headers/trailers are about in current practice. Not so much about the sign-off header in particular (it’s not the only one).

Headers or trailers (?1) like “sign-off” (?2) is, in current practice in projects like Git and Linux, effectively structured metadata for the commit. These are all appended to the end of the commit message, after the “free form” (unstructured) part of the body of the message. These are token–value (or key–value) pairs typically delimited by a colon and a space (:?).

Like I mentioned, “sign-off” is not the only trailer in current practice. See for example this commit, which has to do with “Dirty Cow”:

 mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
 This is an ancient bug that was actually attempted to be fixed once
 (badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
 get_user_pages() race for write access") but that was then undone due to
 problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").

 In the meantime, the s390 situation has long been fixed, and we can now
 fix it by checking the pte_dirty() bit properly (and do it better).  The
 s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
 software dirty bits") which made it into v3.9.  Earlier kernels will
 have to look at the page state itself.

 Also, the VM has become more scalable, and what used a purely
 theoretical race back then has become easier to trigger.

 To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
 we already did a COW" rather than play racy games with FOLL_WRITE that
 is very fundamental, and then use the pte dirty flag to validate that
 the FOLL_COW flag is still valid.

 Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
 Acked-by: Hugh Dickins <[email protected]>
 Reviewed-by: Michal Hocko <[email protected]>
 Cc: Andy Lutomirski <[email protected]>
 Cc: Kees Cook <[email protected]>
 Cc: Oleg Nesterov <[email protected]>
 Cc: Willy Tarreau <[email protected]>
 Cc: Nick Piggin <[email protected]>
 Cc: Greg Thelen <[email protected]>
 Cc: [email protected]
 Signed-off-by: Linus Torvalds <[email protected]>

In addition to the “sign-off” trailer in the above, there is:

  • “Cc” (was notified about the patch)
  • “Acked-by” (acknowledged by the owner of the code, “looks good to me”)
  • “Reviewed-by” (reviewed)
  • “Reported-and-tested-by” (reported and tested the issue (I assume))

Other projects, like for example Gerrit, have their own headers and associated meaning for them.

See: https://git.wiki.kernel.org/index.php/CommitMessageConventions

Moral of the story

It is my impression that, although the initial motivation for this particular metadata was some legal issues (judging by the other answers), the practice of such metadata has progressed beyond just dealing with the case of forming a chain of authorship.

[?1]: man git-interpret-trailers
[?2]: These are also sometimes called “s-o-b” (initials), it seems.

What does upstream mean in nginx?

upstream defines a cluster that you can proxy requests to. It's commonly used for defining either a web server cluster for load balancing, or an app server cluster for routing / load balancing.

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

I had the same issue except removing and adding the reference back did not fix the error, so I changed .Net version from 4.5 to 4.5.1.

To achieve this go to your web.config file and change the following lines

<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />

to this

<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />

and rebuild.

Given an array of numbers, return array of products of all other numbers (no division)

Here is a C implementation
O(n) time complexity.
INPUT

#include<stdio.h>
int main()
{
    int x;
    printf("Enter The Size of Array : ");
    scanf("%d",&x);
    int array[x-1],i ;
    printf("Enter The Value of Array : \n");
      for( i = 0 ; i <= x-1 ; i++)
      {
          printf("Array[%d] = ",i);
          scanf("%d",&array[i]);
      }
    int left[x-1] , right[x-1];
    left[0] = 1 ;
    right[x-1] = 1 ;
      for( i = 1 ; i <= x-1 ; i++)
      {
          left[i] = left[i-1] * array[i-1];
      }
    printf("\nThis is Multiplication of array[i-1] and left[i-1]\n");
      for( i = 0 ; i <= x-1 ; i++)
      {
        printf("Array[%d] = %d , Left[%d] = %d\n",i,array[i],i,left[i]);
      }
      for( i = x-2 ; i >= 0 ; i--)
      {
          right[i] = right[i+1] * array[i+1];
      }
   printf("\nThis is Multiplication of array[i+1] and right[i+1]\n");
      for( i = 0 ; i <= x-1 ; i++)
      {
        printf("Array[%d] = %d , Right[%d] = %d\n",i,array[i],i,right[i]);
      }
    printf("\nThis is Multiplication of Right[i] * Left[i]\n");
      for( i = 0 ; i <= x-1 ; i++)
      {
          printf("Right[%d] * left[%d] = %d * %d = %d\n",i,i,right[i],left[i],right[i]*left[i]);
      }
    return 0 ;
}


OUTPUT

    Enter The Size of Array : 5
    Enter The Value of Array :
    Array[0] = 1
    Array[1] = 2
    Array[2] = 3
    Array[3] = 4
    Array[4] = 5

    This is Multiplication of array[i-1] and left[i-1]
    Array[0] = 1 , Left[0] = 1
    Array[1] = 2 , Left[1] = 1
    Array[2] = 3 , Left[2] = 2
    Array[3] = 4 , Left[3] = 6
    Array[4] = 5 , Left[4] = 24

    This is Multiplication of array[i+1] and right[i+1]
    Array[0] = 1 , Right[0] = 120
    Array[1] = 2 , Right[1] = 60
    Array[2] = 3 , Right[2] = 20
    Array[3] = 4 , Right[3] = 5
    Array[4] = 5 , Right[4] = 1

    This is Multiplication of Right[i] * Left[i]
    Right[0] * left[0] = 120 * 1 = 120
    Right[1] * left[1] = 60 * 1 = 60
    Right[2] * left[2] = 20 * 2 = 40
    Right[3] * left[3] = 5 * 6 = 30
    Right[4] * left[4] = 1 * 24 = 24

    Process returned 0 (0x0)   execution time : 6.548 s
    Press any key to continue.

Build the full path filename in Python

If you are fortunate enough to be running Python 3.4+, you can use pathlib:

>>> from pathlib import Path
>>> dirname = '/home/reports'
>>> filename = 'daily'
>>> suffix = '.pdf'
>>> Path(dirname, filename).with_suffix(suffix)
PosixPath('/home/reports/daily.pdf')

Angular: Cannot Get /

First, delete existing files package.lock.json and node_modules from your project. Then, the first step is to write npm cache clean --force. Second, also write this command npm i on the terminal. This process resolve my error. :D

Simple way to unzip a .zip file using zlib

Minizip does have an example programs to demonstrate its usage - the files are called minizip.c and miniunz.c.

Update: I had a few minutes so I whipped up this quick, bare bones example for you. It's very smelly C, and I wouldn't use it without major improvements. Hopefully it's enough to get you going for now.

// uzip.c - Simple example of using the minizip API.
// Do not use this code as is! It is educational only, and probably
// riddled with errors and leaks!
#include <stdio.h>
#include <string.h>

#include "unzip.h"

#define dir_delimter '/'
#define MAX_FILENAME 512
#define READ_SIZE 8192

int main( int argc, char **argv )
{
    if ( argc < 2 )
    {
        printf( "usage:\n%s {file to unzip}\n", argv[ 0 ] );
        return -1;
    }

    // Open the zip file
    unzFile *zipfile = unzOpen( argv[ 1 ] );
    if ( zipfile == NULL )
    {
        printf( "%s: not found\n" );
        return -1;
    }

    // Get info about the zip file
    unz_global_info global_info;
    if ( unzGetGlobalInfo( zipfile, &global_info ) != UNZ_OK )
    {
        printf( "could not read file global info\n" );
        unzClose( zipfile );
        return -1;
    }

    // Buffer to hold data read from the zip file.
    char read_buffer[ READ_SIZE ];

    // Loop to extract all files
    uLong i;
    for ( i = 0; i < global_info.number_entry; ++i )
    {
        // Get info about current file.
        unz_file_info file_info;
        char filename[ MAX_FILENAME ];
        if ( unzGetCurrentFileInfo(
            zipfile,
            &file_info,
            filename,
            MAX_FILENAME,
            NULL, 0, NULL, 0 ) != UNZ_OK )
        {
            printf( "could not read file info\n" );
            unzClose( zipfile );
            return -1;
        }

        // Check if this entry is a directory or file.
        const size_t filename_length = strlen( filename );
        if ( filename[ filename_length-1 ] == dir_delimter )
        {
            // Entry is a directory, so create it.
            printf( "dir:%s\n", filename );
            mkdir( filename );
        }
        else
        {
            // Entry is a file, so extract it.
            printf( "file:%s\n", filename );
            if ( unzOpenCurrentFile( zipfile ) != UNZ_OK )
            {
                printf( "could not open file\n" );
                unzClose( zipfile );
                return -1;
            }

            // Open a file to write out the data.
            FILE *out = fopen( filename, "wb" );
            if ( out == NULL )
            {
                printf( "could not open destination file\n" );
                unzCloseCurrentFile( zipfile );
                unzClose( zipfile );
                return -1;
            }

            int error = UNZ_OK;
            do    
            {
                error = unzReadCurrentFile( zipfile, read_buffer, READ_SIZE );
                if ( error < 0 )
                {
                    printf( "error %d\n", error );
                    unzCloseCurrentFile( zipfile );
                    unzClose( zipfile );
                    return -1;
                }

                // Write data to file.
                if ( error > 0 )
                {
                    fwrite( read_buffer, error, 1, out ); // You should check return of fwrite...
                }
            } while ( error > 0 );

            fclose( out );
        }

        unzCloseCurrentFile( zipfile );

        // Go the the next entry listed in the zip file.
        if ( ( i+1 ) < global_info.number_entry )
        {
            if ( unzGoToNextFile( zipfile ) != UNZ_OK )
            {
                printf( "cound not read next file\n" );
                unzClose( zipfile );
                return -1;
            }
        }
    }

    unzClose( zipfile );

    return 0;
}

I built and tested it with MinGW/MSYS on Windows like this:

contrib/minizip/$ gcc -I../.. -o unzip uzip.c unzip.c ioapi.c ../../libz.a
contrib/minizip/$ ./unzip.exe /j/zlib-125.zip

How do I lowercase a string in C?

It's in the standard library, and that's the most straight forward way I can see to implement such a function. So yes, just loop through the string and convert each character to lowercase.

Something trivial like this:

#include <ctype.h>

for(int i = 0; str[i]; i++){
  str[i] = tolower(str[i]);
}

or if you prefer one liners, then you can use this one by J.F. Sebastian:

for ( ; *p; ++p) *p = tolower(*p);

Usage of the backtick character (`) in JavaScript

Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.

Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}. The placeholder / expressions get passed to a function. The default function just concatenates the string.

To escape a backtick, put a backslash before it:

`\`` === '`'; => true

Use backticks to more easily write multi-line string:

console.log(`string text line 1
string text line 2`);

or

console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);

vs. vanilla JavaScript:

console.log('string text line 1\n' +
'string text line 2');

or

console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');

Escape sequences:

  • Unicode escapes started by \u, for example \u00A9
  • Unicode code point escapes indicated by \u{}, for example \u{2F804}
  • Hexadecimal escapes started by \x, for example \xA9
  • Octal literal escapes started by \ and (a) digit(s), for example \251

'names' attribute must be the same length as the vector

Depending on what you're doing in the loop, the fact that the %in% operator returns a vector might be an issue; consider a simple example:

c1 <- c("one","two","three","more","more")
c2 <- c("seven","five","three")

if(c1%in%c2) {
    print("hello")
}

then the following warning is issued:

Warning message:
In if (c1 %in% c2) { :
  the condition has length > 1 and only the first element will be used

if something in your if statement is dependent on a specific number of elements, and they don't match, then it is possible to obtain the error you see

WPF Databinding: How do I access the "parent" data context?

This also works in Silverlight 5 (perhaps earlier as well but i haven't tested it). I used the relative source like this and it worked fine.

RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType=telerik:RadGridView}"

How to do the equivalent of pass by reference for primitives in Java

You cannot pass primitives by reference in Java. All variables of object type are actually pointers, of course, but we call them "references", and they are also always passed by value.

In a situation where you really need to pass a primitive by reference, what people will do sometimes is declare the parameter as an array of primitive type, and then pass a single-element array as the argument. So you pass a reference int[1], and in the method, you can change the contents of the array.

git push: permission denied (public key)

I was facing same problem, here is what I did that worked for me.

Use ssh instead of http. Remove origin if its http.

git remote rm origin

Add ssh url

git remote add origin [email protected]:<username>/<repo>.git

Generate ssh key inside .ssh/ folder. It will ask for path and passphrase where you can just press enter and proceed.

cd ~/.ssh
ssh-keygen

Copy the key. You can view your key using. If you hadn't specified a different path then this is the default one.

cat ~/.ssh/id_rsa.pub

Add this key to your github account. Next do

ssh -T [email protected]

You will get a welcome message in your console.

cd into to your project folder. git push -u origin master now works!

Adding header to all request with Retrofit 2

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

httpClient.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request().newBuilder().addHeader("parameter", "value").build();
        return chain.proceed(request);
    }
});
Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(url).client(httpClient.build()).build();

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

Syncing Android Studio project with Gradle files

Keys combination:

Ctrl + F5

Syncs the project with Gradle files.

Installing SciPy and NumPy using pip

you need the libblas and liblapack dev packages if you are using Ubuntu.

aptitude install libblas-dev liblapack-dev
pip install scipy

Skip first line(field) in loop using CSV file?

There are many ways to skip the first line. In addition to those said by Bakuriu, I would add:

with open(filename, 'r') as f:
    next(f)
    for line in f:

and:

with open(filename,'r') as f:
    lines = f.readlines()[1:]

How to run mvim (MacVim) from Terminal?

I'd seriously recommend installing MacVim via MacPorts (sudo port install MacVim).

When installed, MacPorts automatically updates your profile to include /opt/local/bin in your path, and so when mvim is installed as /opt/local/bin/mvim during the install of MacVim you'll find it ready to use straight away.

When you install the MacVim port the MacVim.app bundle is installed in /Applications/MacPorts for you too.

A good thing about going the MacPorts route is that you'll also be able to install git too (sudo port install git-core) and many many other ports. Highly recommended.

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Run below 2 commands in PowerShell window

  1. Set-ExecutionPolicy unrestricted

  2. Unblock-File -Path D:\PowerShell\Script.ps1

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

You can use NSValue for this. An NSValue object is a simple container for a single C or Objective-C data item. It can hold any of the scalar types such as int, float, and char, as well as pointers, structures, and object ids.

Example:

  CGPoint cgPoint = CGPointMake(10,30);
    NSLog(@"%@",[NSValue valueWithCGPoint:cgPoint]);

OUTPUT : NSPoint: {10, 30}

Hope it helps you.

How to put comments in Django templates

In contrast to traditional html comments like this:

<!-- not so secret secrets -->

Django template comments are not rendered in the final html. So you can feel free to stuff implementation details in there like so:

Multi-line:

{% comment %}
    The other half of the flexbox is defined 
    in a different file `sidebar.html`
    as <div id="sidebar-main">.
{% endcomment %}

Single line:

{# jquery latest #}

{#
    beware, this won't be commented out... 
    actually renders as regular body text on the page
#}

I find single line comments especially helpful for <a href="{% url 'view_name' %}" views that have not been created yet.

How to check for palindrome using Python logic

Here a case insensitive function since all those solutions above are case sensitive.

def Palindrome(string): 

  return (string.upper() == string.upper()[::-1]) 

This function will return a boolean value.

Adding an external directory to Tomcat classpath

I might be a bit late for the party but I follow below steps to make it fully configurable using IntelliJ's way of in-IDE app test. I believe the best way to go with is to Combine below with @BelusC's answer.

1. run the application using IDE's tomcat run config. 
2. ps -ef | grep -i tomcat //this will give you a good idea about what the ide doing actually.
3. Copy the -Dcatalina.base parameter value from the command. this is your application specific catalina base. In this folder you can play with catalina.properties, application root path etc.. basically everything you have been doing is doable here too. 

Dynamically Add C# Properties at Runtime

you could deserialize your json string into a dictionary and then add new properties then serialize it.

 var jsonString = @"{}";

        var jsonDoc = JsonSerializer.Deserialize<Dictionary<string, object>>(jsonString);

        jsonDoc.Add("Name", "Khurshid Ali");

        Console.WriteLine(JsonSerializer.Serialize(jsonDoc));

How can I create a Java method that accepts a variable number of arguments?

You can pass all similar type values in the function while calling it. In the function definition put a array so that all the passed values can be collected in that array. e.g. .

static void demo (String ... stringArray) {
  your code goes here where read the array stringArray
}

Setting href attribute at runtime

<style>
a:hover {
    cursor:pointer;
}
</style>

<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $(".link").click(function(){
        var href = $(this).attr("href").split("#");
        $(".results").text(href[1]);
    })
})
</script>



<a class="link" href="#one">one</a><br />
<a class="link" href="#two">two</a><br />
<a class="link" href="#three">three</a><br />
<a class="link" href="#four">four</a><br />
<a class="link" href="#five">five</a>


<br /><br />
<div class="results"></div>

How to display data from database into textbox, and update it

Populate the text box values in the Page Init event as opposed to using the Postback.

protected void Page_Init(object sender, EventArgs e)
{
    DropDownTitle();
}

Vertical align text in block element

with thanks to Vlad's answer for inspiration; tested & working on IE11, FF49, Opera40, Chrome53

li > a {
  height: 100px;
  width: 300px;
  display: table-cell;
  text-align: center; /* H align */
  vertical-align: middle;
}

centers in all directions nicely even with text wrapping, line breaks, images, etc.

I got fancy and made a snippet

_x000D_
_x000D_
li > a {_x000D_
  height: 100px;_x000D_
  width: 300px;_x000D_
  display: table-cell;_x000D_
  /*H align*/_x000D_
  text-align: center;_x000D_
  /*V align*/_x000D_
  vertical-align: middle;_x000D_
}_x000D_
a.thin {_x000D_
  width: 40px;_x000D_
}_x000D_
a.break {_x000D_
  /*force text wrap, otherwise `width` is treated as `min-width` when encountering a long word*/_x000D_
  word-break: break-all;_x000D_
}_x000D_
/*more css so you can see this easier*/_x000D_
_x000D_
li {_x000D_
  display: inline-block;_x000D_
}_x000D_
li > a {_x000D_
  padding: 10px;_x000D_
  margin: 30px;_x000D_
  background: aliceblue;_x000D_
}_x000D_
li > a:hover {_x000D_
  padding: 10px;_x000D_
  margin: 30px;_x000D_
  background: aqua;_x000D_
}
_x000D_
<li><a href="">My menu item</a>_x000D_
</li>_x000D_
<li><a href="">My menu <br> break item</a>_x000D_
</li>_x000D_
<li><a href="">My menu item that is really long and unweildly</a>_x000D_
</li>_x000D_
<li><a href="" class="thin">Good<br>Menu<br>Item</a>_x000D_
</li>_x000D_
<li><a href="" class="thin">Fantastically Menu Item</a>_x000D_
</li>_x000D_
<li><a href="" class="thin break">Fantastically Menu Item</a>_x000D_
</li>_x000D_
<br>_x000D_
note: if using "break-all" need to also use "&lt;br>" or suffer the consequences
_x000D_
_x000D_
_x000D_

error: unknown type name ‘bool’

C99 does, if you have

#include <stdbool.h> 

If the compiler does not support C99, you can define it yourself:

// file : myboolean.h
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H

#define false 0
#define true 1
typedef int bool; // or #define bool int

#endif

(but note that this definition changes ABI for bool type so linking against external libraries which were compiled with properly defined bool may cause hard-to-diagnose runtime errors).

How do I trim whitespace?

No one has posted these regex solutions yet.

Matching:

>>> import re
>>> p=re.compile('\\s*(.*\\S)?\\s*')

>>> m=p.match('  \t blah ')
>>> m.group(1)
'blah'

>>> m=p.match('  \tbl ah  \t ')
>>> m.group(1)
'bl ah'

>>> m=p.match('  \t  ')
>>> print m.group(1)
None

Searching (you have to handle the "only spaces" input case differently):

>>> p1=re.compile('\\S.*\\S')

>>> m=p1.search('  \tblah  \t ')
>>> m.group()
'blah'

>>> m=p1.search('  \tbl ah  \t ')
>>> m.group()
'bl ah'

>>> m=p1.search('  \t  ')
>>> m.group()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

If you use re.sub, you may remove inner whitespace, which could be undesirable.

Python: print a generator expression?

>>> list(x for x in string.letters if x in (y for y in "BigMan on campus"))
['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']

How to increase the Java stack size?

Add this option

--driver-java-options -Xss512m

to your spark-submit command will fix this issue.

Compare two dates with JavaScript

you use this code,

var firstValue = "2012-05-12".split('-');
var secondValue = "2014-07-12".split('-');

 var firstDate=new Date();
 firstDate.setFullYear(firstValue[0],(firstValue[1] - 1 ),firstValue[2]);

 var secondDate=new Date();
 secondDate.setFullYear(secondValue[0],(secondValue[1] - 1 ),secondValue[2]);     

  if (firstDate > secondDate)
  {
   alert("First Date  is greater than Second Date");
  }
 else
  {
    alert("Second Date  is greater than First Date");
  }

And also check this link http://www.w3schools.com/js/js_obj_date.asp

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

Since youre using JSON, I would Base64 Encode it before sending it across the wire.

If the files are large, try to look at BSON, or some other format that is better with binary transfers.

You could also zip the files, if they compress well, before base64 encoding them.

Get size of folder or file

After lot of researching and looking into different solutions proposed here at StackOverflow. I finally decided to write my own solution. My purpose is to have no-throw mechanism because I don't want to crash if the API is unable to fetch the folder size. This method is not suitable for mult-threaded scenario.

First of all I want to check for valid directories while traversing down the file system tree.

private static boolean isValidDir(File dir){
    if (dir != null && dir.exists() && dir.isDirectory()){
        return true;
    }else{
        return false;
    }
}

Second I do not want my recursive call to go into symlinks (softlinks) and include the size in total aggregate.

public static boolean isSymlink(File file) throws IOException {
    File canon;
    if (file.getParent() == null) {
        canon = file;
    } else {
        canon = new File(file.getParentFile().getCanonicalFile(),
                file.getName());
    }
    return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
}

Finally my recursion based implementation to fetch the size of the specified directory. Notice the null check for dir.listFiles(). According to javadoc there is a possibility that this method can return null.

public static long getDirSize(File dir){
    if (!isValidDir(dir))
        return 0L;
    File[] files = dir.listFiles();
    //Guard for null pointer exception on files
    if (files == null){
        return 0L;
    }else{
        long size = 0L;
        for(File file : files){
            if (file.isFile()){
                size += file.length();
            }else{
                try{
                    if (!isSymlink(file)) size += getDirSize(file);
                }catch (IOException ioe){
                    //digest exception
                }
            }
        }
        return size;
    }
}

Some cream on the cake, the API to get the size of the list Files (might be all of files and folder under root).

public static long getDirSize(List<File> files){
    long size = 0L;
    for(File file : files){
        if (file.isDirectory()){
            size += getDirSize(file);
        } else {
            size += file.length();
        }
    }
    return size;
}

Refresh Page C# ASP.NET

Careful with rewriting URLs, though. I'm using this, so it keeps URLs rewritten.

Response.Redirect(Request.RawUrl);

What does "if (rs.next())" mean?

I'm presuming you're using Java 6 and that the ResultSet that you're using is a java.sql.ResultSet.

The JavaDoc for the ResultSet.next() method states:

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.

So, if(rs.next(){ //do something } means "If the result set still has results, move to the next result and do something".

As BalusC pointed out, you need to replace

ResultSet rs = stmt.executeQuery(sql);

with

ResultSet rs = stmt.executeQuery();

Because you've already set the SQL to use in the statement with your previous line

PreparedStatement stmt = conn.prepareStatement(sql);

If you weren't using the PreparedStatement, then ResultSet rs = stmt.executeQuery(sql); would work.

What does the "assert" keyword do?

Assertions are generally used primarily as a means of checking the program's expected behavior. It should lead to a crash in most cases, since the programmer's assumptions about the state of the program are false. This is where the debugging aspect of assertions come in. They create a checkpoint that we simply can't ignore if we would like to have correct behavior.

In your case it does data validation on the incoming parameters, though it does not prevent clients from misusing the function in the future. Especially if they are not, (and should not) be included in release builds.

Interface/enum listing standard mime-type constants

As pointed out by an answer above, you can use javax.ws.rs.core.MediaType which has the required constants.

I also wanted to share a really cool and handy link which I found that gives a reference to all the Javax constants in one place - https://docs.oracle.com/javaee/7/api/constant-values.html.

Converting an int into a 4 byte char array (C)

The portable way to do this (ensuring that you get 0x00 0x00 0x00 0xaf everywhere) is to use shifts:

unsigned char bytes[4];
unsigned long n = 175;

bytes[0] = (n >> 24) & 0xFF;
bytes[1] = (n >> 16) & 0xFF;
bytes[2] = (n >> 8) & 0xFF;
bytes[3] = n & 0xFF;

The methods using unions and memcpy() will get a different result on different machines.


The issue you are having is with the printing rather than the conversion. I presume you are using char rather than unsigned char, and you are using a line like this to print it:

printf("%x %x %x %x\n", bytes[0], bytes[1], bytes[2], bytes[3]);

When any types narrower than int are passed to printf, they are promoted to int (or unsigned int, if int cannot hold all the values of the original type). If char is signed on your platform, then 0xff likely does not fit into the range of that type, and it is being set to -1 instead (which has the representation 0xff on a 2s-complement machine).

-1 is promoted to an int, and has the representation 0xffffffff as an int on your machine, and that is what you see.

Your solution is to either actually use unsigned char, or else cast to unsigned char in the printf statement:

printf("%x %x %x %x\n", (unsigned char)bytes[0],
                        (unsigned char)bytes[1],
                        (unsigned char)bytes[2],
                        (unsigned char)bytes[3]);

Is there a way to make npm install (the command) to work behind proxy?

Though i set proxy with config, problem was not solved but after This one worked for me:

npm --https-proxy http://XX.AA.AA.BB:8080 install cordova-plugins

npm --proxy http://XX.AA.AA.BB:8080 install

Functional, Declarative, and Imperative Programming

imperative - expressions describe sequence of actions to perform (associative)

declarative - expressions are declarations that contribute to behavior of program (associative, commutative, idempotent, monotonic)

functional - expressions have value as only effect; semantics support equational reasoning

Format datetime in asp.net mvc 4

Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat] attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407


Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.

Model:

public class MyViewModel
{
    [DisplayName("date of birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime? Birth { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel
        {
            Birth = DateTime.Now
        });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Birth)
    @Html.EditorFor(x => x.Birth)
    @Html.ValidationMessageFor(x => x.Birth)
    <button type="submit">OK</button>
}

Registration of the custom model binder in Application_Start:

ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());

And the custom model binder itself:

public class MyDateTimeModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (!string.IsNullOrEmpty(displayFormat) && value != null)
        {
            DateTime date;
            displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
            // use the format specified in the DisplayFormat attribute to parse the date
            if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
            {
                return date;
            }
            else
            {
                bindingContext.ModelState.AddModelError(
                    bindingContext.ModelName,
                    string.Format("{0} is an invalid date format", value.AttemptedValue)
                );
            }
        }

        return base.BindModel(controllerContext, bindingContext);
    }
}

Now, no matter what culture you have setup in your web.config (<globalization> element) or the current thread culture, the custom model binder will use the DisplayFormat attribute's date format when parsing nullable dates.

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...

<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />

The above assumes that you have a folder called CSS in the root of your website like this:

http://www.website.com/CSS/Style.css

All shards failed

It is possible on your restart some shards were not recovered, causing the cluster to stay red.
If you hit:
http://<yourhost>:9200/_cluster/health/?level=shards you can look for red shards.

I have had issues on restart where shards end up in a non recoverable state. My solution was to simply delete that index completely. That is not an ideal solution for everyone.

It is also nice to visualize issues like this with a plugin like:
Elasticsearch Head

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

(9.61 + "").replace('.',':')

Or if your 9.61 is already a string:

"9.61".replace('.',':')

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

I'm using the following trick:

I select the declaration of the class with the data-members and press:

Ctrl+C, Shift+Ctrl+C, Ctrl+V.

  • The first command copies the declaration to the clipboard,
  • The second command is a shortcut that invokes the PROGRAM
  • The last command overwrites the selection by text from the clipboard.

The PROGRAM gets the declaration from the clipboard, finds the name of the class, finds all members and their types, generates constructor and copies it all back into the clipboard.

We are doing it with freshmen on my "Programming-I" practice (Charles University, Prague) and most of students gets it done till the end of the hour.

If you want to see the source code, let me know.

PL/pgSQL checking if a row exists

Simpler, shorter, faster: EXISTS.

IF EXISTS (SELECT 1 FROM people p WHERE p.person_id = my_person_id) THEN
  -- do something
END IF;

The query planner can stop at the first row found - as opposed to count(), which will scan all matching rows regardless. Makes a difference with big tables. Hardly matters with a condition on a unique column - only one row qualifies anyway (and there is an index to look it up quickly).

Improved with input from @a_horse_with_no_name in the comments below.

You could even use an empty SELECT list:

IF EXISTS (SELECT FROM people p WHERE p.person_id = my_person_id) THEN ...

Since the SELECT list is not relevant to the outcome of EXISTS. Only the existence of at least one qualifying row matters.

How to write "not in ()" sql query using join

I would opt for NOT EXISTS in this case.

SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
    (SELECT 'X'
     FROM Domain2 D2
     WHERE D2.ShortCode = D1.ShortCode
    )

CSS3 :unchecked pseudo-class

I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.

input[type="checkbox"] {
  // Unchecked Styles
}
input[type="checkbox"]:checked {
  // Checked Styles
}

I apologize for bringing up an old thread but felt like it could have used a better answer.

EDIT (3/3/2016):

W3C Specs state that :not(:checked) as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"] selector. See example below for clarification.

input[type="checkbox"] {
  /* Base Styles aka unchecked */
  font-weight: 300; // Will be overwritten by :checked
  font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
  /* Explicit Unchecked Styles */
  border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
  /* Checked Styles */
  font-weight: 900; // Use a bold font when checked
}

Without using :not(:checked) in the example above the :checked selector would have needed to use a border: none; to achieve the same affect.

Use the input[type="checkbox"] for base styling to reduce duplication.

Use the input[type="checkbox"]:not(:checked) for explicit unchecked styles that you do not want to apply to the checked state.

Slide div left/right using jQuery

You can easy get that effect without using jQueryUI, for example:

$(document).ready(function(){
    $('#slide').click(function(){
    var hidden = $('.hidden');
    if (hidden.hasClass('visible')){
        hidden.animate({"left":"-1000px"}, "slow").removeClass('visible');
    } else {
        hidden.animate({"left":"0px"}, "slow").addClass('visible');
    }
    });
});

Try this working Fiddle:

http://jsfiddle.net/ZQTFq/

How do I reference tables in Excel using VBA?

A "table" in Excel is indeed known as a ListObject.

The "proper" way to reference a table is by getting its ListObject from its Worksheet i.e. SheetObject.ListObjects(ListObjectName).

If you want to reference a table without using the sheet, you can use a hack Application.Range(ListObjectName).ListObject.

NOTE: This hack relies on the fact that Excel always creates a named range for the table's DataBodyRange with the same name as the table. However this range name can be changed...though it's not something you'd want to do since the name will reset if you edit the table name! Also you could get a named range with no associated ListObject.

Given Excel's not-very-helpful 1004 error message when you get the name wrong, you may want to create a wrapper...

Public Function GetListObject(ByVal ListObjectName As String, Optional ParentWorksheet As Worksheet = Nothing) As Excel.ListObject
On Error Resume Next

    If (Not ParentWorksheet Is Nothing) Then
        Set GetListObject = ParentWorksheet.ListObjects(ListObjectName)
    Else
        Set GetListObject = Application.Range(ListObjectName).ListObject
    End If

On Error GoTo 0 'Or your error handler

    If (Not GetListObject Is Nothing) Then
        'Success
    ElseIf (Not ParentWorksheet Is Nothing) Then
        Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found on sheet '" & ParentWorksheet.Name & "'!")
    Else
        Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found!")
    End If

End Function

Also some good ListObject info here.

Java Hashmap: How to get key from value?

Using Java 8:

ftw.forEach((key, value) -> {
    if (value.equals("foo")) {
        System.out.print(key);
    }
});

Cannot connect to Database server (mysql workbench)

I was in similar situations before and last time I found it was some Windows update issue(not sure). This time, I opened MySQL workbench and found no connection to my local database. I cannot see my tables, but yesterday I could connect to the database.

I found that my cause is that, after letting my computer sleeping for some time and wake it again, the mysql service is not running. My solution: restart the service named "mysql" and rerun the workbench. Restarting the service takes a while, but it works.

Execute JavaScript using Selenium WebDriver in C#

How about a slightly simplified version of @Morten Christiansen's nice extension method idea:

public static object Execute(this IWebDriver driver, string script)
{
    return ((IJavaScriptExecutor)driver).ExecuteScript(script);
}

// usage
var title = (string)driver.Execute("return document.title");

or maybe the generic version:

public static T Execute<T>(this IWebDriver driver, string script)
{
    return (T)((IJavaScriptExecutor)driver).ExecuteScript(script);
}

// usage
var title = driver.Execute<string>("return document.title");

taking input of a string word by word

getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.

#include <iostream>
using namespace std;

int main() {
    string a, b, c;
    cin >> a >> b >> c;
    //now you have your three words
    return 0;
}

I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.

How can I clear the content of a file?

The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.

Cleanest way to toggle a boolean variable in Java?

There are several

The "obvious" way (for most people)

theBoolean = !theBoolean;

The "shortest" way (most of the time)

theBoolean ^= true;

The "most visual" way (most uncertainly)

theBoolean = theBoolean ? false : true;

Extra: Toggle and use in a method call

theMethod( theBoolean ^= true );

Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call.

How to play an android notification sound

Try this:

public void ringtone(){
    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
        r.play();
     } catch (Exception e) {
         e.printStackTrace();
     }
}

How to read data from a zip file without having to unzip the entire file

Zip files have a table of contents. Every zip utility should have the ability to query just the TOC. Or you can use a command line program like 7zip -t to print the table of contents and redirect it to a text file.

Function to return only alpha-numeric characters from string?

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.

Find index of last occurrence of a sub-string using T-SQL

I needed to find the nth last position of a backslash in a folder path. Here is my solution.

/*
http://stackoverflow.com/questions/1024978/find-index-of-last-occurrence-of-a-sub-string-using-t-sql/30904809#30904809
DROP FUNCTION dbo.GetLastIndexOf
*/
CREATE FUNCTION dbo.GetLastIndexOf
(
  @expressionToFind         VARCHAR(MAX)
  ,@expressionToSearch      VARCHAR(8000)
  ,@Occurrence              INT =  1        -- Find the nth last 
)
RETURNS INT
AS
BEGIN

    SELECT  @expressionToSearch = REVERSE(@expressionToSearch)

    DECLARE @LastIndexOf        INT = 0
            ,@IndexOfPartial    INT = -1
            ,@OriginalLength    INT = LEN(@expressionToSearch)
            ,@Iteration         INT = 0

    WHILE (1 = 1)   -- Poor man's do-while
    BEGIN
        SELECT @IndexOfPartial  = CHARINDEX(@expressionToFind, @expressionToSearch)

        IF (@IndexOfPartial = 0) 
        BEGIN
            IF (@Iteration = 0) -- Need to compensate for dropping out early
            BEGIN
                SELECT @LastIndexOf = @OriginalLength  + 1
            END
            BREAK;
        END

        IF (@Occurrence > 0)
        BEGIN
            SELECT @expressionToSearch = SUBSTRING(@expressionToSearch, @IndexOfPartial + 1, LEN(@expressionToSearch) - @IndexOfPartial - 1)
        END

        SELECT  @LastIndexOf = @LastIndexOf + @IndexOfPartial
                ,@Occurrence = @Occurrence - 1
                ,@Iteration = @Iteration + 1

        IF (@Occurrence = 0) BREAK;
    END

    SELECT @LastIndexOf = @OriginalLength - @LastIndexOf + 1 -- Invert due to reverse
    RETURN @LastIndexOf 
END
GO

GRANT EXECUTE ON GetLastIndexOf TO public
GO

Here are my test cases which pass

SELECT dbo.GetLastIndexOf('f','123456789\123456789\', 1) as indexOf -- expect 0 (no instances)
SELECT dbo.GetLastIndexOf('\','123456789\123456789\', 1) as indexOf -- expect 20
SELECT dbo.GetLastIndexOf('\','123456789\123456789\', 2) as indexOf -- expect 10
SELECT dbo.GetLastIndexOf('\','1234\6789\123456789\', 3) as indexOf -- expect 5

How to use Tomcat 8 in Eclipse?

UPDATE: Eclipse Mars EE and later have native support for Tomcat8. Use this only if you have an earlier version of eclipse.


The latest version of Eclipse still does not support Tomcat 8, but you can add the new version of WTP and Tomcat 8 support will be added natively. To do this:

  • Download the latest version of Eclipse for Java EE
  • Go to the WTP downloads page, select the latest version (currently 3.6), and download the zip (under Traditional Zip Files...Web App Developers). Here's the current link.
  • Copy the all of the files in features and plugins directories of the downloaded WTP into the corresponding Eclipse directories in your Eclipse folder (overwriting the existing files).

Start Eclipse and you should have a Tomcat 8 option available when you go to deploy. enter image description here

Log all requests from the python-requests module

I'm using python 3.4, requests 2.19.1:

'urllib3' is the logger to get now (no longer 'requests.packages.urllib3'). Basic logging will still happen without setting http.client.HTTPConnection.debuglevel

Determine when a ViewPager changes pages

For ViewPager2,

viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
  override fun onPageSelected(position: Int) {
    super.onPageSelected(position)
  }
})

where OnPageChangeCallback is a static class with three methods:

onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position), 
onPageScrollStateChanged(@ScrollState int state)

Can table columns with a Foreign Key be NULL?

The above works but this does not. Note the ON DELETE CASCADE

CREATE DATABASE t;
USE t;

CREATE TABLE parent (id INT NOT NULL,
                 PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (id INT NULL, 
                parent_id INT NULL,
                FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE

) ENGINE=INNODB;


INSERT INTO child (id, parent_id) VALUES (1, NULL);
-- Query OK, 1 row affected (0.01 sec)

SQL Server Management Studio missing

In SQL Server 2016 it has its own link:

enter image description here

Just download it here: https://msdn.microsoft.com/en-us/library/mt238290.aspx

How to download a file using a Java REST service and a data stream

See example here: Input and Output binary streams using JERSEY?

Pseudo code would be something like this (there are a few other similar options in above mentioned post):

@Path("file/")
@GET
@Produces({"application/pdf"})
public StreamingOutput getFileContent() throws Exception {
     public void write(OutputStream output) throws IOException, WebApplicationException {
        try {
          //
          // 1. Get Stream to file from first server
          //
          while(<read stream from first server>) {
              output.write(<bytes read from first server>)
          }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
              // close input stream
        }
    }
}

draw diagonal lines in div background with CSS

_x000D_
_x000D_
.borders {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    background-color: black;_x000D_
    border-width: 40px;_x000D_
    border-style: solid;_x000D_
    border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
_x000D_
_x000D_

What are the advantages of Sublime Text over Notepad++ and vice-versa?

It's best if you judge on your own,

1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).

http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text

This Link is no more working so please watch this video for similar details Video

Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)

Some Variation: Some user find plugins useful for PHP coders on that

http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html

although, there are many plugins for Notepad Plus Plus ..

I am not sure of your requirements, nor I am promoter of either of these editors :)

So, judge on basis of your requirements, this should satisfy you query...

Yes we can add that both are evolving and changing fast..

How do I vertically center text with CSS?

A very simple & most powerful solution to vertically align center:

_x000D_
_x000D_
.outer-div {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  text-align: center;_x000D_
  border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  position: relative;_x000D_
  top: 50%;_x000D_
  transform: translateY(-50%);_x000D_
  color: red;_x000D_
}
_x000D_
<div class="outer-div">_x000D_
  <span class="inner">No data available</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

PHP json_encode encoding numbers as strings

The following test confirms that changing the type to string causes json_encode() to return a numeric as a JSON string (i.e., surrounded by double quotes). Use settype(arr["var"], "integer") or settype($arr["var"], "float") to fix it.

<?php

class testclass {
    public $foo = 1;
    public $bar = 2;
    public $baz = "Hello, world";
}

$testarr = array( 'foo' => 1, 'bar' => 2, 'baz' => 'Hello, world');

$json_obj_txt = json_encode(new testclass());
$json_arr_txt = json_encode($testarr);

echo "<p>Object encoding:</p><pre>" . $json_obj_txt . "</pre>";
echo "<p>Array encoding:</p><pre>" . $json_arr_txt . "</pre>";

// Both above return ints as ints. Type the int to a string, though, and...
settype($testarr["foo"], "string");
$json_arr_cast_txt = json_encode($testarr);
echo "<p>Array encoding w/ cast:</p><pre>" . $json_arr_cast_txt . "</pre>";

?>

How to scan multiple paths using the @ComponentScan annotation?

@ComponentScan uses string array, like this:

@ComponentScan({"com.my.package.first","com.my.package.second"})

When you provide multiple package names in only one string, Spring interprets this as one package name, and thus can't find it.

How to convert from []byte to int in Go Programming

now := []byte{0xFF,0xFF,0xFF,0xFF}
nowBuffer := bytes.NewReader(now)
var  nowVar uint32
binary.Read(nowBuffer,binary.BigEndian,&nowVar)
fmt.Println(nowVar)
4294967295

How to create a GUID in Excel?

ESP:

=CONCATENAR(
    DEC.A.HEX(ALEATORIO.ENTRE(0;4294967295);8);"-"; 
    DEC.A.HEX(ALEATORIO.ENTRE(0;42949);4);"-"; 
    DEC.A.HEX(ALEATORIO.ENTRE(0;42949);4);"-"; 
    DEC.A.HEX(ALEATORIO.ENTRE(0;42949);4);"-"; 
    DEC.A.HEX(ALEATORIO.ENTRE(0;4294967295);8); 
    DEC.A.HEX(ALEATORIO.ENTRE(0;42949);4)
)

How to select only the records with the highest date in LINQ

If you want the whole record,here is a lambda way:

var q = _context
             .lasttraces
             .GroupBy(s => s.AccountId)
             .Select(s => s.OrderByDescending(x => x.Date).FirstOrDefault());

How can I convert an Integer to localized month name in Java?

I would use SimpleDateFormat. Someone correct me if there is an easier way to make a monthed calendar though, I do this in code now and I'm not so sure.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;


public String formatMonth(int month, Locale locale) {
    DateFormat formatter = new SimpleDateFormat("MMMM", locale);
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.set(Calendar.DAY_OF_MONTH, 1);
    calendar.set(Calendar.MONTH, month-1);
    return formatter.format(calendar.getTime());
}

Set color of TextView span in Android

  1. create textview in ur layout
  2. paste this code in ur MainActivity

    TextView textview=(TextView)findViewById(R.id.textviewid);
    Spannable spannable=new SpannableString("Hello my name is sunil");
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, 
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    textview.setText(spannable);
    //Note:- the 0,5 is the size of colour which u want to give the strring
    //0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily
    

How to add subject alernative name to ssl certs?

Both IP and DNS can be specified with the keytool additional argument -ext SAN=dns:abc.com,ip:1.1.1.1

Example:

keytool -genkeypair -keystore <keystore> -dname "CN=test, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass <keypwd> -storepass <storepass> -keyalg RSA -alias unknown -ext SAN=dns:test.abc.com,ip:1.1.1.1

Why does git revert complain about a missing -m option?

Say the other guy created bar on top of foo, but you created baz in the meantime and then merged, giving a history of

$ git lola
*   2582152 (HEAD, master) Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

Note: git lola is a non-standard but useful alias.

No dice with git revert:

$ git revert HEAD
fatal: Commit 2582152... is a merge but no -m option was given.

Charles Bailey gave an excellent answer as usual. Using git revert as in

$ git revert --no-edit -m 1 HEAD
[master e900aad] Revert "Merge branch 'otherguy'"
 0 files changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 bar

effectively deletes bar and produces a history of

$ git lola
* e900aad (HEAD, master) Revert "Merge branch 'otherguy'"
*   2582152 Merge branch 'otherguy'
|\  
| * c7256de (otherguy) bar
* | b7e7176 baz
|/  
* 9968f79 foo

But I suspect you want to throw away the merge commit:

$ git reset --hard HEAD^
HEAD is now at b7e7176 baz

$ git lola
* b7e7176 (HEAD, master) baz
| * c7256de (otherguy) bar
|/  
* 9968f79 foo

As documented in the git rev-parse manual

<rev>^, e.g. HEAD^, v1.5.1^0
A suffix ^ to a revision parameter means the first parent of that commit object. ^<n> means the n-th parent (i.e. <rev>^ is equivalent to <rev>^1). As a special rule, <rev>^0 means the commit itself and is used when <rev> is the object name of a tag object that refers to a commit object.

so before invoking git reset, HEAD^ (or HEAD^1) was b7e7176 and HEAD^2 was c7256de, i.e., respectively the first and second parents of the merge commit.

Be careful with git reset --hard because it can destroy work.

How to multiply duration by integer?

You have to cast it to a correct format Playground.

yourTime := rand.Int31n(1000)
time.Sleep(time.Duration(yourTime) * time.Millisecond)

If you will check documentation for sleep, you see that it requires func Sleep(d Duration) duration as a parameter. Your rand.Int31n returns int32.

The line from the example works (time.Sleep(100 * time.Millisecond)) because the compiler is smart enough to understand that here your constant 100 means a duration. But if you pass a variable, you should cast it.

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

It's worth noting some other things:

  1. As shown in Windows Explorer Properties dialog for the generated assembly file, there are two places called "File version". The one seen in the header of the dialog shows the AssemblyVersion, not the AssemblyFileVersion.

    In the Other version information section, there is another element called "File Version". This is where you can see what was entered as the AssemblyFileVersion.

  2. AssemblyFileVersion is just plain text. It doesn't have to conform to the numbering scheme restrictions that AssemblyVersion does (<build> < 65K, e.g.). It can be 3.2.<release tag text>.<datetime>, if you like. Your build system will have to fill in the tokens.

    Moreover, it is not subject to the wildcard replacement that AssemblyVersion is. If you just have a value of "3.0.1.*" in the AssemblyInfo.cs, that is exactly what will show in the Other version information->File Version element.

  3. I don't know the impact upon an installer of using something other than numeric file version numbers, though.

Resource files not found from JUnit test cases

Main classes should be under src/main/java
and
test classes should be under src/test/java

If all in the correct places and still main classes are not accessible then
Right click project => Maven => Update Project
Hope so this will resolve the issue

What is the proper declaration of main in C++?

Details on return values and their meaning

Per 3.6.1 ([basic.start.main]):

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing

return 0;

The behavior of std::exit is detailed in section 18.5 ([support.start.term]), and describes the status code:

Finally, control is returned to the host environment. If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned. If status is EXIT_FAILURE, an implementation-defined form of the status unsuccessful termination is returned. Otherwise the status returned is implementation-defined.

SQL query to group by day

if you're using SQL Server,

dateadd(DAY,0, datediff(day,0, created)) will return the day created

for example, if the sale created on '2009-11-02 06:12:55.000', dateadd(DAY,0, datediff(day,0, created)) return '2009-11-02 00:00:00.000'

select sum(amount) as total, dateadd(DAY,0, datediff(day,0, created)) as created
from sales
group by dateadd(DAY,0, datediff(day,0, created))

How good is Java's UUID.randomUUID?

Wikipedia has a very good answer http://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions

the number of random version 4 UUIDs which need to be generated in order to have a 50% probability of at least one collision is 2.71 quintillion, computed as follows:

...

This number is equivalent to generating 1 billion UUIDs per second for about 85 years, and a file containing this many UUIDs, at 16 bytes per UUID, would be about 45 exabytes, many times larger than the largest databases currently in existence, which are on the order of hundreds of petabytes.

...

Thus, for there to be a one in a billion chance of duplication, 103 trillion version 4 UUIDs must be generated.

How to detect when keyboard is shown and hidden

Swift 4:

  NotificationCenter.default.addObserver( self, selector: #selector(ControllerClassName.keyboardWillShow(_:)),
  name: Notification.Name.UIKeyboardWillShow,
  object: nil)
  NotificationCenter.default.addObserver(self, selector: #selector(ControllerClassName.keyboardWillHide(_:)),
  name: Notification.Name.UIKeyboardWillHide,
  object: nil)

Next, adding method to stop listening for notifications when the object’s life ends:-

Then add the promised methods from above to the view controller:
deinit {
  NotificationCenter.default.removeObserver(self)
}
func adjustKeyboardShow(_ open: Bool, notification: Notification) {
  let userInfo = notification.userInfo ?? [:]
  let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
  let height = (keyboardFrame.height + 20) * (open ? 1 : -1)
  scrollView.contentInset.bottom += height
  scrollView.scrollIndicatorInsets.bottom += height
}

@objc func keyboardWillShow(_ notification: Notification) {
  adjustKeyboardShow(true, notification: notification)
}
@objc func keyboardWillHide(_ notification: Notification) {
  adjustKeyboardShow(false, notification: notification)
}

Setting equal heights for div's with jQuery

You can reach each separate container using .parent() API.

Like,

var highestBox = 0;
        $('.container .column').each(function(){  
                if($(this).parent().height() > highestBox){  
                highestBox = $(this).height();  
        }
    }); 

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this

 $(function(){
   $("input[type='number']").prop('min',1);
   $("input[type='number']").prop('max',10);
});

Demo

SQL to LINQ Tool

I know that this isn't what you asked for but LINQPad is a really great tool to teach yourself LINQ (and it's free :o).

When time isn't critical, I have been using it for the last week or so instead or a query window in SQL Server and my LINQ skills are getting better and better.

It's also a nice little code snippet tool. Its only downside is that the free version doesn't have IntelliSense.

how to make div click-able?

I suggest to use a CSS class called clickbox and activate it with jQuery:

$(".clickbox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
 });

Now the only thing you have to do is mark your div as clickable and provide a link:

<div id="logo" class="clickbox"><a href="index.php"></a></div>

Plus a CSS style to change the mouse cursor:

.clickbox {
    cursor: pointer;
}

Easy, isn't it?

MySQL show status - active or total connections?

To see a more complete list you can run:

show session status;

or

show global status;

See this link to better understand the usage.

If you want to know details about the database you can run:

status;

Selecting the last value of a column

This one works for me:

=INDEX(I:I;MAX((I:I<>"")*(ROW(I:I))))

How can I create database tables from XSD files?

hyperjaxb (versions 2 and 3) actually generates hibernate mapping files and related entity objects and also does a round trip test for a given XSD and sample XML file. You can capture the log output and see the DDL statements for yourself. I had to tweak them a little bit, but it gives you a basic blue print to start with.

oracle diff: how to compare two tables?

Try This,

alter session set "_convert_set_to_join"= true;

The other alternative is to rewrite the SQL query manually [replacing the minus operator with a NOT IN subquery] evidences about 30% improvement in execution time .

 select * 
   from A 
    where (col1,col2,?) not in 
   (select col1,col2,? from B) 
   union all 
   select * from B 
  where (col1,col2,?) not in 
  (select col1,col2,? from A); 

I have referred from this post click here

How to figure out the SMTP server host?

You can use the dig/host command to look up the MX records to see which mail server is handling mails for this domain.

On Linux you can do it as following for example:

$ host google.com
google.com has address 74.125.127.100
google.com has address 74.125.67.100
google.com has address 74.125.45.100
google.com mail is handled by 10 google.com.s9a2.psmtp.com.
google.com mail is handled by 10 smtp2.google.com.
google.com mail is handled by 10 google.com.s9a1.psmtp.com.
google.com mail is handled by 100 google.com.s9b2.psmtp.com.
google.com mail is handled by 10 smtp1.google.com.
google.com mail is handled by 100 google.com.s9b1.psmtp.com.

(as you can see, google has quite a lot of mail servers)

If you are working with windows, you might use nslookup (?) or try some web tool (e.g. that one) to display the same information.

Although that will only tell you the mail server for that domain. All other settings which are required can't be gathered that way. You might have to ask the provider.

Difference between filter and filter_by in SQLAlchemy

filter_by is used for simple queries on the column names using regular kwargs, like

db.users.filter_by(name='Joe')

The same can be accomplished with filter, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:

db.users.filter(db.users.name=='Joe')

You can also write more powerful queries using filter, such as expressions like:

db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))

How can I debug a .BAT script?

I don't know of anyway to step through the execution of a .bat file but you can use echo and pause to help with debugging.

ECHO
Will echo a message in the batch file. Such as ECHO Hello World will print Hello World on the screen when executed. However, without @ECHO OFF at the beginning of the batch file you'll also get "ECHO Hello World" and "Hello World." Finally, if you'd just like to create a blank line, type ECHO. adding the period at the end creates an empty line.

PAUSE
Prompt the user to press any key to continue.

Source: Batch File Help

@workmad3: answer has more good tips for working with the echo command.

Another helpful resource... DDB: DOS Batch File Tips

How to Find the Default Charset/Encoding in Java?

I have set the vm argument in WAS server as -Dfile.encoding=UTF-8 to change the servers' default character set.

ThreadStart with parameters

class Program
{
    static void Main(string[] args)
    {
        Thread t = new Thread(new ParameterizedThreadStart(ThreadMethod));

        t.Start("My Parameter");
    }

    static void ThreadMethod(object parameter)
    {
        // parameter equals to "My Parameter"
    }
}

Javascript - Regex to validate date format

@mplungjan, @eduard-luca

function isDate(str) {    
    var parms = str.split(/[\.\-\/]/);
    var yyyy = parseInt(parms[2],10);
    var mm   = parseInt(parms[1],10);
    var dd   = parseInt(parms[0],10);
    var date = new Date(yyyy,mm-1,dd,12,0,0,0);
    return mm === (date.getMonth()+1) && 
        dd === date.getDate() && 
        yyyy === date.getFullYear();
}

new Date() uses local time, hour 00:00:00 will show the last day when we have "Summer Time" or "DST (Daylight Saving Time)" events.

Example:

new Date(2010,9,17)
Sat Oct 16 2010 23:00:00 GMT-0300 (BRT)

Another alternative is to use getUTCDate().

Listing only directories in UNIX

ls -l | grep '^d'

You can make an alias and put it into the profile file

alias ld="ls -l| grep '^d'"

Converting EditText to int? (Android)

Use Integer.parseInt, and make sure you catch the NumberFormatException that it throws if the input is not an integer.

Align button at the bottom of div using CSS

Parent container has to have this:

position: relative;

Button itself has to have this:

position: relative;
bottom: 20px;
right: 20px;

or whatever you like

How do I work with a git repository within another repository?

Consider using subtree instead of submodules, it will make your repo users life much easier. You may find more detailed guide in Pro Git book.

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

Reading *.wav files in Python

I needed to read a 1-channel 24-bit WAV file. The post above by Nak was very useful. However, as mentioned above by basj 24-bit is not straightforward. I finally got it working using the following snippet:

from scipy.io import wavfile
TheFile = 'example24bit1channelFile.wav'
[fs, x] = wavfile.read(TheFile)

# convert the loaded data into a 24bit signal

nx = len(x)
ny = nx/3*4    # four 3-byte samples are contained in three int32 words

y = np.zeros((ny,), dtype=np.int32)    # initialise array

# build the data left aligned in order to keep the sign bit operational.
# result will be factor 256 too high

y[0:ny:4] = ((x[0:nx:3] & 0x000000FF) << 8) | \
  ((x[0:nx:3] & 0x0000FF00) << 8) | ((x[0:nx:3] & 0x00FF0000) << 8)
y[1:ny:4] = ((x[0:nx:3] & 0xFF000000) >> 16) | \
  ((x[1:nx:3] & 0x000000FF) << 16) | ((x[1:nx:3] & 0x0000FF00) << 16)
y[2:ny:4] = ((x[1:nx:3] & 0x00FF0000) >> 8) | \
  ((x[1:nx:3] & 0xFF000000) >> 8) | ((x[2:nx:3] & 0x000000FF) << 24)
y[3:ny:4] = (x[2:nx:3] & 0x0000FF00) | \
  (x[2:nx:3] & 0x00FF0000) | (x[2:nx:3] & 0xFF000000)

y = y/256   # correct for building 24 bit data left aligned in 32bit words

Some additional scaling is required if you need results between -1 and +1. Maybe some of you out there might find this useful

batch to copy files with xcopy

You must specify your file in the copy:

xcopy C:\source\myfile.txt C:\target

Or if you want to copy all txt files for example

xcopy C:\source\*.txt C:\target

Select objects based on value of variable in object using jq

I had a similar related question: What if you wanted the original object format back (with key names, e.g. FOO, BAR)?

Jq provides to_entries and from_entries to convert between objects and key-value pair arrays. That along with map around the select

These functions convert between an object and an array of key-value pairs. If to_entries is passed an object, then for each k: v entry in the input, the output array includes {"key": k, "value": v}.

from_entries does the opposite conversion, and with_entries(foo) is a shorthand for to_entries | map(foo) | from_entries, useful for doing some operation to all keys and values of an object. from_entries accepts key, Key, name, Name, value and Value as keys.

jq15 < json 'to_entries | map(select(.value.location=="Stockholm")) | from_entries'

{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

Using the with_entries shorthand, this becomes:

jq15 < json 'with_entries(select(.value.location=="Stockholm"))'
{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

How to decode HTML entities using jQuery?

To decode HTML Entities with jQuery, just use this function:

function html_entity_decode(txt){
    var randomID = Math.floor((Math.random()*100000)+1);
    $('body').append('<div id="random'+randomID+'"></div>');
    $('#random'+randomID).html(txt);
    var entity_decoded = $('#random'+randomID).html();
    $('#random'+randomID).remove();
    return entity_decoded;
}

How to use:

Javascript:

var txtEncoded = "&aacute; &eacute; &iacute; &oacute; &uacute;";
$('#some-id').val(html_entity_decode(txtEncoded));

HTML:

<input id="some-id" type="text" />

How to set value to variable using 'execute' in t-sql?

The dynamic SQL is a different scope to the outer, calling SQL: so @siteid is not recognised

You'll have to use a temp table/table variable outside of the dynamic SQL:

DECLARE @dbName nvarchar(128) = 'myDb'
DECLARE @siteId TABLE (siteid int)

INSERT @siteId
exec ('SELECT TOP 1 Id FROM ' + @dbName + '..myTbl')  

select * FROM @siteId

Note: TOP without an ORDER BY is meaningless. There is no natural, implied or intrinsic ordering to a table. Any order is only guaranteed by the outermost ORDER BY

Powershell Log Off Remote Session

Log off all users from a machine:

try {
   query user /server:$SERVER 2>&1 | select -skip 1 | foreach {
     logoff ($_ -split "\s+")[-6] /server:$SERVER
   }
}
catch {}

Details:

  • the try/catch is used when there are no users are on the server, and the query returns an error. however, you could drop the 2>&1 part, and remove the try/catch if you don't mind seeing the error string
  • select -skip 1 removes the header line
  • the inner foreach logs off each user
  • ($_ -split "\s+") splits the string to an array with just text items
  • [-6] index gets session ID and is the 6th string counting from the reverse of the array, you need to do this because the query output will have either 8 or 9 elements depending if the users connected or disconnected from the terminal session

Enable & Disable a Div and its elements in Javascript

If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.

try this.

$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');

iPhone/iOS JSON parsing tutorial

As of iOS 5.0 Apple provides the NSJSONSerialization class "to convert JSON to Foundation objects and convert Foundation objects to JSON". No external frameworks to incorporate and according to benchmarks its performance is quite good, significantly better than SBJSON.

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

It could also be as simple as the fact that your database is not actually MS SQL Server. If your database is actually MySql, for instance, and you try to connect to it with System.Data.SqlClient you will get this error.

By far most examples of ADO.Net will be for MSSQL and the inexperienced user may not know that you can't use SqlConnection, SqlCommand, etc., with MySql.

While all ADO.Net data providers conform to the same interface, you have to use the provider made for your database.

Catching KeyboardInterrupt in Python during program shutdown

Checkout this thread, it has some useful information about exiting and tracebacks.

If you are more interested in just killing the program, try something like this (this will take the legs out from under the cleanup code as well):

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('Interrupted')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

How to validate a credit card number

These are my two cents.

Note #1: this is not a perfect validation method, but it is OK for my needs.
Note #2: IIN ranges can be changed (and will be), so it is a good idea to check this link to be sure that we are up to date.

function validateCCNum(ccnum)
{
    var ccCheckRegExp = /[^\d\s-]/;
    var isValid = !ccCheckRegExp.test(ccnum);
    var i;

    if (isValid) {
        var cardNumbersOnly = ccnum.replace(/[\s-]/g,"");
        var cardNumberLength = cardNumbersOnly.length;

        var arrCheckTypes = ['visa', 'mastercard', 'amex', 'discover', 'dinners', 'jcb'];
        for(i=0; i<arrCheckTypes.length; i++) {
            var lengthIsValid = false;
            var prefixIsValid = false;
            var prefixRegExp;

            switch (arrCheckTypes[i]) {
                case "mastercard":
                    lengthIsValid = (cardNumberLength === 16);
                    prefixRegExp = /5[1-5][0-9]|(2(?:2[2-9][^0]|2[3-9]|[3-6]|22[1-9]|7[0-1]|72[0]))\d*/;
                    break;

                case "visa":
                    lengthIsValid = (cardNumberLength === 16 || cardNumberLength === 13);
                    prefixRegExp = /^4/;
                    break;

                case "amex":
                    lengthIsValid = (cardNumberLength === 15);
                    prefixRegExp = /^3([47])/;
                    break;

                case "discover":
                    lengthIsValid = (cardNumberLength === 15 || cardNumberLength === 16);
                    prefixRegExp = /^(6011|5)/;
                    break;

                case "dinners":
                    lengthIsValid = (cardNumberLength === 14);
                    prefixRegExp = /^(300|301|302|303|304|305|36|38)/;
                    break;

                case "jcb":
                    lengthIsValid = (cardNumberLength === 15 || cardNumberLength === 16);
                    prefixRegExp = /^(2131|1800|35)/;
                    break;

                default:
                    prefixRegExp = /^$/;
            }

            prefixIsValid = prefixRegExp.test(cardNumbersOnly);
            isValid = prefixIsValid && lengthIsValid;

            // Check if we found a correct one
            if(isValid) {
                break;
            }
        }
    }

    if (!isValid) {
        return false;
    }

    // Remove all dashes for the checksum checks to eliminate negative numbers
    ccnum = ccnum.replace(/[\s-]/g,"");
    // Checksum ("Mod 10")
    // Add even digits in even length strings or odd digits in odd length strings.
    var checksum = 0;
    for (i = (2 - (ccnum.length % 2)); i <= ccnum.length; i += 2) {
        checksum += parseInt(ccnum.charAt(i - 1));
    }

    // Analyze odd digits in even length strings or even digits in odd length strings.
    for (i = (ccnum.length % 2) + 1; i < ccnum.length; i += 2) {
        var digit = parseInt(ccnum.charAt(i - 1)) * 2;
        if (digit < 10) {
            checksum += digit;
        } else {
            checksum += (digit - 9);
        }
    }

    return (checksum % 10) === 0;
}

Thanks to @Peter Mortensen for the comment :)

PHP class not found but it's included

If you've included the file correctly and file exists and still getting error:

Then make sure:
Your included file contains the class and is not defined within any namespace.
If the class is in a namespace then:
instead of new YourClass() you've to do new YourNamespace\YourClass()

What is the difference between <section> and <div>?

<section> marks up a section, <div> marks up a generic block with no associated semantics.

ImportError: No module named google.protobuf

I got the same error message as in the title, but in my case import google was working and import google.protobuf wasn't (on python3.5, ubuntu 16.04).

It turned out that I've installed python3-google-apputils package (using apt) and it was installed to '/usr/lib/python3/dist-packages/google/apputils/', while protobuf (which was installed using pip) was in "/usr/lib/python3.5/dist-packages/google/protobuf/" - and it was a "google" namespace collapse.

Uninstalling google-apputils (from apt, and reinstalling it using pip) solved the problem.

sudo apt remove python3-google-apputils
sudo pip3 install google-apputils

Inner text shadow with CSS

Here's what I came up with after looking at some of the ideas here. The main idea is that the color of the text blends with both shadows, and note that this is being used on a grey background (otherwise the white won't show up well).

.inset {
    color: rgba(0,0,0, 0.6);
    text-shadow: 1px 1px 1px #fff, 0 0 1px rgba(0,0,0,0.6);
}

Python: finding an element in a list

how's this one?

def global_index(lst, test):
    return ( pair[0] for pair in zip(range(len(lst)), lst) if test(pair[1]) )

Usage:

>>> global_index([1, 2, 3, 4, 5, 6], lambda x: x>3)
<generator object <genexpr> at ...>
>>> list(_)
[3, 4, 5]

Java compile error: "reached end of file while parsing }"

You have to open and close your class with { ... } like:

public class mod_MyMod extends BaseMod
{
  public String Version()
  {
    return "1.2_02";
  }

  public void AddRecipes(CraftingManager recipes)
  {
     recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
        "#", Character.valueOf('#'), Block.dirt });
  }
}

Regex match digits, comma and semicolon?

You are 90% of the way there.

^[0-9,;]+$

Starting with the carat ^ indicates a beginning of line.

The [ indicates a character set

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ;.

The closing ] indicates the end of the character set.

The plus + indicates that one or more of the "previous item" must be present. In this case it means that you must have one or more of the characters in the previously declared character set.

The dollar $ indicates the end of the line.

What version of javac built my jar?

The code posted by Owen can tell you the information mentioned by a number of the other answers here:

public void simpleExample ()
{
    FileInputStream fis = new FileInputStream ("mytest.class");
    parseJavaClassFile ( fis );
}
protected void parseJavaClassFile ( InputStream classByteStream ) throws Exception
{
    DataInputStream dataInputStream = new DataInputStream ( classByteStream );
    magicNumber = dataInputStream.readInt();
    if ( magicNumber == 0xCAFEBABE )
    {
        int minorVer = dataInputStream.readUnsignedShort();
        int majorVer = dataInputStream.readUnsignedShort();
        // do something here with major & minor numbers
    }
}

See also this and this site. I ended up modifying the Mind Products code quickly to check what each of my dependencies was compiled for.

How to get difference between two dates in Year/Month/Week/Day?

Leap years and uneven months actually make this a non-trivial problem. I'm sure someone can come up with a more efficient way, but here's one option - approximate on the small side first and adjust up (untested):

public static void GetDifference(DateTime date1, DateTime date2, out int Years, 
    out int Months, out int Weeks, out int Days)
{
    //assumes date2 is the bigger date for simplicity

    //years
    TimeSpan diff = date2 - date1;
    Years = diff.Days / 366;
    DateTime workingDate = date1.AddYears(Years);

    while(workingDate.AddYears(1) <= date2)
    {
        workingDate = workingDate.AddYears(1);
        Years++;
    }

    //months
    diff = date2 - workingDate;
    Months = diff.Days / 31;
    workingDate = workingDate.AddMonths(Months);

    while(workingDate.AddMonths(1) <= date2)
    {
        workingDate = workingDate.AddMonths(1);
        Months++;
    }

    //weeks and days
    diff = date2 - workingDate;
    Weeks = diff.Days / 7; //weeks always have 7 days
    Days = diff.Days % 7;
}

OSX - How to auto Close Terminal window after the "exit" command executed.

If this is a Mac you type 'exit' then press return.

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

i think lodash _.get() can help here, as in _.get(user, 'name'), and more complex tasks like _.get(o, 'a[0].b.c', 'default-value')

Tensorflow: how to save/restore a model?

There are two parts to the model, the model definition, saved by Supervisor as graph.pbtxt in the model directory and the numerical values of tensors, saved into checkpoint files like model.ckpt-1003418.

The model definition can be restored using tf.import_graph_def, and the weights are restored using Saver.

However, Saver uses special collection holding list of variables that's attached to the model Graph, and this collection is not initialized using import_graph_def, so you can't use the two together at the moment (it's on our roadmap to fix). For now, you have to use approach of Ryan Sepassi -- manually construct a graph with identical node names, and use Saver to load the weights into it.

(Alternatively you could hack it by using by using import_graph_def, creating variables manually, and using tf.add_to_collection(tf.GraphKeys.VARIABLES, variable) for each variable, then using Saver)

How do I disable a Pylint warning?

Python syntax does permit more than one statement on a line, separated by semicolon (;). However, limiting each line to one statement makes it easier for a human to follow a program's logic when reading through it.

So, another way of solving this issue, is to understand why the lint message is there and not put more than one statement on a line.

Yes, you may find it easier to write multiple statements per line, however, Pylint is for every other reader of your code not just you.

Merging multiple PDFs using iTextSharp in c#.net

I found the answer:

Instead of the 2nd Method, add more files to the first array of input files.

public static void CombineMultiplePDFs(string[] fileNames, string outFile)
{
    // step 1: creation of a document-object
    Document document = new Document();
    //create newFileStream object which will be disposed at the end
    using (FileStream newFileStream = new FileStream(outFile, FileMode.Create))
    {
       // step 2: we create a writer that listens to the document
       PdfCopy writer = new PdfCopy(document, newFileStream );
       if (writer == null)
       {
           return;
       }

       // step 3: we open the document
       document.Open();

       foreach (string fileName in fileNames)
       {
           // we create a reader for a certain document
           PdfReader reader = new PdfReader(fileName);
           reader.ConsolidateNamedDestinations();

           // step 4: we add content
           for (int i = 1; i <= reader.NumberOfPages; i++)
           {                
               PdfImportedPage page = writer.GetImportedPage(reader, i);
               writer.AddPage(page);
           }

           PRAcroForm form = reader.AcroForm;
           if (form != null)
           {
               writer.CopyAcroForm(reader);
           }

           reader.Close();
       }

       // step 5: we close the document and writer
       writer.Close();
       document.Close();
   }//disposes the newFileStream object
}

Sending XML data using HTTP POST with PHP

you can use cURL library for posting data: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

Convert file path to a file URI?

At least in .NET 4.5+ you can also do:

var uri = new System.Uri("C:\\foo", UriKind.Absolute);

AND/OR in Python?

Are you looking for...

a if b else c

Or perhaps you misunderstand Python's or? True or True is True.

JSON character encoding

finally I got the solution:

Only put this line

@RequestMapping(value = "/YOUR_URL_Name",method = RequestMethod.POST,produces = "application/json; charset=utf-8")

this will definitely help.

Recursively counting files in a Linux directory

If you want to avoid error cases, don't allow wc -l to see files with newlines (which it will count as 2+ files)

e.g. Consider a case where we have a single file with a single EOL character in it

> mkdir emptydir && cd emptydir
> touch $'file with EOL(\n) character in it'
> find -type f
./file with EOL(?) character in it
> find -type f | wc -l
2

Since at least gnu wc does not appear to have an option to read/count a null terminated list (except from a file), the easiest solution would just be to not pass it filenames, but a static output each time a file is found, e.g. in the same directory as above

> find -type f -exec printf '\n' \; | wc -l
1

Or if your find supports it

> find -type f -printf '\n' | wc -l
1 

jQuery .load() call doesn't execute JavaScript in loaded HTML file

$("#images").load(location.href+" #images",function(){
    $.getScript("js/productHelper.js"); 
});

DataTable: Hide the Show Entries dropdown but keep the Search box

Just write :

  $(document).ready( function () {
        $('#example').dataTable( {
          "lengthChange": false
        } );
    } );

Initializing select with AngularJS and ng-repeat

The fact that angular is injecting an empty option element to the select is that the model object binded to it by default comes with an empty value in when initialized.

If you want to select a default option then you can probably can set it on the scope in the controller

$scope.filterCondition.operator = "your value here";

If you want to an empty option placeholder, this works for me

<select ng-model="filterCondition.operator" ng-options="operator.id as operator.name for operator in operators">
  <option value="">Choose Operator</option>
</select>

Print execution time of a shell command

root@hostname:~# time [command]

It also distinguishes between real time used and system time used.

Check if a file is executable

First you need to remember that in Unix and Linux, everything is a file, even directories. For a file to have the rights to be executed as a command, it needs to satisfy 3 conditions:

  1. It needs to be a regular file
  2. It needs to have read-permissions
  3. It needs to have execute-permissions

So this can be done simply with:

[ -f "${file}" ] && [ -r "${file}" ] && [ -x "${file}" ]

If your file is a symbolic link to a regular file, the test command will operate on the target and not the link-name. So the above command distinguishes if a file can be used as a command or not. So there is no need to pass the file first to realpath or readlink or any of those variants.

If the file can be executed on the current OS, that is a different question. Some answers above already pointed to some possibilities for that, so there is no need to repeat it here.

Image is not showing in browser?

You put inside img tag physical path you your image. Instead of that you should put virtual path (according to root of web application) to your image. This value depends on location of your image and your html page.

for example if you have:

/yourDir
-page.html
-66.jpg

in your page.html it should be something like that:

<img  src="66.jpg" width="400" height="400" ></img>

second scenario:

/images
-66.jpg
/html
page.html

So your img should look like:

<img  src="../images/66.jpg" width="400" height="400" ></img>

Instantiating a generic class in Java

For Java 8 ....

There is a good solution at https://stackoverflow.com/a/36315051/2648077 post.

This uses Java 8 Supplier functional interface

Export HTML table to pdf using jspdf

Use get(0) instead of html(). In other words, replace

doc.fromHTML($('#htmlTableId').html(), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

with

doc.fromHTML($('#htmlTableId').get(0), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

Possible to access MVC ViewBag object from Javascript file?

For CoreMVC 3.1, that would be,

@using Newtonsoft.Json
var listInJs =  @Html.Raw(JsonConvert.SerializeObject(ViewBag.SomeGenericList));

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

What you need (for tic-tac-toe or a far more difficult game like Chess) is the minimax algorithm, or its slightly more complicated variant, alpha-beta pruning. Ordinary naive minimax will do fine for a game with as small a search space as tic-tac-toe, though.

In a nutshell, what you want to do is not to search for the move that has the best possible outcome for you, but rather for the move where the worst possible outcome is as good as possible. If you assume your opponent is playing optimally, you have to assume they will take the move that is worst for you, and therefore you have to take the move that MINimises their MAXimum gain.

Displaying splash screen for longer than default seconds

This works...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Load Splash View Controller first
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"Splash"];
    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];

    // Load other stuff that requires time

    // Now load the main View Controller that you want
}

Eclipse: How do you change the highlight color of the currently selected method/expression?

1 - right click the highlight whose color you want to change

2 - select "Properties" in the popup menu

3 - choose the new color (as coobird suggested)

This solution is easy because you dont have to search for the highlight by its name ("Ocurrence" or "Write Ocurrence" etc), just right click and the appropriate window is shown.

How to check Spark Version

You can get the spark version by using the following command:

spark-submit --version

spark-shell --version

spark-sql --version

You can visit the below site to know the spark-version used in CDH 5.7.0

http://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_rn_new_in_cdh_57.html#concept_m3k_rxh_1v

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<?php 
    $sessionDetails = $this->Session->read('Auth.User');

    if (!empty($sessionDetails)) {


        $loginFlag = 1;
        # code...
    }else{
        $loginFlag =  0;
    }


?>

<script type="text/javascript">

    var sessionValue = '<?php echo $loginFlag; ?>';
    if (sessionValue = 0) {

        //model show
    }
</script>

Save each sheet in a workbook to separate CSV files

And here's my solution should work with Excel > 2000, but tested only on 2007:

Private Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven

' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

' ask the user where to save
OutputPath = InputBox("Enter a directory to save to", "Save to directory", Path)

If OutputPath <> "" Then

    ' save for each sheet
    For Each Sheet In Sheets

        OutputFile = OutputPath & "\" & Sheet.Name & ".csv"

        ' make a copy to create a new book with this sheet
        ' otherwise you will always only get the first sheet
        Sheet.Copy
        ' this copy will now become active
        ActiveWorkbook.SaveAs FileName:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False
        ActiveWorkbook.Close
    Next

End If

Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

Exit Sub

Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
        "Source: " & Err.Source & " " & vbCrLf & _
        "Number: " & Err.Number & " " & vbCrLf & _
        "Description: " & Err.Description & " " & vbCrLf

GoTo Finally
End Sub

(OT: I wonder if SO will replace some of my minor blogging)

XPath test if node value is number

Test the value against NaN:

<xsl:if test="string(number(myNode)) != 'NaN'">
    <!-- myNode is a number -->
</xsl:if>

This is a shorter version (thanks @Alejandro):

<xsl:if test="number(myNode) = myNode">
    <!-- myNode is a number -->
</xsl:if>

If input value is blank, assign a value of "empty" with Javascript

If you're using pure JS you can simply do it like:

var input = document.getElementById('myInput');

if(input.value.length == 0)
    input.value = "Empty";

Here's a demo: http://jsfiddle.net/nYtm8/

Setting state on componentDidMount()

It is not an anti-pattern to call setState in componentDidMount. In fact, ReactJS provides an example of this in their documentation:

You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.

Example From Doc

componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

How to recover closed output window in netbeans?

Here is solution

  1. First go to service window which is next tab to project tab...
  2. then right click on apache tomcat
  3. click view server log and view server output

Getting a browser's name client-side

It's all about what you really want to do, but in times to come and right now, the best way is avoid browser detection and check for features. like Canvas, Audio, WebSockets, etc through simple javascript calls or in your CSS, for me your best approach is use a tool like ModernizR:

Unlike with the traditional—but highly unreliable—method of doing “UA sniffing,” which is detecting a browser by its (user-configurable) navigator.userAgent property, Modernizr does actual feature detection to reliably discern what the various browsers can and cannot do.

If using CSS, you can do this:

.no-js .glossy,
.no-cssgradients .glossy {
    background: url("images/glossybutton.png");
}

.cssgradients .glossy {
    background-image: linear-gradient(top, #555, #333);
}

as it will load and append all features as a class name in the <html> element and you will be able to do as you wish in terms of CSS.

And you can even load files upon features, for example, load a polyfill js and css if the browser does not have native support

Modernizr.load([
  // Presentational polyfills
  {
    // Logical list of things we would normally need
    test : Modernizr.fontface && Modernizr.canvas && Modernizr.cssgradients,
    // Modernizr.load loads css and javascript by default
    nope : ['presentational-polyfill.js', 'presentational.css']
  },
  // Functional polyfills
  {
    // This just has to be truthy
    test : Modernizr.websockets && window.JSON,
    // socket-io.js and json2.js
    nope : 'functional-polyfills.js',
    // You can also give arrays of resources to load.
    both : [ 'app.js', 'extra.js' ],
    complete : function () {
      // Run this after everything in this group has downloaded
      // and executed, as well everything in all previous groups
      myApp.init();
    }
  },
  // Run your analytics after you've already kicked off all the rest
  // of your app.
  'post-analytics.js'
]);

a simple example of requesting features from javascript:

http://jsbin.com/udoyic/1

Background color for Tk in Python

config is another option:

widget1.config(bg='black')
widget2.config(bg='#000000')

or:

widget1.config(background='black')
widget2.config(background='#000000')

How to retrieve checkboxes values in jQuery

Here's an alternative in case you need to save the value to a variable:

var _t = $('#c_b :checkbox:checked').map(function() {
    return $(this).val();
});
$('#t').append(_t.join(','));

(map() returns an array, which I find handier than the text in textarea).

html vertical align the text inside input type button

I was having a similar issue with my button. I included line-height: 0; and it appears to have worked. Also mentioned by @anddero.

button[type=submit] {
  background-color: #4056A1;
  border-radius: 12px;
  border: 1px solid #4056A1;
  color: white;
  padding: 16px 32px;
  text-decoration: none;
  margin: 2px 1px;
  cursor: pointer;
  display: inline-block;
  font-size: 16px;
  height: 20px;
  line-height: 0;
}

Best way to resolve file path too long exception

Not mention so far and an update, there is a very well establish library for handling paths that are too long. AlphaFS is a .NET library providing more complete Win32 file system functionality to the .NET platform than the standard System.IO classes. The most notable deficiency of the standard .NET System.IO is the lack of support of advanced NTFS features, most notably extended length path support (eg. file/directory paths longer than 260 characters).

Best XML parser for Java

In addition to SAX and DOM there is STaX parsing available using XMLStreamReader which is an xml pull parser.

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

Understanding the set() function

After reading the other answers, I still had trouble understanding why the set comes out un-ordered.

Mentioned this to my partner and he came up with this metaphor: take marbles. You put them in a tube a tad wider than marble width : you have a list. A set, however, is a bag. Even though you feed the marbles one-by-one into the bag; when you pour them from a bag back into the tube, they will not be in the same order (because they got all mixed up in a bag).

How does one reorder columns in a data frame?

You can also use the subset function:

data <- subset(data, select=c(3,2,1))

You should better use the [] operator as in the other answers, but it may be useful to know that you can do a subset and a column reorder operation in a single command.

Update:

You can also use the select function from the dplyr package:

data = data %>% select(Time, out, In, Files)

I am not sure about the efficiency, but thanks to dplyr's syntax this solution should be more flexible, specially if you have a lot of columns. For example, the following will reorder the columns of the mtcars dataset in the opposite order:

mtcars %>% select(carb:mpg)

And the following will reorder only some columns, and discard others:

mtcars %>% select(mpg:disp, hp, wt, gear:qsec, starts_with('carb'))

Read more about dplyr's select syntax.

How to make an AJAX call without jQuery?

XMLHttpRequest()

You can use the XMLHttpRequest() constructor to create a new XMLHttpRequest (XHR) object which will allow you to interact with a server using standard HTTP request methods (such as GET and POST):

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

const request = new XMLHttpRequest();

request.addEventListener('load', function () {
  if (this.readyState === 4 && this.status === 200) {
    console.log(this.responseText);
  }
});

request.open('POST', 'example.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);

fetch()

You can also use the fetch() method to obtain a Promise which resolves to the Response object representing the response to your request:

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

fetch('example.php', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  },
  body: data,
}).then(response => {
  if (response.ok) {
    response.text().then(response => {
      console.log(response);
    });
  }
});

navigator.sendBeacon()

On the other hand, if you are simply attempting to POST data and do not need a response from the server, the shortest solution would be to use navigator.sendBeacon():

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

navigator.sendBeacon('example.php', data);

C++ printing spaces or tabs given a user input integer

cout << "Enter amount of spaces you would like (integer)" << endl; 
cin >> n;
//print n spaces
for (int i = 0; i < n; ++i)
{
   cout << " " ;
}
cout <<endl;

Testing whether a value is odd or even

Use modulus:

function isEven(n) {
   return n % 2 == 0;
}

function isOdd(n) {
   return Math.abs(n % 2) == 1;
}

You can check that any value in Javascript can be coerced to a number with:

Number.isFinite(parseFloat(n))

This check should preferably be done outside the isEven and isOdd functions, so you don't have to duplicate error handling in both functions.

How to center a View inside of an Android Layout?

Updated answer: Constraint Layout

It seems that the trend in Android now is to use a Constraint layout. Although it is simple enough to center a view using a RelativeLayout (as other answers have shown), the ConstraintLayout is more powerful than the RelativeLayout for more complex layouts. So it is worth learning how do do now.

To center a view, just drag the handles to all four sides of the parent.

enter image description here

How to give a Linux user sudo access?

You need run visudo and in the editor that it opens write:

igor    ALL=(ALL) ALL

That line grants all permissions to user igor.

If you want permit to run only some commands, you need to list them in the line:

igor    ALL=(ALL) /bin/kill, /bin/ps

How to solve a timeout error in Laravel 5

Add above query

ini_set("memory_limit", "10056M");