Programs & Examples On #Method signature

In computer programming, especially object-oriented programming, a method is commonly identified by its unique method signature, which usually includes the method name, and the number, types and order of its parameters. A method signature is the smallest type of a method.

How to return an array from a function?

how can i return a array in a c++ method and how must i declare it? int[] test(void); ??

This sounds like a simple question, but in C++ you have quite a few options. Firstly, you should prefer...

  • std::vector<>, which grows dynamically to however many elements you encounter at runtime, or

  • std::array<> (introduced with C++11), which always stores a number of elements specified at compile time, they manage memory for you, ensuring correct behaviour and simplifying things considerably:

std::vector<int> fn()
    std::vector<int> x;
    return x;

std::array<int, 2> fn2()  // C++11
    return {3, 4};

void caller()
    std::vector<int> a = fn();
    const std::vector<int>& b = fn(); // extend lifetime but read-only
                                      // b valid until scope exit/return

    std::array<int, 2> c = fn2();
    const std::array<int, 2>& d = fn2();

The practice of creating a const reference to the returned data can sometimes avoid a copy, but normally you can just rely on Return Value Optimisation, or - for vector but not array - move semantics (introduced with C++11).

If you really want to use an inbuilt array (as distinct from the Standard library class called array mentioned above), one way is for the caller to reserve space and tell the function to use it:

void fn(int x[], int n)
    for (int i = 0; i < n; ++i)
        x[i] = n;

void caller()
    // local space on the stack - destroyed when caller() returns
    int x[10];
    fn(x, sizeof x / sizeof x[0]);

    // or, use the heap, lives until delete[](p) called...
    int* p = new int[10];
    fn(p, 10);

Another option is to wrap the array in a structure, which - unlike raw arrays - are legal to return by value from a function:

struct X
    int x[10];

X fn()
    X x;
    x.x[0] = 10;
    // ...
    return x;

void caller()
    X x = fn();

Starting with the above, if you're stuck using C++03 you might want to generalise it into something closer to the C++11 std::array:

template <typename T, size_t N>
struct array
    T& operator[](size_t n) { return x[n]; }
    const T& operator[](size_t n) const { return x[n]; }
    size_t size() const { return N; }
    // iterators, constructors etc....
    T x[N];

Another option is to have the called function allocate memory on the heap:

int* fn()
    int* p = new int[2];
    p[0] = 0;
    p[1] = 1;
    return p;

void caller()
    int* p = fn();
    // use p...
    delete[] p;

To help simplify the management of heap objects, many C++ programmers use "smart pointers" that ensure deletion when the pointer(s) to the object leave their scopes. With C++11:

std::shared_ptr<int> p(new int[2], [](int* p) { delete[] p; } );
std::unique_ptr<int[]> p(new int[3]);

If you're stuck on C++03, the best option is to see if the boost library is available on your machine: it provides boost::shared_array.

Yet another option is to have some static memory reserved by fn(), though this is NOT THREAD SAFE, and means each call to fn() overwrites the data seen by anyone keeping pointers from previous calls. That said, it can be convenient (and fast) for simple single-threaded code.

int* fn(int n)
    static int x[2];  // clobbered by each call to fn()
    x[0] = n;
    x[1] = n + 1;
    return x;  // every call to fn() returns a pointer to the same static x memory

void caller()
    int* p = fn(3);
    // use p, hoping no other thread calls fn() meanwhile and clobbers the values...
    // no clean up necessary...

Reading a registry key in C#

string InstallPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\MyApplication\AppPath", "Installed", null);    
if (InstallPath != null)
    // Do stuff

That code should get your value. You'll need to be

using Microsoft.Win32;

for that to work though.

How to get directory size in PHP

Even though there are already many many answers to this post, I feel I have to add another option for unix hosts that only returns the sum of all file sizes in the directory (recursively).

If you look at Jonathan's answer he uses the du command. This command will return the total directory size but the pure PHP solutions posted by others here will return the sum of all file sizes. Big difference!

What to look out for

When running du on a newly created directory, it may return 4K instead of 0. This may even get more confusing after having deleted files from the directory in question, having du reporting a total directory size that does not correspond to the sum of the sizes of the files within it. Why? The command du returns a report based on some file settings, as Hermann Ingjaldsson commented on this post.

The solution

To form a solution that behaves like some of the PHP-only scripts posted here, you can use ls command and pipe it to awk like this:

ls -ltrR /path/to/dir |awk '{print \$5}'|awk 'BEGIN{sum=0} {sum=sum+\$1} END {print sum}'

As a PHP function you could use something like this:

function getDirectorySize( $path )
    if( !is_dir( $path ) ) {
        return 0;

    $path   = strval( $path );
    $io     = popen( "ls -ltrR {$path} |awk '{print \$5}'|awk 'BEGIN{sum=0} {sum=sum+\$1} END {print sum}'", 'r' );
    $size   = intval( fgets( $io, 80 ) );
    pclose( $io );

    return $size;

Why am I getting ImportError: No module named pip ' right after installing pip?

turned out i had 2 versions of python on my laptop

both commands worked for me

python -m ensurepip
py -m ensurepip

both with another installation path

c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages 

only the first path was in my %PATH% variable

Remove all whitespace in a string

import re    
sentence = ' hello  apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub('  ',' ',sentence) #hello world (remove double spaces)

Easiest way to rotate by 90 degrees an image using OpenCV?

This is an example without the new C++ interface (works for 90, 180 and 270 degrees, using param = 1, 2 and 3). Remember to call cvReleaseImage on the returned image after using it.

IplImage *rotate_image(IplImage *image, int _90_degrees_steps_anti_clockwise)
    IplImage *rotated;

    if(_90_degrees_steps_anti_clockwise != 2)
        rotated = cvCreateImage(cvSize(image->height, image->width), image->depth, image->nChannels);
        rotated = cvCloneImage(image);

    if(_90_degrees_steps_anti_clockwise != 2)
        cvTranspose(image, rotated);

    if(_90_degrees_steps_anti_clockwise == 3)
        cvFlip(rotated, NULL, 1);
    else if(_90_degrees_steps_anti_clockwise == 1)
        cvFlip(rotated, NULL, 0);
    else if(_90_degrees_steps_anti_clockwise == 2)
        cvFlip(rotated, NULL, -1);

    return rotated;

Log exception with traceback

My job recently tasked me with logging all the tracebacks/exceptions from our application. I tried numerous techniques that others had posted online such as the one above but settled on a different approach. Overriding traceback.print_exception.

I have a write up at That would be much easier to read but Ill paste it in here as well.

When tasked with logging all the exceptions that our software might encounter in the wild I tried a number of different techniques to log our python exception tracebacks. At first I thought that the python system exception hook, sys.excepthook would be the perfect place to insert the logging code. I was trying something similar to:

import traceback
import StringIO
import logging
import os, sys

def my_excepthook(excType, excValue, traceback, logger=logger):
    logger.error("Logging an uncaught exception",
                 exc_info=(excType, excValue, traceback))

sys.excepthook = my_excepthook  

This worked for the main thread but I soon found that the my sys.excepthook would not exist across any new threads my process started. This is a huge issue because most everything happens in threads in this project.

After googling and reading plenty of documentation the most helpful information I found was from the Python Issue tracker.

The first post on the thread shows a working example of the sys.excepthook NOT persisting across threads (as shown below). Apparently this is expected behavior.

import sys, threading

def log_exception(*args):
    print 'got exception %s' % (args,)
sys.excepthook = log_exception

def foo():
    a = 1 / 0


The messages on this Python Issue thread really result in 2 suggested hacks. Either subclass Thread and wrap the run method in our own try except block in order to catch and log exceptions or monkey patch to run in your own try except block and log the exceptions.

The first method of subclassing Thread seems to me to be less elegant in your code as you would have to import and use your custom Thread class EVERYWHERE you wanted to have a logging thread. This ended up being a hassle because I had to search our entire code base and replace all normal Threads with this custom Thread. However, it was clear as to what this Thread was doing and would be easier for someone to diagnose and debug if something went wrong with the custom logging code. A custome logging thread might look like this:

class TracebackLoggingThread(threading.Thread):
    def run(self):
            super(TracebackLoggingThread, self).run()
        except (KeyboardInterrupt, SystemExit):
        except Exception, e:
            logger = logging.getLogger('')
            logger.exception("Logging an uncaught exception")

The second method of monkey patching is nice because I could just run it once right after __main__ and instrument my logging code in all exceptions. Monkey patching can be annoying to debug though as it changes the expected functionality of something. The suggested patch from the Python Issue tracker was:

def installThreadExcepthook():
    Workaround for sys.excepthook thread bug

    Call once from __main__ before creating any threads.
    If using psyco, call psyco.cannotcompile(
    since this replaces a new-style class method.
    init_old = threading.Thread.__init__
    def init(self, *args, **kwargs):
        init_old(self, *args, **kwargs)
        run_old =
        def run_with_except_hook(*args, **kw):
                run_old(*args, **kw)
            except (KeyboardInterrupt, SystemExit):
                sys.excepthook(*sys.exc_info()) = run_with_except_hook
    threading.Thread.__init__ = init

It was not until I started testing my exception logging I realized that I was going about it all wrong.

To test I had placed a

raise Exception("Test")

somewhere in my code. However, wrapping a a method that called this method was a try except block that printed out the traceback and swallowed the exception. This was very frustrating because I saw the traceback bring printed to STDOUT but not being logged. It was I then decided that a much easier method of logging the tracebacks was just to monkey patch the method that all python code uses to print the tracebacks themselves, traceback.print_exception. I ended up with something similar to the following:

def add_custom_print_exception():
    old_print_exception = traceback.print_exception
    def custom_print_exception(etype, value, tb, limit=None, file=None):
        tb_output = StringIO.StringIO()
        traceback.print_tb(tb, limit, tb_output)
        logger = logging.getLogger('customLogger')
        old_print_exception(etype, value, tb, limit=None, file=None)
    traceback.print_exception = custom_print_exception

This code writes the traceback to a String Buffer and logs it to logging ERROR. I have a custom logging handler set up the 'customLogger' logger which takes the ERROR level logs and send them home for analysis.

Mips how to store user input string

# This code works fine in QtSpim simulator

    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"


    la $a0, str1    # Load and print string asking for string
    li $v0, 4

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string

    li $v0, 10      # end program

How to get the 'height' of the screen using jquery

use with responsive website (view in mobile or ipad)

jQuery(window).height();   // return height of browser viewport
jQuery(window).width();    // return width of browser viewport

rarely use

jQuery(document).height(); // return height of HTML document
jQuery(document).width();  // return width of HTML document

Tab key == 4 spaces and auto-indent after curly braces in Vim

Afterall, you could edit the .vimrc,then add the conf

set tabstop=4

Or exec the command


A quick solution from the internet search was npm config set strict-ssl false, luckily it worked. But as a part of my work environment, I am restricted to set the strict-ssl flag to false.

Later I found a safe and working solution,

npm config set registry  

this worked perfectly and I got a success message Happy Hacking! by not setting the strict-ssl flag to false.

How can I define an array of objects?

You are better off using a native array instead of an object literal with number-like properties, so that numbering (as well as numerous other array functions) are taken care of off-the-shelf.

What you are looking for here is an inline interface definition for your array that defines every element in that array, whether initially present or introduced later:

let userTestStatus: { id: number, name: string }[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]

If you are initializing your array with values right away, the explicit type definition is not a necessity; TypeScript can automatically infer most element types from the initial assignment:

let userTestStatus = [
    { "id": 0, "name": "Available" },

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]

A cron job for rails: best practices?

I use backgroundrb.

I use it to run scheduled tasks as well as tasks that take too long for the normal client/server relationship.

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Frequently we deal with other fellow java programmers work which create these Stored Procedure. and we do not want to mess around with it. but there is possibility you get the result set where these exec sample return 0 (almost Stored procedure call returning zero).

check this sample :

public void generateINOUT(String USER, int DPTID){

    try {

        conUrl = JdbcUrls + dbServers +";databaseName="+ dbSrcNames+";instance=MSSQLSERVER";

        con = DriverManager.getConnection(conUrl,dbUserNames,dbPasswords);
        //stat = con.createStatement();
        Statement st = con.createStatement(); 

        st.executeUpdate("DECLARE @RC int\n" +
                "DECLARE @pUserID nvarchar(50)\n" +
                "DECLARE @pDepartmentID int\n" +
                "DECLARE @pStartDateTime datetime\n" +
                "DECLARE @pEndDateTime datetime\n" +
                "EXECUTE [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] \n" +
                ""+USER +
                "," +DPTID+
                ",'"+STARTDATE +

        ResultSet rs = st.getGeneratedKeys();

        while ({
              String userID = rs.getString("UserID");
              Timestamp timeIN = rs.getTimestamp("timeIN");
              Timestamp timeOUT = rs.getTimestamp ("timeOUT");
              int totTime = rs.getInt ("totalTime");
              int pivot = rs.getInt ("pivotvalue");

              timeINS = sdz.format(timeIN);

              timeOUTS = sdz.format(timeOUT);

              System.out.println("User : "+userID+" |IN : "+timeIN+" |OUT : "+timeOUT+"| Total Time : "+totTime+" | PivotValue : "+pivot);


    }catch (Exception e) {
        if (e.getCause() != null) {

I came to this solutions after few days trial and error, googling and get confused ;) it execute below Stored Procedure :

USE [AccessManager]
/****** Object:  StoredProcedure [dbo].[SP_GenerateInOutDetailReportSimple]    
Script Date: 04/05/2013 15:54:11 ******/

ALTER PROCEDURE [dbo].[SP_GenerateInOutDetailReportSimple]
@pUserID nvarchar(50),
@pDepartmentID int,
@pStartDateTime datetime,
@pEndDateTime datetime

Declare @ErrorCode int
Select @ErrorCode = @@Error

Declare @TransactionCountOnEntry int
If @ErrorCode = 0
    Select @TransactionCountOnEntry = @@TranCount

If @ErrorCode = 0

    -- Create table variable instead of SQL temp table because report wont pick up the temp table
    DECLARE @tempInOutDetailReport TABLE
        UserID nvarchar(50),
        LogDate datetime,   
        LogDay varchar(20), 
        TimeIN datetime,
        TimeOUT datetime,
        TotalTime int,
        RemarkTimeIn nvarchar(100),
        RemarkTimeOut nvarchar(100),
        TerminalIPTimeIn varchar(50),
        TerminalIPTimeOut varchar(50),
        TerminalSNTimeIn nvarchar(50),
        TerminalSNTimeOut nvarchar(50),
        PivotValue int

    -- Declare variables for the while loop
    Declare @LogUserID nvarchar(50)
    Declare @LogEventID nvarchar(50)
    Declare @LogTerminalSN nvarchar(50)
    Declare @LogTerminalIP nvarchar(50)
    Declare @LogRemark nvarchar(50)
    Declare @LogTimestamp datetime  
    Declare @LogDay nvarchar(20)

    -- Filter off userID, departmentID, StartDate and EndDate if specified, only process the remaining logs
    -- Note: order by user then timestamp
    Declare LogCursor Cursor For 
    Select distinct access_event_logs.USERID, access_event_logs.EVENTID, 
        access_event_logs.TERMINALSN, access_event_logs.TERMINALIP,
        access_event_logs.REMARKS, access_event_logs.LOCALTIMESTAMP, Datename(dw,access_event_logs.LOCALTIMESTAMP) AS WkDay
    From access_event_logs
        Left Join access_user on access_user.User_ID = access_event_logs.USERID
        Left Join access_user_dept on access_user.User_ID = access_user_dept.User_ID
    Where ((Dept_ID = @pDepartmentID) OR (@pDepartmentID IS NULL))
        And ((access_event_logs.USERID LIKE '%' + @pUserID + '%') OR (@pUserID IS NULL)) 
        And ((access_event_logs.LOCALTIMESTAMP >= @pStartDateTime ) OR (@pStartDateTime IS NULL)) 
        And ((access_event_logs.LOCALTIMESTAMP < DATEADD(day, 1, @pEndDateTime) ) OR (@pEndDateTime IS NULL)) 
        And (access_event_logs.USERID != 'UNKNOWN USER') -- Ignore UNKNOWN USER
    Order by access_event_logs.USERID, access_event_logs.LOCALTIMESTAMP

    Open LogCursor

    Fetch Next 
    From LogCursor
    Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay

    -- Temp storage for IN event details
    Declare @InEventUserID nvarchar(50)
    Declare @InEventDay nvarchar(20)
    Declare @InEventTimestamp datetime
    Declare @InEventRemark nvarchar(100)
    Declare @InEventTerminalIP nvarchar(50)
    Declare @InEventTerminalSN nvarchar(50)

    -- Temp storage for OUT event details
    Declare @OutEventUserID nvarchar(50)        
    Declare @OutEventTimestamp datetime
    Declare @OutEventRemark nvarchar(100)
    Declare @OutEventTerminalIP nvarchar(50)
    Declare @OutEventTerminalSN nvarchar(50)

    Declare @CurrentUser varchar(50) -- used to indicate when we change user group
    Declare @CurrentDay varchar(50) -- used to indicate when we change day
    Declare @FirstEvent int -- indicate the first event we received     
    Declare @ReceiveInEvent int -- indicate we have received an IN event
    Declare @PivotValue int -- everytime we change user or day - we reset it (reporting purpose), if same user..keep increment its value
    Declare @CurrTrigger varchar(50) -- used to keep track of the event of the current event log trigger it is handling 
    Declare @CurrTotalHours int -- used to keep track of total hours of the day of the user

    Declare @FirstInEvent datetime
    Declare @FirstInRemark nvarchar(100)
    Declare @FirstInTerminalIP nvarchar(50)
    Declare @FirstInTerminalSN nvarchar(50)
    Declare @FirstRecord int -- indicate another day of same user

    Set @PivotValue = 0 -- initialised
    Set @CurrentUser = '' -- initialised
    Set @FirstEvent = 1 -- initialised
    Set @ReceiveInEvent = 0 -- initialised  
    Set @CurrTrigger = '' -- Initialised    
    Set @CurrTotalHours = 0 -- initialised
    Set @FirstRecord = 1 -- initialised
    Set @CurrentDay = '' -- initialised

    While @@FETCH_STATUS = 0
        -- use to track current log trigger
        Set @CurrTrigger =LOWER(@LogEventID)

        If (@CurrentUser != '' And @CurrentUser != @LogUserID) -- new batch of user
            If @ReceiveInEvent = 1  -- previous IN event is not cleared (no OUT is found)
                -- Check day
                If (@CurrentDay != @InEventDay) -- change to another day                    
                    Set @PivotValue = 0 -- Reset                        

                Else -- same day
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @InEventDay -- update the day

                -- invalid row (only has IN event)
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                    TerminalSNTimeIn, PivotValue, LogDate )
                values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                                                         

            Set @FirstEvent = 1 -- Reset flag (we are having a new user group)
            Set @ReceiveInEvent = 0 -- Reset
            Set @PivotValue = 0 -- Reset
            --Set @CurrentDay = '' -- Reset

        If LOWER(@LogEventID) = 'in' -- IN event
            If @ReceiveInEvent = 1  -- previous IN event is not cleared (no OUT is found)
                -- Check day
                If (@CurrentDay != @InEventDay) -- change to another day
                    Set @PivotValue = 0 -- Reset

                    --Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                    --  RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                    --  LogDate)
                    --values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp,  @CurrTotalHours,
                    --  @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
                    --  DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))  
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @InEventDay -- update the day

                -- invalid row (only has IN event)
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                    TerminalSNTimeIn, PivotValue, LogDate )
                values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                     

            If((@CurrentDay != @LogDay And @CurrentDay != '') Or (@CurrentUser != @LogUserID And @CurrentUser != '') )

                    Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                        RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                    values( @CurrentUser, @CurrentDay, @FirstInEvent, @OutEventTimestamp, @CurrTotalHours,
                        @FirstInRemark, @OutEventRemark, @FirstInTerminalIP, @OutEventTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
                        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))      

                Set @FirstRecord = 1
            -- Save it
            Set @InEventUserID = @LogUserID                         
            Set @InEventDay = @LogDay
            Set @InEventTimestamp = @LogTimeStamp
            Set @InEventRemark = @LogRemark
            Set @InEventTerminalIP = @LogTerminalIP
            Set @InEventTerminalSN = @LogTerminalSN

            If (@FirstRecord = 1) -- save for first in event record of the day
                Set @FirstInEvent = @LogTimestamp
                Set @FirstInRemark = @LogRemark
                Set @FirstInTerminalIP = @LogTerminalIP
                Set @FirstInTerminalSN = @LogTerminalSN
                Set @CurrTotalHours = 0 --initialise total hours for another day

            Set @FirstRecord = 0 -- no more first record of the day
            Set @ReceiveInEvent = 1 -- indicate we have received an "IN" event
            Set @FirstEvent = 0  -- no more "first" event
        Else If LOWER(@LogEventID) = 'out' -- OUT event
            If @FirstEvent = 1 -- the first OUT record when change users 
                -- Check day
                If (@CurrentDay != @LogDay) -- change to another day
                    Set @PivotValue = 0 -- Reset
                    Set @PivotValue = @PivotValue + 1 -- increment
                Set @CurrentDay = @LogDay -- update the day

                -- Only an OUT event (no IN event) - invalid record but we show it anyway
                Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
                    PivotValue, LogDate )
                values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
                    DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)))                                              

                Set @FirstEvent = 0 -- not "first" anymore
            Else -- Not first event

                If @ReceiveInEvent = 1 -- if there are IN event previously
                    -- Check day
                    If (@CurrentDay != @InEventDay) -- change to another day                        
                        Set @PivotValue = 0 -- Reset                        
                        Set @PivotValue = @PivotValue + 1 -- increment
                    Set @CurrentDay = @InEventDay -- update the day     
                    Set @CurrTotalHours = @CurrTotalHours +  DATEDIFF(second,@InEventTimestamp, @LogTimeStamp) -- update total time             

                    Set @OutEventRemark = @LogRemark
                    Set @OutEventTerminalIP = @LogTerminalIP
                    Set @OutEventTerminalSN = @LogTerminalSN
                    Set @OutEventTimestamp = @LogTimestamp          
                    -- valid row
                    --Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
                    --  RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
                    --  LogDate)
                    --values( @LogUserID, @InEventDay, @InEventTimestamp, @LogTimestamp,  Datediff(second, @InEventTimestamp, @LogTimeStamp),
                    --  @InEventRemark, @LogRemark, @InEventTerminalIP, @LogTerminalIP, @InEventTerminalSN, @LogTerminalSN, @PivotValue,
                    --  DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))                      

                    Set @ReceiveInEvent = 0 -- Reset
                Else -- no IN event previously
                    -- Check day
                    If (@CurrentDay != @LogDay) -- change to another day
                        Set @PivotValue = 0 -- Reset
                        Set @PivotValue = @PivotValue + 1 -- increment
                    Set @CurrentDay = @LogDay -- update the day                         

                    -- invalid row (only has OUT event)
                    Insert into @tempInOutDetailReport( UserID, LogDay, TimeOUT, RemarkTimeOut, TerminalIPTimeOut, TerminalSNTimeOut,
                        PivotValue, LogDate )
                    values( @LogUserID, @LogDay, @LogTimestamp, @LogRemark, @LogTerminalIP, @LogTerminalSN, @PivotValue,
                        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @LogTimestamp)) )             

        Set @CurrentUser = @LogUserID -- update user        

        Fetch Next 
        From LogCursor
        Into @LogUserID, @LogEventID, @LogTerminalSN, @LogTerminalIP, @LogRemark, @LogTimestamp, @LogDay

    -- Need to handle the last log if its IN log as it will not be processed by the while loop
    if @CurrTrigger='in'
    -- Check day
            If (@CurrentDay != @InEventDay) -- change to another day
                Set @PivotValue = 0 -- Reset
            Else -- same day
                Set @PivotValue = @PivotValue + 1 -- increment
            Set @CurrentDay = @InEventDay -- update the day

            -- invalid row (only has IN event)
            Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, RemarkTimeIn, TerminalIPTimeIn, 
                TerminalSNTimeIn, PivotValue, LogDate )
            values( @InEventUserID, @InEventDay, @InEventTimestamp, @InEventRemark, @InEventTerminalIP, 
                    @InEventTerminalSN, @PivotValue, DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))     
    else if @CurrTrigger = 'out'
        Insert into @tempInOutDetailReport( UserID, LogDay, TimeIN, TimeOUT, TotalTime, RemarkTimeIn,
        RemarkTimeOut, TerminalIPTimeIn, TerminalIPTimeOut, TerminalSNTimeIn, TerminalSNTimeOut, PivotValue,
        values( @LogUserID, @CurrentDay, @FirstInEvent, @LogTimestamp,  @CurrTotalHours,
        @FirstInRemark, @LogRemark, @FirstInTerminalIP, @LogTerminalIP, @FirstInTerminalSN, @LogTerminalSN, @PivotValue,
        DATEADD(HOUR, 0, DATEDIFF(DAY, 0, @InEventTimestamp)))  

    Close LogCursor
    Deallocate LogCursor

    Select * 
    From @tempInOutDetailReport tempTable
        Left Join access_user on access_user.User_ID = tempTable.UserID
    Order By tempTable.UserID, LogDate


If @@TranCount > @TransactionCountOnEntry
     If @ErrorCode = 0

return @ErrorCode

you will get the "java SQL Code" by right click on stored procedure in your database. something like this :

DECLARE @pUserID nvarchar(50)
DECLARE @pDepartmentID int
DECLARE @pStartDateTime datetime
DECLARE @pEndDateTime datetime

-- TODO: Set parameter values here.

EXECUTE @RC = [AccessManager].[dbo].[SP_GenerateInOutDetailReportSimple] 

check the query String I've done, that is your homework ;) so sorry answering this long, this is my first answer since I register few weeks ago to get answer.

How do I manage conflicts with git submodules?

Got help from this discussion. In my case the

git reset HEAD subby
git commit

worked for me :)

Predefined type 'System.ValueTuple´2´ is not defined or imported

In case others have the same problem, I ran into this error after updating a project to 4.7. Oddly enough, I had to remove the System.ValueTuple reference for this error to go away.

How do I parse JSON with Ruby on Rails?

require 'json'

hash = JSON.parse string

work with the hash and do what you want to do.

Notepad++ Regular expression find and delete a line

Combining the best from all the answers

enter image description here

Failed to load resource: the server responded with a status of 404 (Not Found)

I have added app.UseStaticFiles(); this code in my startup.cs than it is fixed

two divs the same line, one dynamic width, one fixed

I've had success with using white-space: nowrap; on the outer container, display: inline-block; on the inner containers, and then (in my case since I wanted the second one to word-wrap) white-space: normal; on the inner ones.

How do I display images from Google Drive on a website?

if you want to embedded Google drive images in your blogger or any sites then just follow the instructions : -


  1. upload the image on google drive
  2. click on image and share with public
  3. <img src=';id=1OCx6mUEMbWcwCQbDePA5PeeOh'/>

How to calculate the sentence similarity using word2vec model of gensim with python

Gensim implements a model called Doc2Vec for paragraph embedding.

There are different tutorials presented as IPython notebooks:

Another method would rely on Word2Vec and Word Mover's Distance (WMD), as shown in this tutorial:

An alternative solution would be to rely on average vectors:

from gensim.models import KeyedVectors
from gensim.utils import simple_preprocess    

def tidy_sentence(sentence, vocabulary):
    return [word for word in simple_preprocess(sentence) if word in vocabulary]    

def compute_sentence_similarity(sentence_1, sentence_2, model_wv):
    vocabulary = set(model_wv.index2word)    
    tokens_1 = tidy_sentence(sentence_1, vocabulary)    
    tokens_2 = tidy_sentence(sentence_2, vocabulary)    
    return model_wv.n_similarity(tokens_1, tokens_2)

wv = KeyedVectors.load('model.wv', mmap='r')
sim = compute_sentence_similarity('this is a sentence', 'this is also a sentence', wv)

Finally, if you can run Tensorflow, you may try:

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

Take note of what is printed for x. You are trying to convert an array (basically just a list) into an int. length-1 would be an array of a single number, which I assume numpy just treats as a float. You could do this, but it's not a purely-numpy solution.

EDIT: I was involved in a post a couple of weeks back where numpy was slower an operation than I had expected and I realised I had fallen into a default mindset that numpy was always the way to go for speed. Since my answer was not as clean as ayhan's, I thought I'd use this space to show that this is another such instance to illustrate that vectorize is around 10% slower than building a list in Python. I don't know enough about numpy to explain why this is the case but perhaps someone else does?

import numpy as np
import matplotlib.pyplot as plt
import datetime

time_start =

# My original answer
def f(x):
    rebuilt_to_plot = []
    for num in x:
    return rebuilt_to_plot

for t in range(10000):
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f(x))

time_end =

# Answer by ayhan
def f_1(x):

for t in range(10000):
    f2 = np.vectorize(f_1)
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f2(x))

time_end_2 =

print time_end - time_start
print time_end_2 - time_end

How to set the range of y-axis for a seaborn boxplot?

It is standard matplotlib.pyplot:

import matplotlib.pyplot as plt
plt.ylim(10, 40)

Or simpler, as mwaskom comments below:

ax.set(ylim=(10, 40))

enter image description here

How to block calls in android

It is possible and you don't need to code it on your own.

Just set the ringer volume to zero and vibration to none if incomingNumber equals an empty string. Thats it ...

Its just done for you with the application Nostalk from Android Market. Just give it a try ...

ReactJs: What should the PropTypes be for this.props.children?

Try something like this utilizing oneOfType or PropTypes.node

import PropTypes from 'prop-types'


static propTypes = {
    children: PropTypes.oneOfType([


static propTypes = {
    children: PropTypes.node.isRequired,

Asserting successive calls to a mock method

I always have to look this one up time and time again, so here is my answer.

Asserting multiple method calls on different objects of the same class

Suppose we have a heavy duty class (which we want to mock):

In [1]: class HeavyDuty(object):
   ...:     def __init__(self):
   ...:         import time
   ...:         time.sleep(2)  # <- Spends a lot of time here
   ...:     def do_work(self, arg1, arg2):
   ...:         print("Called with %r and %r" % (arg1, arg2))

here is some code that uses two instances of the HeavyDuty class:

In [2]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(13, 17)
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(23, 29)

Now, here is a test case for the heavy_work function:

In [3]: from unittest.mock import patch, call
   ...: def test_heavy_work():
   ...:     expected_calls = [call.do_work(13, 17),call.do_work(23, 29)]
   ...:     with patch('__main__.HeavyDuty') as MockHeavyDuty:
   ...:         heavy_work()
   ...:         MockHeavyDuty.return_value.assert_has_calls(expected_calls)

We are mocking the HeavyDuty class with MockHeavyDuty. To assert method calls coming from every HeavyDuty instance we have to refer to MockHeavyDuty.return_value.assert_has_calls, instead of MockHeavyDuty.assert_has_calls. In addition, in the list of expected_calls we have to specify which method name we are interested in asserting calls for. So our list is made of calls to call.do_work, as opposed to simply call.

Exercising the test case shows us it is successful:

In [4]: print(test_heavy_work())

If we modify the heavy_work function, the test fails and produces a helpful error message:

In [5]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(113, 117)  # <- call args are different
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(123, 129)  # <- call args are different

In [6]: print(test_heavy_work())
(traceback omitted for clarity)

AssertionError: Calls not found.
Expected: [call.do_work(13, 17), call.do_work(23, 29)]
Actual: [call.do_work(113, 117), call.do_work(123, 129)]

Asserting multiple calls to a function

To contrast with the above, here is an example that shows how to mock multiple calls to a function:

In [7]: def work_function(arg1, arg2):
   ...:     print("Called with args %r and %r" % (arg1, arg2))

In [8]: from unittest.mock import patch, call
   ...: def test_work_function():
   ...:     expected_calls = [call(13, 17), call(23, 29)]    
   ...:     with patch('__main__.work_function') as mock_work_function:
   ...:         work_function(13, 17)
   ...:         work_function(23, 29)
   ...:         mock_work_function.assert_has_calls(expected_calls)

In [9]: print(test_work_function())

There are two main differences. The first one is that when mocking a function we setup our expected calls using call, instead of using call.some_method. The second one is that we call assert_has_calls on mock_work_function, instead of on mock_work_function.return_value.

Fastest way to check if a file exist using standard C++/C++11/C?

inline bool exist(const std::string& name)
    ifstream file(name);
    if(!file)            // If the file was not found, then file is 0, i.e. !file=1 or true.
        return false;    // The file was not found.
    else                 // If the file was found, then file is non-0.
        return true;     // The file was found.

How can I view the shared preferences file using Android Studio?

To open shared preference in android studio

Open device explorer file from right side- data>data> >shared_prefs

find the attached image for more description

Escape @ character in razor view engine

Actually @ should be used with the Razor syntax Keywords or to the variable/model to bind a Value.

For Eg: if test is assigned with value i.e @ { var test = "ABC" } then you can get the value by settings as @test anywhere is cshtml page in html part. otherwise, simple use as @Html.DisplayName("test")

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector was part of 1.0 -- the original implementation had two drawbacks:

1. Naming: vectors are really just lists which can be accessed as arrays, so it should have been called ArrayList (which is the Java 1.2 Collections replacement for Vector).

2. Concurrency: All of the get(), set() methods are synchronized, so you can't have fine grained control over synchronization.

There is not much difference between ArrayList and Vector, but you should use ArrayList.

From the API doc.

As of the Java 2 platform v1.2, this class was retrofitted to implement the List interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Vector is synchronized.

How to get rid of blank pages in PDF exported from SSRS

If the pages are blank coming from SSRS, you need to tweak your report layout. This will be far more efficient than running the output through and post process to repair the side effects of a layout problem.

SSRS is very finicky when it comes to pushing the boundaries of the margins. It is easy to accidentally widen/lengthen the report just by adjusting text box or other control on the report. Check the width and height property of the report surface carefully and squeeze them as much as possible. Watch out for large headers and footers.

JavaScript, get date of the next day

Using Date object guarantees that. For eg if you try to create April 31st :

new Date(2014,3,31)        // Thu May 01 2014 00:00:00

Please note that it's zero indexed, so Jan. is 0, Feb. is 1 etc.

Installing Git on Eclipse

egit was included in Indigo (2011) and should be there in all future Eclipse versions after that.

Just go to ![(Help->Install New Software)]

Then Work with: --All Available Sites--

Then type egit underneath and wait (may take a while) ! Then click the checkbox and install.

Display a message in Visual Studio's output window when not debug mode?

To write in the Visual Studio output window I used IVsOutputWindow and IVsOutputWindowPane. I included as members in my OutputWindow class which look like this :

public class OutputWindow : TextWriter
  #region Members

  private static readonly Guid mPaneGuid = new Guid("AB9F45E4-2001-4197-BAF5-4B165222AF29");
  private static IVsOutputWindow mOutputWindow = null;
  private static IVsOutputWindowPane mOutputPane = null;


  #region Constructor

  public OutputWindow(DTE2 aDte)
    if( null == mOutputWindow )
      IServiceProvider serviceProvider = 
      new ServiceProvider(aDte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
      mOutputWindow = serviceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;

    if (null == mOutputPane)
      Guid generalPaneGuid = mPaneGuid;
      mOutputWindow.GetPane(ref generalPaneGuid, out IVsOutputWindowPane pane);

      if ( null == pane)
        mOutputWindow.CreatePane(ref generalPaneGuid, "Your output window name", 0, 1);
        mOutputWindow.GetPane(ref generalPaneGuid, out pane);
      mOutputPane = pane;


  #region Properties

  public override Encoding Encoding => System.Text.Encoding.Default;


  #region Public Methods

  public override void Write(string aMessage) => mOutputPane.OutputString($"{aMessage}\n");

  public override void Write(char aCharacter) => mOutputPane.OutputString(aCharacter.ToString());

  public void Show(DTE2 aDte)
    aDte.ExecuteCommand("View.Output", string.Empty);

  public void Clear() => mOutputPane.Clear();


If you have a big text to write in output window you usually don't want to freeze the UI. In this purpose you can use a Dispatcher. To write something in output window using this implementation now you can simple do this:

Dispatcher mDispatcher = HwndSource.FromHwnd((IntPtr)mDte.MainWindow.HWnd).RootVisual.Dispatcher;

using (OutputWindow outputWindow = new OutputWindow(mDte))
  mDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
    outputWindow.Write("Write what you want here");

Java Command line arguments

Command-line arguments are passed in the first String[] parameter to main(), e.g.

public static void main( String[] args ) {

In the example above, args contains all the command-line arguments.

The short, sweet answer to the question posed is:

public static void main( String[] args ) {
    if( args.length > 0 && args[0].equals( "a" ) ) {
        // first argument is "a"
    } else {
        // oh noes!?

How to find column names for all tables in all databases in SQL Server

user @KM say best Answer.

I Use This :

Declare @Table_Name VarChar(100) ,@Column_Name VarChar(100)
Set @Table_Name = ''
Set @Column_Name = ''

RowNumber = Row_Number() Over( PARTITION BY T.[Name] Order By T.[Name],C.column_id  ),
SCHEMA_NAME( T.schema_id ) As SchemaName ,  
T.[Name] As Table_Name ,
C.[Name] As Field_Name , ,
C.max_length , C.is_nullable , C.is_identity , C.scale , C.precision  
From Sys.Tables As T
Left Join Sys.Columns As C On ( T.[Object_Id] = C.[Object_Id] )
Left Join sys.types As sysType On ( C.user_type_id = sysType.user_type_id )
Where ( Type = 'U' )
    And ( C.Name Like '%' + @Column_Name + '%' )  
    And ( T.Name Like '%' + @Table_Name + '%' ) 

Script Tag - async & defer

HTML5: async, defer

In HTML5, you can tell browser when to run your JavaScript code. There are 3 possibilities:

<script       src="myscript.js"></script>

<script async src="myscript.js"></script>

<script defer src="myscript.js"></script>
  1. Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.

  2. With async (asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.

  3. With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. This is good.)

Revert to a commit by a SHA hash in Git?

It reverts the said commit, that is, adds the commit opposite to it. If you want to checkout an earlier revision, you do:

git checkout 56e05fced214c44a37759efa2dfc25a65d8ae98d

Padding a table row

The trick is to give padding on the td elements, but make an exception for the first (yes, it's hacky, but sometimes you have to play by the browser's rules):

td {

td:first-child {

First-child is relatively well supported:

You can use the same reasoning for the horizontal padding by using tr:first-child td.

Alternatively, exclude the first column by using the not operator. Support for this is not as good right now, though.

td:not(:first-child) {

How to add include path in Qt Creator?

For anyone completely new to Qt Creator like me, you can modify your project's .pro file from within Qt Creator:

enter image description here

Just double-click on "your project name".pro in the Projects window and add the include path at the bottom of the .pro file like I've done.

How can I make the browser wait to display the page until it's fully loaded?

You could start by having your site's main index page contain only a message saying "Loading". From here you could use ajax to fetch the contents of your next page and embed it into the current one, on completion removing the "Loading" message.

You might be able to get away with just including a loading message container at the top of your page which is 100% width/height and then removing the said div on load complete.

The latter may not work perfectly in both situations and will depends on how the browser renders content.

I'm not entirely sure if its a good idea. For simple static sites I would say not. However, I have seen a lot of heavy javascript sites lately from design companies that use complex animation and are one page. These sites use a loading message to wait for all scripts/html/css to be loaded so that the page functions as expected.

How do I read the contents of a Node.js stream into a string variable?

Using the quite popular stream-buffers package which you probably already have in your project dependencies, this is pretty straightforward:

// imports
const { WritableStreamBuffer } = require('stream-buffers');
const { promisify } = require('util');
const { createReadStream } = require('fs');
const pipeline = promisify(require('stream').pipeline);

// sample stream
let stream = createReadStream('/etc/hosts');

// pipeline the stream into a buffer, and print the contents when done
let buf = new WritableStreamBuffer();
pipeline(stream, buf).then(() => console.log(buf.getContents().toString()));

How do I find the CPU and RAM usage using PowerShell?

Get-WmiObject Win32_Processor | Select LoadPercentage | Format-List

This gives you CPU load.

Get-WmiObject Win32_Processor | Measure-Object -Property LoadPercentage -Average | Select Average Date without time

I almost always use the standard formating ShortDateString, because I want the user to be in control of the actual output of the date.


   Dim d As DateTime = Now


Wednesday, December 10, 2008

Note that these results will vary depending on the culture settings on your computer.

Android: How to create a Dialog without a title?

set the "gravity" attribute on the entire dialog to "center". Then you will need to override that setting to all of the child components in the dialog that you do not want centered.

How to get the integer value of day of week

day1= (int)ClockInfoFromSystem.DayOfWeek;

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

I had the same problem - solved it by setting display_errors = On in both php.ini files.


Then restarting Apache:

sudo /etc/init.d/apache2 restart

Hope this helps.

how to toggle (hide/show) a table onClick of <a> tag in java script

Simple using jquery

$(document).ready(function() {
    $('#loginLink').click(function() {

DataGridView checkbox column - value and functionality

  1. There is no way to do that directly. Once you have your data in the grid, you can loop through the rows and check each box like this:

    foreach (DataGridViewRow row in dataGridView1.Rows)
        row.Cells[CheckBoxColumn1.Name].Value = true;
  2. The Click event might look something like this:

    private void button1_Click(object sender, EventArgs e)
        List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();
        foreach (DataGridViewRow row in dataGridView1.Rows)
            if (Convert.ToBoolean(row.Cells[CheckBoxColumn1.Name].Value) == true)
        // Do what you want with the check rows

How can I check if my Element ID has focus?

Write below code in script and also add jQuery library

var getElement = document.getElementById('myID');

if (document.activeElement === getElement) {
        $(document).keydown(function(event) {
            if (event.which === 40) {
                console.log('keydown pressed')

Thank you...

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

In my case I just needed to remove Homebrew's executable using:

sudo rm -f `which brew`

Then reinstall Homebrew:

ruby -e "$(curl -fsSL"

json_decode to array

json_decode support second argument, when it set to TRUE it will return an Array instead of stdClass Object. Check the Manual page of json_decode function to see all the supported arguments and its details.

For example try this:

$json_string = '';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, TRUE); // Set second argument as TRUE
print_r($obj['Result']); // Now this will works!

How to simulate a mouse click using JavaScript?

From the Mozilla Developer Network (MDN) documentation, is what you're looking for. You can find out more events here.

How to control size of list-style-type disc in CSS?

You can also use 2D transform. It is illustrated in the snippet below with a list being scaled by 25%.

Nota: Bootstrap is used here for the sole purpose of layouting the demo (before/after effect).

ul#before {_x000D_
ul#after {_x000D_
  transform: scale(1.25);_x000D_
div.container, div.row {_x000D_
  padding: 20px;_x000D_
ul {_x000D_
  border: 6px solid #000000;_x000D_
<!-- Bootstrap CSS -->_x000D_
<link rel="stylesheet" href="" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
<!-- Bootstrap theme -->_x000D_
<link rel="stylesheet" href="" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">_x000D_
<!-- HTML -->_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-5">_x000D_
    <div class="col-xs-5 col-xs-offset-1">_x000D_
      After (scale 25%)_x000D_
  <div class="row">_x000D_
    <div class="col-xs-5">_x000D_
      <ul id="before">_x000D_
        <li>Lorem ipsum dolor sit amet...</li>_x000D_
        <li>In vel ante vel est accumsan...</li>_x000D_
        <li>In elementum libero vel...</li>_x000D_
        <li>Nam ut ante a sem mattis...</li>_x000D_
        <li>Curabitur fermentum nisl...</li>_x000D_
        <li>Praesent vel risus ultrices...</li>_x000D_
    <div class="col-xs-5 col-xs-offset-1">_x000D_
      <ul id="after">_x000D_
        <li>Lorem ipsum dolor sit amet...</li>_x000D_
        <li>In vel ante vel est accumsan...</li>_x000D_
        <li>In elementum libero vel...</li>_x000D_
        <li>Nam ut ante a sem mattis...</li>_x000D_
        <li>Curabitur fermentum nisl...</li>_x000D_
        <li>Praesent vel risus ultrices...</li>_x000D_
<!-- JQuery -->_x000D_
<script src=""></script>_x000D_
<!-- Bootstrap JS -->_x000D_
<script src="" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>


how to open popup window using jsp or jquery?

Try this:


function winOpen()


<a href="javascript:;" onclick="winOpen()">Pop Up</a>

Read for

How to redirect to the same page in PHP

Another elegant one is

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");

Enable CORS in Web API 2

For reference using the [EnableCors()] approach will not work if you intercept the Message Pipeline using a DelegatingHandler. In my case was checking for an Authorization header in the request and handling it accordingly before the routing was even invoked, which meant my request was getting processed earlier in the pipeline so the [EnableCors()] had no effect.

In the end found an example CrossDomainHandler class (credit to shaunxu for the Gist) which handles the CORS for me in the pipeline and to use it is as simple as adding another message handler to the pipeline.

public class CrossDomainHandler : DelegatingHandler
        const string Origin = "Origin";
        const string AccessControlRequestMethod = "Access-Control-Request-Method";
        const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
        const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
        const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            bool isCorsRequest = request.Headers.Contains(Origin);
            bool isPreflightRequest = request.Method == HttpMethod.Options;
            if (isCorsRequest)
                if (isPreflightRequest)
                    return Task.Factory.StartNew(() =>
                        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                        response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

                        string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                        if (accessControlRequestMethod != null)
                            response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);

                        string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
                        if (!string.IsNullOrEmpty(requestedHeaders))
                            response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);

                        return response;
                    }, cancellationToken);
                    return base.SendAsync(request, cancellationToken).ContinueWith(t =>
                        HttpResponseMessage resp = t.Result;
                        resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                        return resp;
                return base.SendAsync(request, cancellationToken);

To use it add it to the list of registered message handlers

config.MessageHandlers.Add(new CrossDomainHandler());

Any preflight requests by the Browser are handled and passed on, meaning I didn't need to implement an [HttpOptions] IHttpActionResult method on the Controller.

Django CharField vs TextField

For eg.,. 2 fields are added in a model like below..

description = models.TextField(blank=True, null=True)
title = models.CharField(max_length=64, blank=True, null=True)

Below are the mysql queries executed when migrations are applied.

for TextField(description) the field is defined as a longtext

ALTER TABLE `sometable_sometable` ADD COLUMN `description` longtext NULL;

The maximum length of TextField of MySQL is 4GB according to string-type-overview.

for CharField(title) the max_length(required) is defined as varchar(64)

ALTER TABLE `sometable_sometable` ADD COLUMN `title` varchar(64) NULL;
ALTER TABLE `sometable_sometable` ALTER COLUMN `title` DROP DEFAULT;

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)

The only reason that the names matter is the default make rules, visible via make -p, which use some of them.

If you write all your own rules, you get to pick all your own macro names.

In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS, CPPFLAGS, and CXXFLAGS. CFLAGS for the C compiler, CXXFLAGS for C++, and CPPFLAGS for both.

Why is CPPFLAGS in both? Conventionally, it's the home of preprocessor flags (-D, -U) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.

P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.

how to force maven to update local repo

Even though this is an old question, I 've stumbled upon this issue multiple times and until now never figured out how to fix it. The update maven indices is a term coined by IntelliJ, and if it still doesn't work after you've compiled the first project, chances are that you are using 2 different maven installations.

Press CTRL+Shift+A to open up the Actions menu. Type Maven and go to Maven Settings. Check the Home Directory to use the same maven as you use via the command line

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

I know this is not fully relevant, but since this answer is ranked first many a times when you search 'how to display images in Jupyter', please consider this answer as well.

You could use matplotlib to show an image as follows.

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread("your_image.png")

Adding VirtualHost fails: Access Forbidden Error 403 (XAMPP) (Windows 7)

I am using xampp 1.7.3. Using inspiration from here: xampp 1.7.3 upgrade broken virtual hosts access forbidden

INSTEAD OF add <Directory> .. </Directory> in httpd-vhosts.conf, I add it in httpd.conf right after <Directory "D:/xampplite/cgi-bin"> .. </Directory>.

Here is what I add in httpd.conf:

<Directory "D:/CofeeShop">
    AllowOverride All
    Options  All
    Order allow,deny
    Allow from all

And here is what I add in httpd-vhosts.conf

<VirtualHost *:8001>
    ServerAdmin [email protected]
    DocumentRoot "D:/CofeeShop"
    ServerName localhost:8001

I also add Listen 8001 in httpd.conf to complete my setting.

Hope it helps

Nginx no-www to www and www to no-www

  1. Best Practice: separate server w/ hardcoded server_name

Best practice with nginx is to use a separate server for a redirect like this (not shared with the server of your main configuration), to hardcode everything, and not use regular expressions at all.

It may also be necessary to hardcode the domains if you're using HTTPS, because you have to know upfront which certificates you'll be providing.

server {
    return  301 $scheme://$request_uri;
server {
    return  301 $scheme://$request_uri;
server {
    # real configuration goes here

  1. Using Regular Expressions within server_name

If you have a number of sites, and don't care for the most ultimate performance, but want every single one of them to have the same policy in regards to the www. prefix, then you can use regular expressions. The best practice of using a separate server would still stand.

Note that this solution gets tricky if you use https, as you must then have a single certificate to cover all of your domain names if you want this to work properly.

non-www to www w/ regex in a dedicated single server for all sites:

server {
    server_name ~^(?!www\.)(?<domain>.+)$;
    return  301 $scheme://www.$domain$request_uri;

www to non-www w/ regex in a dedicated single server for all sites:

server {
    server_name ~^www\.(?<domain>.+)$;
    return  301 $scheme://$domain$request_uri;

www to non-www w/ regex in a dedicated server for some sites only:

It may be necessary to restrict the regex to cover only a couple of domains, then you can use something like this to only match, and

server {
    server_name ~^www\.(?<domain>(?:example\.org|example\.com|subdomain\.example\.net))$;
    return  301 $scheme://$domain$request_uri;

Testing Regular Expressions w/ nginx

You can test that the regex works as expected with pcretest on your system, which is the exact same pcre library that your nginx will be using for regular expressions:

% pcretest 
PCRE version 8.35 2014-04-04

  re> #^www\.(?<domain>(?:example\.org|example\.com|subdomain\.example\.net))$#
data> test
No match
No match
No match
No match

Note that you don't have to worry about trailing dots or case, as nginx already takes care of it, as per nginx server name regex when "Host" header has a trailing dot.

  1. Sprinkle if within existing server / HTTPS:

This final solution is generally not considered to be the best practice, however, it still works and does the job.

In fact, if you're using HTTPS, then this final solution may end up easier to maintain, as you wouldn't have to copy-paste a whole bunch of ssl directives between the different server definitions, and could instead place the snippets only into the needed servers, making it easier to debug and maintain your sites.

non-www to www:

if ($host ~ ^(?!www\.)(?<domain>.+)$) {
    return  301 $scheme://www.$domain$request_uri;

www to non-www:

if ($host ~ ^www\.(?<domain>.+)$) {
    return  301 $scheme://$domain$request_uri;

hardcoding a single preferred domain

If you want a little bit more performance, as well as consistency between multiple domains a single server may use, it might still make sense to explicitly hardcode a single preferred domain:

if ($host != "") {
    return  301 $scheme://$request_uri;


The maximum value for an int type in Go for physical type limits.

The max values are defined in the math package so in your case: math.MaxUint32

Watch out as there is no overflow - incrementing past max causes wraparound.

How to remove part of a string?

Dynamically, if you want to remove (a) part(s) from (a) fixed index(es) of a string, use this function:

 * Removes index/indexes from a string, using a delimiter.
 * @param string $string
 * @param int|int[] $index An index, or a list of indexes to be removed from string.
 * @param string $delimiter 
 * @return string
 * @todo Note: For PHP versions lower than 7.0, remove scalar type hints (i.e. the
 * types before each argument) and the return type.
function removeFromString(string $string, $index, string $delimiter = " "): string
    $stringParts = explode($delimiter, $string);

    // Remove indexes from string parts
    if (is_array($index)) {
        foreach ($index as $i) {
    } else {

    // Join all parts together and return it
    return implode($delimiter, $stringParts);

For your purpose:

remove_from_str("REGISTER 11223344 here", 1); // Output: REGISTER here

One of its usages is to execute command-like strings, which you know their structures.

How do you share constants in NodeJS modules?

I found the solution Dominic suggested to be the best one, but it still misses one feature of the "const" declaration. When you declare a constant in JS with the "const" keyword, the existence of the constant is checked at parse time, not at runtime. So if you misspelled the name of the constant somewhere later in your code, you'll get an error when you try to start your node.js program. Which is a far more better misspelling check.

If you define the constant with the define() function like Dominic suggested, you won't get an error if you misspelled the constant, and the value of the misspelled constant will be undefined (which can lead to debugging headaches).

But I guess this is the best we can get.

Additionally, here's a kind of improvement of Dominic's function, in constans.js:

global.define = function ( name, value, exportsObject )
    if ( !exportsObject )
        if ( exports.exportsObject )
            exportsObject = exports.exportsObject;
            exportsObject = exports;        

    Object.defineProperty( exportsObject, name, {
        'value': value,
        'enumerable': true,
        'writable': false,

exports.exportObject = null;

In this way you can use the define() function in other modules, and it allows you to define constants both inside the constants.js module and constants inside your module from which you called the function. Declaring module constants can then be done in two ways (in script.js).


require( './constants.js' );

define( 'SOME_LOCAL_CONSTANT', "const value 1", this ); // constant in script.js
define( 'SOME_OTHER_LOCAL_CONSTANT', "const value 2", this ); // constant in script.js

define( 'CONSTANT_IN_CONSTANTS_MODULE', "const value x" ); // this is a constant in constants.js module


constants = require( './constants.js' );

// More convenient for setting a lot of constants inside the module
constants.exportsObject = this;
define( 'SOME_CONSTANT', "const value 1" ); // constant in script.js
define( 'SOME_OTHER_CONSTANT', "const value 2" ); // constant in script.js

Also, if you want the define() function to be called only from the constants module (not to bloat the global object), you define it like this in constants.js:

exports.define = function ( name, value, exportsObject )

and use it like this in script.js:

constants.define( 'SOME_CONSTANT', "const value 1" );

Class method differences in Python: bound, unbound and static

In Python, there is a distinction between bound and unbound methods.

Basically, a call to a member function (like method_one), a bound function


is translated to


i.e. a call to an unbound method. Because of that, a call to your version of method_two will fail with a TypeError

>>> a_test = Test() 
>>> a_test.method_two()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: method_two() takes no arguments (1 given) 

You can change the behavior of a method using a decorator

class Test(object):
    def method_one(self):
        print "Called method_one"

    def method_two():
        print "Called method two"

The decorator tells the built-in default metaclass type (the class of a class, cf. this question) to not create bound methods for method_two.

Now, you can invoke static method both on an instance or on the class directly:

>>> a_test = Test()
>>> a_test.method_one()
Called method_one
>>> a_test.method_two()
Called method_two
>>> Test.method_two()
Called method_two

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page about implementing this on Twenty Sixteen theme, so feel free to check it out :)


I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>

    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">


add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;

function load_posts(){
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            } else{
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);

    return false;

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here


For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

How do I compare two columns for equality in SQL Server?

The use of IIF? And it depends on version of SQL Server.

IIF(Column1 = Column2, 1, 0) AS MyDesiredResult
FROM Table;

Inserting an image with PHP and FPDF

You can use $pdf->GetX() and $pdf->GetY() to get current cooridnates and use them to insert image.

$pdf->Image($image1, 5, $pdf->GetY(), 33.78);

or even

$pdf->Image($image1, 5, null, 33.78);

(ALthough in first case you can add a number to create a bit of a space)

$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);

Tkinter module not found on Ubuntu

Use the following command:

sudo apt-get install python3-tk

The following commands do not work:

sudo apt-get install python3-tkinter
sudo apt-get install python3-Tkinter
pip3 install Tkinter
pip3 install tkinter

What key shortcuts are to comment and uncomment code?

You can also add the toolbar in Visual Studio to have the buttons available.

View > Toolbars > Text Editor

enter image description here

What does it mean by command cd /d %~dp0 in Windows

~dp0 : d=drive, p=path, %0=full path\name of this batch-file.

cd /d %~dp0 will change the path to the same, where the batch file resides.

See for /? or call / for more details about the %~... modifiers.
See cd /? about the /d switch.

How does Java deal with multiple conditions inside a single IF statement

Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false?

Its not a matter of being smart, its a requirement specified in the language. Otherwise you couldn't write expressions like.

if(s != null && s.length() > 0)


if(s == null || s.length() == 0)

BTW if you use & and | it will always evaluate both sides of the expression.

Creating a new ArrayList in Java

Java 8

In order to create a non-empty list of fixed size where different operations like add, remove, etc won't be supported:

List<Integer> fixesSizeList= Arrays.asList(1, 2);

Non-empty mutable list:

List<Integer> mutableList = new ArrayList<>(Arrays.asList(3, 4));

Java 9

With Java 9 you can use the List.of(...) static factory method:

List<Integer> immutableList = List.of(1, 2);

List<Integer> mutableList = new ArrayList<>(List.of(3, 4));

Java 10

With Java 10 you can use the Local Variable Type Inference:

var list1 = List.of(1, 2);

var list2 = new ArrayList<>(List.of(3, 4));

var list3 = new ArrayList<String>();

Check out more ArrayList examples here.

Simple way to compare 2 ArrayLists

The answer is given in @dku-rajkumar post.

ArrayList commonList = CollectionUtils.retainAll(list1,list2);

How can I check if a Perl array contains a particular value?

Even though it's convenient to use, it seems like the convert-to-hash solution costs quite a lot of performance, which was an issue for me.

use Benchmark;
my @list;
for (1..10_000) {
    push @list, $_;

timethese(10000, {
  'grep'    => sub {
            if ( grep(/^5000$/o, @list) ) {
                # code
  'hash'    => sub {
            my %params = map { $_ => 1 } @list;
            if ( exists($params{5000}) ) {
                # code

Output of benchmark test:

Benchmark: timing 10000 iterations of grep, hash...
          grep:  8 wallclock secs ( 7.95 usr +  0.00 sys =  7.95 CPU) @ 1257.86/s (n=10000)
          hash: 50 wallclock secs (49.68 usr +  0.01 sys = 49.69 CPU) @ 201.25/s (n=10000)

WARNING: Can't verify CSRF token authenticity rails

Ugrading from an older app to rails 3.1, including the csrf meta tag is still not solving it. On the blog, they give some upgrade tips, and specifically this line of jquery which should go in the head section of your layout:

$(document).ajaxSend(function(e, xhr, options) {
 var token = $("meta[name='csrf-token']").attr("content");
  xhr.setRequestHeader("X-CSRF-Token", token);

taken from this blog post:

In my case, the session was being reset upon each ajax request. Adding the above code solved that issue.

How to get the seconds since epoch from the time + date output of gmtime()?

Note that time.gmtime maps timestamp 0 to 1970-1-1 00:00:00.

In [61]: import time       
In [63]: time.gmtime(0)
Out[63]: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

time.mktime(time.gmtime(0)) gives you a timestamp shifted by an amount that depends on your locale, which in general may not be 0.

In [64]: time.mktime(time.gmtime(0))
Out[64]: 18000.0

The inverse of time.gmtime is calendar.timegm:

In [62]: import calendar    
In [65]: calendar.timegm(time.gmtime(0))
Out[65]: 0

if A vs if A is not None:

python >= 2.6,

if we write such as

if A:

will generate warning as,

FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead.

So we can use

if A is not None:

alternative to "!is.null()" in R

You may be better off working out what value type your function or code accepts, and asking for that:

if (is.integer(aVariable))
  do whatever

This may be an improvement over isnull, because it provides type checking. On the other hand, it may reduce the genericity of your code.

Alternatively, just make the function you want:

is.defined = function(x)!is.null(x)

Is a URL allowed to contain a space?

Can someone point to an RFC indicating that a URL with a space must be encoded?

URIs, and thus URLs, are defined in RFC 3986.

If you look at the grammar defined over there you will eventually note that a space character never can be part of a syntactically legal URL, thus the term "URL with a space" is a contradiction in itself.

ssh_exchange_identification: Connection closed by remote host under Git bash

Hit the following ssh restart command in linux

prayag@prayag:~/backup/NoisyNeighbour$ service ssh restart 
stop: Rejected send message, 1 matched rules; type="method_call", sender=":1.75" (uid=1417676764 pid=5933 comm="stop ssh ") interface="com.ubuntu.Upstart0_6.Job" member="Stop" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init")
start: Rejected send message, 1 matched rules; type="method_call", sender=":1.76" (uid=1417676764 pid=5930 comm="start ssh ") interface="com.ubuntu.Upstart0_6.Job" member="Start" error name="(unset)" requested_reply="0" destination="com.ubuntu.Upstart" (uid=0 pid=1 comm="/sbin/init")

Convert a space delimited string to list

Use string's split() method.


How do I format a string using a dictionary in python-3.x?

geopoint = {'latitude':41.123,'longitude':71.091}

# working examples.
print(f'{geopoint["latitude"]} {geopoint["longitude"]}') # from above answer
print('{geopoint[latitude]} {geopoint[longitude]}'.format(geopoint=geopoint)) # alternate for format method  (including dict name in string).
print('%(latitude)s %(longitude)s'%geopoint) # thanks @tcll

ValueError: unconverted data remains: 02:05

You have to parse all of the input string, you cannot just ignore parts.

from datetime import date, datetime

for item in j:
    st = datetime.strptime(item['start'], '%A %d %B %H:%M')

    if ==
        item['start'] = st.time()

Here, we compare the date to today's date by using more datetime objects instead of trying to use strings.

The alternative is to only pass in part of the item['start'] string (splitting out just the time), but there really is no point here, not when you could just parse everything in one step first.

How to break out from a ruby block?

Perhaps you can use the built-in methods for finding particular items in an Array, instead of each-ing targets and doing everything by hand. A few examples:

class Array
  def first_frog
    detect {|i| i =~ /frog/ }

  def last_frog
    select {|i| i =~ /frog/ }.last

p ["dog", "cat", "godzilla", "dogfrog", "woot", "catfrog"].first_frog
# => "dogfrog"
p ["hats", "coats"].first_frog
# => nil
p ["houses", "frogcars", "bottles", "superfrogs"].last_frog
# => "superfrogs"

One example would be doing something like this:

class Bar
  def do_things
    Foo.some_method(x) do |i|
      # only valid `targets` here, yay.

class Foo
  def self.failed
    @failed ||= []

  def self.some_method(targets, &block)
    targets.reject {|t| t.do_something.bad? }.each(&block)

Git command to display HEAD commit id?

Play with Bash:

git show HEAD | sed -n 1p | cut -d " " -f 2

There is already an open DataReader associated with this Command which must be closed first

In my case, using Include() solved this error and depending on the situation can be a lot more efficient then issuing multiple queries when it can all be queried at once with a join.

IEnumerable<User> users = db.Users.Include("Projects.Tasks.Messages");

foreach (User user in users)
    foreach (Project project in user.Projects)
        foreach (Task task in project.Tasks)
            Console.WriteLine("\t\t" + task.Subject);
            foreach (Message message in task.Messages)
                Console.WriteLine("\t\t\t" + message.Text);

How to Debug Variables in Smarty like in PHP var_dump()

You can use {php} tags

Method 1 (won't work in Smarty 3.1 or later):


$var =


Method 2:


Method 3:


How do you clear the SQL Server transaction log?

Making a log file smaller should really be reserved for scenarios where it encountered unexpected growth which you do not expect to happen again. If the log file will grow to the same size again, not very much is accomplished by shrinking it temporarily. Now, depending on the recovery goals of your database, these are the actions you should take.

First, take a full backup

Never make any changes to your database without ensuring you can restore it should something go wrong.

If you care about point-in-time recovery

(And by point-in-time recovery, I mean you care about being able to restore to anything other than a full or differential backup.)

Presumably your database is in FULL recovery mode. If not, then make sure it is:


Even if you are taking regular full backups, the log file will grow and grow until you perform a log backup - this is for your protection, not to needlessly eat away at your disk space. You should be performing these log backups quite frequently, according to your recovery objectives. For example, if you have a business rule that states you can afford to lose no more than 15 minutes of data in the event of a disaster, you should have a job that backs up the log every 15 minutes. Here is a script that will generate timestamped file names based on the current time (but you can also do this with maintenance plans etc., just don't choose any of the shrink options in maintenance plans, they're awful).

DECLARE @path NVARCHAR(255) = N'\\backup_share\log\testdb_' 
  + CONVERT(CHAR(8), GETDATE(), 112) + '_'
  + REPLACE(CONVERT(CHAR(8), GETDATE(), 108),':','')
  + '.trn';


Note that \\backup_share\ should be on a different machine that represents a different underlying storage device. Backing these up to the same machine (or to a different machine that uses the same underlying disks, or a different VM that's on the same physical host) does not really help you, since if the machine blows up, you've lost your database and its backups. Depending on your network infrastructure it may make more sense to backup locally and then transfer them to a different location behind the scenes; in either case, you want to get them off the primary database machine as quickly as possible.

Now, once you have regular log backups running, it should be reasonable to shrink the log file to something more reasonable than whatever it's blown up to now. This does not mean running SHRINKFILE over and over again until the log file is 1 MB - even if you are backing up the log frequently, it still needs to accommodate the sum of any concurrent transactions that can occur. Log file autogrow events are expensive, since SQL Server has to zero out the files (unlike data files when instant file initialization is enabled), and user transactions have to wait while this happens. You want to do this grow-shrink-grow-shrink routine as little as possible, and you certainly don't want to make your users pay for it.

Note that you may need to back up the log twice before a shrink is possible (thanks Robert).

So, you need to come up with a practical size for your log file. Nobody here can tell you what that is without knowing a lot more about your system, but if you've been frequently shrinking the log file and it has been growing again, a good watermark is probably 10-50% higher than the largest it's been. Let's say that comes to 200 MB, and you want any subsequent autogrowth events to be 50 MB, then you can adjust the log file size this way:

USE [master];
  (NAME = yourdb_log, SIZE = 200MB, FILEGROWTH = 50MB);

Note that if the log file is currently > 200 MB, you may need to run this first:

USE yourdb;
DBCC SHRINKFILE(yourdb_log, 200);

If you don't care about point-in-time recovery

If this is a test database, and you don't care about point-in-time recovery, then you should make sure that your database is in SIMPLE recovery mode.


Putting the database in SIMPLE recovery mode will make sure that SQL Server re-uses portions of the log file (essentially phasing out inactive transactions) instead of growing to keep a record of all transactions (like FULL recovery does until you back up the log). CHECKPOINT events will help control the log and make sure that it doesn't need to grow unless you generate a lot of t-log activity between CHECKPOINTs.

Next, you should make absolute sure that this log growth was truly due to an abnormal event (say, an annual spring cleaning or rebuilding your biggest indexes), and not due to normal, everyday usage. If you shrink the log file to a ridiculously small size, and SQL Server just has to grow it again to accommodate your normal activity, what did you gain? Were you able to make use of that disk space you freed up only temporarily? If you need an immediate fix, then you can run the following:

USE yourdb;
CHECKPOINT; -- run twice to ensure file wrap-around
DBCC SHRINKFILE(yourdb_log, 200); -- unit is set in MBs

Otherwise, set an appropriate size and growth rate. As per the example in the point-in-time recovery case, you can use the same code and logic to determine what file size is appropriate and set reasonable autogrowth parameters.

Some things you don't want to do

  • Back up the log with TRUNCATE_ONLY option and then SHRINKFILE. For one, this TRUNCATE_ONLY option has been deprecated and is no longer available in current versions of SQL Server. Second, if you are in FULL recovery model, this will destroy your log chain and require a new, full backup.

  • Detach the database, delete the log file, and re-attach. I can't emphasize how dangerous this can be. Your database may not come back up, it may come up as suspect, you may have to revert to a backup (if you have one), etc. etc.

  • Use the "shrink database" option. DBCC SHRINKDATABASE and the maintenance plan option to do the same are bad ideas, especially if you really only need to resolve a log problem issue. Target the file you want to adjust and adjust it independently, using DBCC SHRINKFILE or ALTER DATABASE ... MODIFY FILE (examples above).

  • Shrink the log file to 1 MB. This looks tempting because, hey, SQL Server will let me do it in certain scenarios, and look at all the space it frees! Unless your database is read only (and it is, you should mark it as such using ALTER DATABASE), this will absolutely just lead to many unnecessary growth events, as the log has to accommodate current transactions regardless of the recovery model. What is the point of freeing up that space temporarily, just so SQL Server can take it back slowly and painfully?

  • Create a second log file. This will provide temporarily relief for the drive that has filled your disk, but this is like trying to fix a punctured lung with a band-aid. You should deal with the problematic log file directly instead of just adding another potential problem. Other than redirecting some transaction log activity to a different drive, a second log file really does nothing for you (unlike a second data file), since only one of the files can ever be used at a time. Paul Randal also explains why multiple log files can bite you later.

Be proactive

Instead of shrinking your log file to some small amount and letting it constantly autogrow at a small rate on its own, set it to some reasonably large size (one that will accommodate the sum of your largest set of concurrent transactions) and set a reasonable autogrow setting as a fallback, so that it doesn't have to grow multiple times to satisfy single transactions and so that it will be relatively rare for it to ever have to grow during normal business operations.

The worst possible settings here are 1 MB growth or 10% growth. Funny enough, these are the defaults for SQL Server (which I've complained about and asked for changes to no avail) - 1 MB for data files, and 10% for log files. The former is much too small in this day and age, and the latter leads to longer and longer events every time (say, your log file is 500 MB, first growth is 50 MB, next growth is 55 MB, next growth is 60.5 MB, etc. etc. - and on slow I/O, believe me, you will really notice this curve).

Further reading

Please don't stop here; while much of the advice you see out there about shrinking log files is inherently bad and even potentially disastrous, there are some people who care more about data integrity than freeing up disk space.

A blog post I wrote in 2009, when I saw a few "here's how to shrink the log file" posts spring up.

A blog post Brent Ozar wrote four years ago, pointing to multiple resources, in response to a SQL Server Magazine article that should not have been published.

A blog post by Paul Randal explaining why t-log maintenance is important and why you shouldn't shrink your data files, either.

Mike Walsh has a great answer covering some of these aspects too, including reasons why you might not be able to shrink your log file immediately.

input() error - NameError: name '...' is not defined

Here is an input function which is compatible with both Python 2.7 and Python 3+: (Slightly modified answer by @Hardian) to avoid UnboundLocalError: local variable 'input' referenced before assignment error

def input_compatible(prompt=None):
        input_func = raw_input
    except NameError:
        input_func = input
    return input_func(prompt)

How can I connect to a Tor hidden service using cURL in PHP?

Try to add this:

curl_setopt($ch, CURLOPT_HEADER, 1); 
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); 

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

How can I clear the terminal in Visual Studio Code?

  1. Just click the gear button on the left-bottom side on the VS code screen
  2. then Search for "Terminal: clear"
  3. By default no keyboard shortcut is assigned.
  4. Just double click the Terminal: Clear
  5. and give the preferred shortcut of your choice to clear the terminal.
  6. Usually ctrl+k is used as that shortcut is not assigned with any command.

FYI: This method is the same as @SuRa but is a little simpler. Btw: I use VS Code version 1.43.0

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

That works in new browsers i.e. IE11+ see table at the bottom of the article.

INSERT INTO from two different server database

The answer given by Simon works fine for me but you have to do it in the right sequence: First you have to be in the server that you want to insert data into which is [DATABASE.WINDOWS.NET].[basecampdev] in your case.

You can try to see if you can select some data out of the Invoice table to make sure you have access.

Select top 10 * from [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]

Secondly, execute the query given by Simon in order to link to a different server. This time use the other server:

EXEC sp_addlinkedserver [BC1-PC]; -- this will create a link tempdb that you can access from where you are
USE tempdb;
    [BC1-PC].testdabse.dbo.invoice; -- Make a copy of the table and data that you can use

Now just do your insert statement.

INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
SELECT [InvoiceNumber]
       ,[Remarks] FROM MyInvoice

Hope this helps!

Insert PHP code In WordPress Page and Post

When I was trying to accomplish something very similar, I ended up doing something along these lines:


add_action('init', 'my_php_function');
function my_php_function() {
    if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
        // add desired php code here

Playing a MP3 file in a WinForm application

You can do it using old DirectShow functionality.

This answer teaches you how to create QuartzTypeLib.dll:

  1. Run tlbimp tool (in your case path will be different):

  2. Run TlbImp.exe %windir%\system32\quartz.dll /out:QuartzTypeLib.dll

Alternatively, this project contains the library interop.QuartzTypeLib.dll, which is basically the same thing as steps 1. and 2. The following steps teach how to use this library:

  1. Add generated QuartzTypeLib.dll as a COM-reference to your project (click right mouse button on the project name in "Solution Explorer", then select "Add" menu item and then "Reference")

  2. In your Project, expand the "References", find the QuartzTypeLib reference. Right click it and select properties, and change "Embed Interop Types" to false. (Otherwise you won't be able to use the FilgraphManager class in your project (and probably a couple of other ones)).

  3. In Project Settings, in the Build tab, I had to disable the Prefer 32-bit flag, Otherwise I would get this Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040266

  4. Use this class to play your favorite MP3 file:

    using QuartzTypeLib;
    public sealed class DirectShowPlayer
        private FilgraphManager FilterGraph;
        public void Play(string path)
            FilgraphManager = new FilgraphManager();
        public void Stop()

PS: TlbImp.exe can be found here: "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin", or in "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools"

What's the difference between [ and [[ in Bash?

[[ is bash's improvement to the [ command. It has several enhancements that make it a better choice if you write scripts that target bash. My favorites are:

  1. It is a syntactical feature of the shell, so it has some special behavior that [ doesn't have. You no longer have to quote variables like mad because [[ handles empty strings and strings with whitespace more intuitively. For example, with [ you have to write

    if [ -f "$file" ]

    to correctly handle empty strings or file names with spaces in them. With [[ the quotes are unnecessary:

    if [[ -f $file ]]
  2. Because it is a syntactical feature, it lets you use && and || operators for boolean tests and < and > for string comparisons. [ cannot do this because it is a regular command and &&, ||, <, and > are not passed to regular commands as command-line arguments.

  3. It has a wonderful =~ operator for doing regular expression matches. With [ you might write

    if [ "$answer" = y -o "$answer" = yes ]

    With [[ you can write this as

    if [[ $answer =~ ^y(es)?$ ]]

    It even lets you access the captured groups which it stores in BASH_REMATCH. For instance, ${BASH_REMATCH[1]} would be "es" if you typed a full "yes" above.

  4. You get pattern matching aka globbing for free. Maybe you're less strict about how to type yes. Maybe you're okay if the user types y-anything. Got you covered:

    if [[ $ANSWER = y* ]]

Keep in mind that it is a bash extension, so if you are writing sh-compatible scripts then you need to stick with [. Make sure you have the #!/bin/bash shebang line for your script if you use double brackets.

See also

In WPF, what are the differences between the x:Name and Name attributes?

x:Name and Name are referencing different namespaces.

x:name is a reference to the x namespace defined by default at the top of the Xaml file.


Just saying Name uses the default below namespace.


x:Name is saying use the namespace that has the x alias. x is the default and most people leave it but you can change it to whatever you like


so your reference would be foo:name

Define and Use Namespaces in WPF

OK lets look at this a different way. Say you drag and drop an button onto your Xaml page. You can reference this 2 ways x:name and name. All xmlns="" and xmlns:x="" are is references to multiple namespaces. Since xaml holds the Control namespace(not 100% on that) and presentation holds the FrameworkElement AND the Button class has a inheritance pattern of:

Button : ButtonBase
ButtonBase : ContentControl, ICommandSource
ContentControl : Control, IAddChild
Control : FrameworkElement
FrameworkElement : UIElement, IFrameworkInputElement, 
                    IInputElement, ISupportInitialize, IHaveResources

So as one would expect anything that inherits from FrameworkElement would have access to all its public attributes. so in the case of Button it is getting its Name attribute from FrameworkElement, at the very top of the hierarchy tree. So you can say x:Name or Name and they will both be accessing the getter/setter from the FrameworkElement.

MSDN Reference

WPF defines a CLR attribute that is consumed by XAML processors in order to map multiple CLR namespaces to a single XML namespace. The XmlnsDefinitionAttribute attribute is placed at the assembly level in the source code that produces the assembly. The WPF assembly source code uses this attribute to map the various common namespaces, such as System.Windows and System.Windows.Controls, to the namespace.

So the assembly attributes will look something like:

PresentationFramework.dll - XmlnsDefinitionAttribute:

[assembly: XmlnsDefinition("", "System.Windows")]

[assembly: XmlnsDefinition("", "System.Windows.Data")]

[assembly: XmlnsDefinition("", "System.Windows.Navigation")]

[assembly: XmlnsDefinition("", "System.Windows.Shapes")]

[assembly: XmlnsDefinition("", "System.Windows.Documents")]

[assembly: XmlnsDefinition("", "System.Windows.Controls")]  

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

If, like me, you need to target v4 but can only build with .net 3.5, follow the instruction here. Just replace in your web.config the whole content of the <configSections> with:

<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
  <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
    <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions,  Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
      <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
      <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
      <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>

post checkbox value

You should use

<input type="submit" value="submit" />

inside your form.

and add action into your form tag for example:

<form action="booking.php" method="post">

It's post your form into action which you choose.

From php you can get this value by


How to get a specific output iterating a hash in Ruby?

You can also refine Hash::each so it will support recursive enumeration. Here is my version of Hash::each(Hash::each_pair) with block and enumerator support:

module HashRecursive
    refine Hash do
        def each(recursive=false, &block)
            if recursive
       do |yielder|
           do |key, value|
                        value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
                        yielder << [[key], value]
        alias_method(:each_pair, :each)

using HashRecursive

Here are usage examples of Hash::each with and without recursive flag:

hash = {
    :a => {
        :b => {
            :c => 1,
            :d => [2, 3, 4]
        :e => 5
    :f => 6

p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2

p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6

hash.each do |key, value|
    puts "#{key} => #{value}"
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6

hash.each(true) do |key, value|
    puts "#{key} => #{value}"
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6

hash.each_pair(recursive=true) do |key, value|
    puts "#{key} => #{value}" unless value.is_a?(Hash)
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6

Here is example from the question itself:

hash = {
    1   =>  ["a", "b"], 
    2   =>  ["c"], 
    3   =>  ["a", "d", "f", "g"], 
    4   =>  ["q"]

hash.each(recursive=false) do |key, value|
    puts "#{key} => #{value}"
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]

Also take a look at my recursive version of Hash::merge(Hash::merge!) here.

Moving average or running mean

Efficient solution

Convolution is much better than straightforward approach, but (I guess) it uses FFT and thus quite slow. However specially for computing the running mean the following approach works fine

def running_mean(x, N):
    cumsum = numpy.cumsum(numpy.insert(x, 0, 0)) 
    return (cumsum[N:] - cumsum[:-N]) / float(N)

The code to check

In[3]: x = numpy.random.random(100000)
In[4]: N = 1000
In[5]: %timeit result1 = numpy.convolve(x, numpy.ones((N,))/N, mode='valid')
10 loops, best of 3: 41.4 ms per loop
In[6]: %timeit result2 = running_mean(x, N)
1000 loops, best of 3: 1.04 ms per loop

Note that numpy.allclose(result1, result2) is True, two methods are equivalent. The greater N, the greater difference in time.

warning: although cumsum is faster there will be increased floating point error that may cause your results to be invalid/incorrect/unacceptable

the comments pointed out this floating point error issue here but i am making it more obvious here in the answer..

# demonstrate loss of precision with only 100,000 points
x = np.random.randn(100000)+1e6
y1 = running_mean_convolve(x, 10)
y2 = running_mean_cumsum(x, 10)
assert np.allclose(y1, y2, rtol=1e-12, atol=0)
  • the more points you accumulate over the greater the floating point error (so 1e5 points is noticable, 1e6 points is more significant, more than 1e6 and you may want to resetting the accumulators)
  • you can cheat by using np.longdouble but your floating point error still will get significant for relatively large number of points (around >1e5 but depends on your data)
  • you can plot the error and see it increasing relatively fast
  • the convolve solution is slower but does not have this floating point loss of precision
  • the uniform_filter1d solution is faster than this cumsum solution AND does not have this floating point loss of precision

Any way to clear python's IDLE window?

If you are using the terminal ( i am using ubuntu ) , then just use the combination of CTRL+l from keyboard to clear the python script, even it clears the terminal script...

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference.

Another great site to help you get started is

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!


Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
End Sub

Can I apply the required attribute to <select> fields in HTML5?

Yes, it's working:

<select name="somename" required>
     <option value="">Please select</option>
     <option value="one">One</option>

you have to keep first option blank.

What is the cleanest way to get the progress of JQuery ajax request?

jQuery has an AjaxSetup() function that allows you to register global ajax handlers such as beforeSend and complete for all ajax calls as well as allow you to access the xhr object to do the progress that you are looking for

Can I do Model->where('id', ARRAY) multiple where conditions?

There's whereIn():

$items = DB::table('items')->whereIn('id', [1, 2, 3])->get();

Get TimeZone offset value from TimeZone without TimeZone name

With java8 now, you can use

Integer offset  =;

to get the current system time offset from UTC. Then you can convert it to any format you want. Found it useful for my case. Example :

UIAlertView first deprecated IOS 9


    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Title"

    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {}];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];

[self showAlert]; // calling Method

Convert date to datetime in Python

I am a newbie to Python. But this code worked for me which converts the specified input I provide to datetime. Here's the code. Correct me if I'm wrong.

import sys
from datetime import datetime
from time import mktime, strptime

user_date = '02/15/1989'
if user_date is not None:
     user_date = datetime.strptime(user_date,"%m/%d/%Y")
     user_date =
print user_date

JavaScript - Get Browser Height

You can use the window.innerHeight

I had same problem when i rolled back to old version via git, and that version had previous .jar library of one 3rd party api, and for some reason turned out that both jar of the same sdk, just different versions were in /libs folder.

copy all files and folders from one drive to another drive using DOS (command prompt)

xcopy "C:\SomeFolderName" "D:\SomeFolderName" /h /i /c /k /e /r /y

Use the above command. It will definitely work.

In this command data will be copied from c:\ to D:\, even folders and system files as well. Here's what the flags do:

  • /h copies hidden and system files also
  • /i if destination does not exist and copying more than one file, assume that destination must be a directory
  • /c continue copying even if error occurs
  • /k copies attributes
  • /e copies directories and subdirectories, including empty ones
  • /r overwrites read-only files
  • /y suppress prompting to confirm whether you want to overwrite a file

Docker and securing passwords

Our team avoids putting credentials in repositories, so that means they're not allowed in Dockerfile. Our best practice within applications is to use creds from environment variables.

We solve for this using docker-compose.

Within docker-compose.yml, you can specify a file that contains the environment variables for the container:

- .env

Make sure to add .env to .gitignore, then set the credentials within the .env file like:


Store the .env file locally or in a secure location where the rest of the team can grab it.


Floating Div Over An Image

you might consider using the Relative and Absolute positining.

`.container {  
position: relative;  
.tag {     
position: absolute;   

I have tested it there, also if you want it to change its position use this as its margin:

top: 20px;
left: 10px;

It will place it 20 pixels from top and 10 pixels from left; but leave this one if not necessary.

onchange equivalent in angular2

In Angular you can define event listeners like in the example below:

<!-- Here you can call public methods from parental component -->
<input (change)="method_name()"> 

Cannot connect to the Docker daemon on macOS

On a supported Mac, run:

brew install --cask docker

Then launch the Docker app. Click next. It will ask for privileged access. Confirm. A whale icon should appear in the top bar. Click it and wait for "Docker is running" to appear.

You should be able to run docker commands now:

docker ps

Because docker is a system-level package, you cannot install it using brew install, and must use --cask instead.

Note: This solution only works for Macs whose CPUs support virtualization, which may not include old Macs.

import sun.misc.BASE64Encoder results in error compiled in Eclipse

I know this is very Old post. Since we don't have any thing sun.misc in maven we can easily use

StringUtils.newStringUtf8(Base64.encodeBase64(encVal)); From org.apache.commons.codec.binary.Base64

How to get year/month/day from a date object?

I would suggest you to use Moment.js

Then you can do:

moment(new Date()).format("YYYY/MM/DD");

Note: you don't actualy need to add new Date() if you want the current TimeDate, I only added it as a reference that you can pass a date object to it. for the current TimeDate this also works:


char *array and char array[]

No, you're creating an array, but there's a big difference:

char *string = "Some CONSTANT string";
printf("%c\n", string[1]);//prints o
string[1] = 'v';//INVALID!!

The array is created in a read only part of memory, so you can't edit the value through the pointer, whereas:

char string[] = "Some string";

creates the same, read only, constant string, and copies it to the stack array. That's why:

string[1] = 'v';

Is valid in the latter case.
If you write:

char string[] = {"some", " string"};

the compiler should complain, because you're constructing an array of char arrays (or char pointers), and assigning it to an array of chars. Those types don't match up. Either write:

char string[] = {'s','o','m', 'e', ' ', 's', 't','r','i','n','g', '\o'};
//this is a bit silly, because it's the same as char string[] = "some string";
char *string[] = {"some", " string"};//array of pointers to CONSTANT strings
char string[][10] = {"some", " string"};

Where the last version gives you an array of strings (arrays of chars) that you actually can edit...

Best way to store date/time in mongodb

The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.

> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }

The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

If you need to, you can easily convert Date objects to and from Unix timestamps1), using the getTime() method and Date(milliseconds) constructor, respectively.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

How to keep one variable constant with other one changing with row in excel

You put it as =(B0+4)/($A$0)

You can also go across WorkSheets with Sheet1!$a$0

Delete all files of specific type (extension) recursively down a directory using a batch file

You can use this to delete ALL Files Inside a Folder and Subfolders:

DEL "C:\Folder\*.*" /S /Q

Or use this to Delete Certain File Types Only:

DEL "C:\Folder\*.mp4" /S /Q 
DEL "C:\Folder\*.dat" /S /Q 

How to set initial value and auto increment in MySQL?

First you need to add column for auto increment

alter table users add column id int(5) NOT NULL AUTO_INCREMENT FIRST

This query for add column at first. Now you have to reset auto increment initial value. So use this query

alter table users AUTO_INCREMENT=1001

Now your table started with 1001

Parenthesis/Brackets Matching using Stack algorithm

I think is the best answer:

public boolean isValid(String s) {
    Map<Character, Character> map = new HashMap<>();
    map.put('(', ')');
    map.put('[', ']');
    map.put('{', '}');
    Stack<Character> stack = new Stack<>();
    for(char c : s.toCharArray()){
        } else if(!stack.empty() && map.get(stack.peek())==c){
        } else {
            return false;
    return stack.empty();

How to generate sample XML documents from their DTD or XSD?

XML Blueprint also does that; instructions here

It's not free, but there's a 10-day free trial; it seems fast and efficient; unfortunately it's Windows only.

Error: Failed to lookup view in Express

Just noticed that I had named my file ' index.html' instead for 'index.html' with a leading space. That was why it could not find it.

What is the difference between MacVim and regular Vim?

It's all about the key bindings which one can simply achieve from .vimrc configurations. As far as clipboard is concerned you can use :set clipboard unnamed and the yank from vim will go to system clipboard. Anyways, whichever one you end up using I suggest using this vimrc config , it contains a whole lot of plugins and bindings which will make your experience smooth.

How to make Excel VBA variables available to multiple macros?

Declare them outside the subroutines, like this:

Public wbA as Workbook
Public wbB as Workbook
Sub MySubRoutine()
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
End Sub
Sub OtherSubRoutine()
    MsgBox wbA.Name, vbInformation
End Sub

Alternately, you can pass variables between subroutines:

Sub MySubRoutine()
Dim wbA as Workbook
Dim wbB as Workbook
    Set wbA = Workbooks.Open("C:\file.xlsx")
    Set wbB = Workbooks.Open("C:\file2.xlsx")
    OtherSubRoutine wbA, wbB
End Sub
Sub OtherSubRoutine(wb1 as Workbook, wb2 as Workbook)
    MsgBox wb1.Name, vbInformation
    MsgBox wb2.Name, vbInformation
End Sub

Or use Functions to return values:

Sub MySubroutine()
    Dim i as Long
    i = MyFunction()
    MsgBox i
End Sub
Function MyFunction()
    'Lots of code that does something
    Dim x As Integer, y as Double
    For x = 1 to 1000
        'Lots of code that does something
    MyFunction = y
End Function

In the second method, within the scope of OtherSubRoutine you refer to them by their parameter names wb1 and wb2. Passed variables do not need to use the same names, just the same variable types. This allows you some freedom, for example you have a loop over several workbooks, and you can send each workbook to a subroutine to perform some action on that Workbook, without making all (or any) of the variables public in scope.

A Note About User Forms

Personally I would recommend keeping Option Explicit in all of your modules and forms (this prevents you from instantiating variables with typos in their names, like lCoutn when you meant lCount etc., among other reasons).

If you're using Option Explicit (which you should), then you should qualify module-scoped variables for style and to avoid ambiguity, and you must qualify user-form Public scoped variables, as these are not "public" in the same sense. For instance, i is undefined, though it's Public in the scope of UserForm1:

enter image description here

You can refer to it as UserForm1.i to avoid the compile error, or since forms are New-able, you can create a variable object to contain reference to your form, and refer to it that way:

enter image description here

NB: In the above screenshots x is declared Public x as Long in another standard code module, and will not raise the compilation error. It may be preferable to refer to this as Module2.x to avoid ambiguity and possible shadowing in case you re-use variable names...

disable a hyperlink using jQuery

Append a class containing pointer-events:non

.active a{ //css
text-decoration: underline;
background-color: #fff;
pointer-events: none;}


Set folder for classpath

Use the command as

java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>

The above command will set the mentioned paths to classpath only once for executing the class named TestClass.

If you want to execute more then one classes, then you can follow this

set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"

After this you can execute as many classes as you want just by simply typing

java <your-class-name>

The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)

If you want to set the classpth only once so that it could work for everytime, then do as follows

1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
    a.  Variable Name-     classpath
    b.  Variable Value-    .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.

Remember this will work every time. You don't need to explicitly set the classpath again and again.

NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.

Hope this will help you.

How to prevent vim from creating (and leaving) temporary files?

I have this setup in my Ubuntu .vimrc. I don't see any swap files in my project files.

set undofile
set undolevels=1000         " How many undos
set undoreload=10000        " number of lines to save for undo

set backup                        " enable backups
set swapfile                      " enable swaps
set undodir=$HOME/.vim/tmp/undo     " undo files
set backupdir=$HOME/.vim/tmp/backup " backups
set directory=$HOME/.vim/tmp/swap   " swap files

" Make those folders automatically if they don't already exist.
if !isdirectory(expand(&undodir))
    call mkdir(expand(&undodir), "p")
if !isdirectory(expand(&backupdir))
    call mkdir(expand(&backupdir), "p")
if !isdirectory(expand(&directory))
    call mkdir(expand(&directory), "p")

How do I get the current location of an iframe?

Ok, so in this application, there is an iframe in which the user is supplied with links or some capacity that allows that iframe to browse to some external site. You are then looking to capture the URL to which the user has browsed.

Something to keep in mind. Since the URL is to an external source, you will be limited in how much you can interact with this iframe via javascript (or an client side access for that matter), this is known as browser cross-domain security, as apparently you have discovered. There are clever work arounds, as presented here Cross-domain, cross-frame Javascript, although I do not think this work around applies in this case.

About all you can access is the location, as you need.

I would suggest making the code presented more resilitant and less error prone. Try browsing the web sometime with IE or FF configured to show javascript errors. You will be surprised just how many javascript errors are thrown, largely because there is a lot of error prone javascript out there, which just continues to proliferate.

This solution assumes that the iframe in question is the same "window" context where you are running the javascript. (Meaning, it is not embedded within another frame or iframe, in which case, the javascript code gets more involved, and you likely need to recursively search through the window hierarchy.)

<iframe name='frmExternal' id='frmExternal' src=''></frame>
<input type='text' id='txtUrl' />
<input type='button' id='btnGetUrl' value='Get URL' onclick='GetIFrameUrl();' />

<script language='javascript' type='text/javascript'>
function GetIFrameUrl()
    if (!document.getElementById)

    var frm = document.getElementById("frmExternal");
    var txt = document.getElementById("txtUrl");

    if (frm == null || txt == null)
        // not great user feedback but slightly better than obnoxious script errors
       alert("There was a problem with this page, please refresh.");

    txt.value = frm.src;

Hope this helps.

Java, How to implement a Shift Cipher (Caesar Cipher)

Two ways to implement a Caesar Cipher:

Option 1: Change chars to ASCII numbers, then you can increase the value, then revert it back to the new character.

Option 2: Use a Map map each letter to a digit like this.

A - 0
B - 1
C - 2

With a map you don't have to re-calculate the shift every time. Then you can change to and from plaintext to encrypted by following map.

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

In newer versions of OS X (especially Yosemite, EL Capitan), Apple has removed Java support for security reasons. To fix this you have to do the following.

  1. Download Java for OS X 2015-001 from this link:
  2. Mount the disk image file and install Java 6 runtime for OS X.

    After this you should not be seeing any of the below messages:

    - Unable to find any JVMs matching version "(null)"

    - No Java runtime present, try --request to install.

    This should resolve the issue for the pop-up shown below: enter image description here

Return string without trailing slash

I'd use a regular expression:

function someFunction(site)
// if site has an end slash (like:,
// then remove it and return the site without the end slash
return site.replace(/\/$/, '') // Match a forward slash / at the end of the string ($)

You'll want to make sure that the variable site is a string, though.

How can you flush a write using a file descriptor?

If you want to go the other way round (associate FILE* with existing file descriptor), use fdopen() :



       fdopen - associate a stream with a file descriptor


       #include <stdio.h>

       FILE *fdopen(int fildes, const char *mode);

What's the best practice to round a float to 2 decimals?

Here is a shorter implementation comparing to @Jav_Rock's

     * Round to certain number of decimals
     * @param d
     * @param decimalPlace the numbers of decimals
     * @return

    public static float round(float d, int decimalPlace) {
         return BigDecimal.valueOf(d).setScale(decimalPlace,BigDecimal.ROUND_HALF_UP).floatValue();

    System.out.println(round(2.345f,2));//two decimal digits, //2.35

Convert tabs to spaces in Notepad++

Follow this procedure to convert spaces to tabs or vice-versa:

Space - Tab

Remote branch is not showing up in "git branch -r"

Update your remote if you still haven't done so:

$ git remote update
$ git branch -r

iPhone SDK:How do you play video inside a view? Rather than fullscreen

Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.framework to your target.

Here's some sample code:

#import <MediaPlayer/MediaPlayer.h>

@interface ViewController () {
    MPMoviePlayerController *moviePlayerController;

@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play


@implementation ViewController

- (void)viewDidLoad
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Instantiate a movie player controller and add it to your view
    NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
    NSURL *movieURL = [NSURL fileURLWithPath:moviePath];    
    moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    [moviePlayerController.view setFrame:self.movieView.bounds];  // player's frame must match parent's
    [self.movieView addSubview:moviePlayerController.view];

    // Configure the movie player controller
    moviePlayerController.controlStyle = MPMovieControlStyleNone;        
    [moviePlayerController prepareToPlay];

- (void)viewDidAppear:(BOOL)animated
    [super viewDidAppear:animated];

    // Start the movie
    [moviePlayerController play];


Time complexity of accessing a Python dict

To answer your specific questions:

"Am I correct that python dicts suffer from linear access times with such inputs?"

A1: If you mean that average lookup time is O(N) where N is the number of entries in the dict, then it is highly likely that you are wrong. If you are correct, the Python community would very much like to know under what circumstances you are correct, so that the problem can be mitigated or at least warned about. Neither "sample" code nor "simplified" code are useful. Please show actual code and data that reproduce the problem. The code should be instrumented with things like number of dict items and number of dict accesses for each P where P is the number of points in the key (2 <= P <= 5)

"As far as I know, sets have guaranteed logarithmic access times. How can I simulate dicts using sets(or something similar) in Python?"

A2: Sets have guaranteed logarithmic access times in what context? There is no such guarantee for Python implementations. Recent CPython versions in fact use a cut-down dict implementation (keys only, no values), so the expectation is average O(1) behaviour. How can you simulate dicts with sets or something similar in any language? Short answer: with extreme difficulty, if you want any functionality beyond dict.has_key(key).

unable to set private key file: './cert.pem' type PEM

After reading cURL documentation on the options you used, it looks like the private key of certificate is not in the same file. If it is in different file, you need to mention it using --key file and supply passphrase.

So, please make sure that either cert.pem has private key (along with the certificate) or supply it using --key option.

Also, this documentation mentions that Note that this option assumes a "certificate" file that is the private key and the private certificate concatenated!

How they are concatenated? It is quite easy. Put them one after another in the same file.

You can get more help on this here.

I believe this might help you.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Pass row number as variable in excel sheet

Assuming your row number is in B1, you can use INDIRECT:


This takes a cell reference as a string (in this case, the concatenation of A and the value of B1 - 5), and returns the value at that cell.

Detect if PHP session exists

The original code is from Sabry Suleiman.

Made it a bit prettier:

function is_session_started() {

    if ( php_sapi_name() === 'cli' )
        return false;

    return version_compare( phpversion(), '5.4.0', '>=' )
        ? session_status() === PHP_SESSION_ACTIVE
        : session_id() !== '';

First condition checks the Server API in use. If Command Line Interface is used, the function returns false.

Then we return the boolean result depending on the PHP version in use.

In ancient history you simply needed to check session_id(). If it's an empty string, then session is not started. Otherwise it is.

Since 5.4 to at least the current 8.0 the norm is to check session_status(). If it's not PHP_SESSION_ACTIVE, then either the session isn't started yet (PHP_SESSION_NONE) or sessions are not available altogether (PHP_SESSION_DISABLED).

Android fastboot waiting for devices

To use the fastboot command you first need to put your device in fastboot mode:

$ adb reboot bootloader

Once the device is in fastboot mode, you can boot it with your own kernel, for example:

$ fastboot boot myboot.img

The above will only boot your kernel once and the old kernel will be used again when you reboot the device. To replace the kernel on the device, you will need to flash it to the device:

$ fastboot flash boot myboot.img

Hope that helps.

Why doesn't Git ignore my specified file?

I tried most commands above on VS Code terminal and I got errors like:

fatal: pathspec '[dir]/[file]' did not match any files

I opened the project on GitHub Desktop and ignored from there and it worked.

How do I add a new class to an element dynamically?

Yes you can - first capture the event using onmouseover, then set the class name using Element.className.

If you like to add or remove classes - use the more convenient Element.classList method.

.active {
  background: red;
<div onmouseover=className="active">
  Hover this!

Configuring diff tool with .gitconfig

Adding one of the blocks below works for me to use KDiff3 for my Windows and Linux development environments. It makes for a nice consistent cross-platform diff and merge tool.


[difftool "kdiff3"]
    path = /usr/bin/kdiff3
    trustExitCode = false
    prompt = false
    tool = kdiff3
[mergetool "kdiff3"]
    path = /usr/bin/kdiff3
    trustExitCode = false
    keepBackup = false
    tool = kdiff3


[difftool "kdiff3"]
    path = C:/Progra~1/KDiff3/kdiff3.exe
    trustExitCode = false
    prompt = false
    tool = kdiff3
[mergetool "kdiff3"]
    path = C:/Progra~1/KDiff3/kdiff3.exe
    trustExitCode = false
    keepBackup = false
    tool = kdiff3

How do I create directory if it doesn't exist to create a file?

As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:


Set variable value to array of strings

declare  @tab table(FirstName  varchar(100))
insert into @tab   values('John'),('Sarah'),('George')

FROM @tab
WHERE 'John' in (FirstName)

What is the iPhone 4 user-agent?

  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/7D11
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A306 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B5097d Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2 like Mac OS X; en_us) AppleWebKit/525.18.1 (KHTML, like Gecko)
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5

...for now

How do I convert a String to an InputStream in Java?

I find that using Apache Commons IO makes my life much easier.

String source = "This is the source of my input stream";
InputStream in =, "UTF-8");

You may find that the library also offer many other shortcuts to commonly done tasks that you may be able to use in your project.

How do I delete everything in Redis?

Open redis-cli and type:


How to draw a line in android

Simple one

    android:layout_marginTop="160dp" />

How to take a first character from the string

Try this:

Dim s = "RAJAN"
Dim firstChar = s(0)

You can even do this:

Dim firstChar = "RAJAN"(0)

I can't install intel HAXM

How I solved this problem:

Step-1: Downloaded the Android Studio and installed it. But it failed to install HAXM.

Step-2: Then ran the AVD. Then it prompts to create a virtual device. But it also failed.

Step-3: I downloaded the latest HAXM from intel's GitHub source. From here

Step-4: Then installed HAXM manually. Documentation is here: Installing Standalone Intel HAXM on Windows

Step-5: Then again tried to create a virtual device of Pie. It successfully created it.

But if your Step-5 fails anyhow, there may another solution: When downloading the .zip file, it will show you the SDK path and also the source path of the .zip file. So you can manually download the .zip and can place it to the SDK path folder. Then again can try to create the virtual device.

Calculating distance between two geographic locations

Look into distanceTo

Returns the approximate distance in meters between this location and the given location. Distance is defined using the WGS84 ellipsoid.

or distanceBetween

Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Distance and bearing are defined using the WGS84 ellipsoid.

You can create a Location object from a latitude and longitude:

Location locationA = new Location("point A");


Location locationB = new Location("point B");


float distance = locationA.distanceTo(locationB);


private double meterDistanceBetweenPoints(float lat_a, float lng_a, float lat_b, float lng_b) {
    float pk = (float) (180.f/Math.PI);

    float a1 = lat_a / pk;
    float a2 = lng_a / pk;
    float b1 = lat_b / pk;
    float b2 = lng_b / pk;

    double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
    double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
    double t3 = Math.sin(a1) * Math.sin(b1);
    double tt = Math.acos(t1 + t2 + t3);
    return 6366000 * tt;

How to resize an image to a specific size in OpenCV?

The two functions you need are documented here:

  1. imread: read an image from disk.
  2. Image resizing: resize to just any size.

In short:

// Load images in the C++ format
cv::Mat img = cv::imread("something.jpg");
cv::Mat src = cv::imread("src.jpg");

// Resize src so that is has the same size as img
cv::resize(src, src, img.size());

And please, please, stop using the old and completely deprecated IplImage* classes

Reading from stdin

You can do something like this to read 10 bytes:

char buffer[10];
read(STDIN_FILENO, buffer, 10);

remember read() doesn't add '\0' to terminate to make it string (just gives raw buffer).

To read 1 byte at a time:

char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
 //do stuff

and don't forget to #include <unistd.h>, STDIN_FILENO defined as macro in this file.

There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:

Integer value   Name
       0        Standard input (stdin)
       1        Standard output (stdout)
       2        Standard error (stderr)

So instead STDIN_FILENO you can use 0.

In Linux System you can find this using following command:

$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define   STDIN_FILENO    0   /* Standard input.  */

Notice the comment /* Standard input. */

MultipartException: Current request is not a multipart request

That happened once to me: I had a perfectly working Postman configuration, but then, without changing anything, even though I didn't inform the Content-Type manually on Postman, it stopped working; following the answers to this question, I tried both disabling the header and letting Postman add it automatically, but neither options worked.

I ended up solving it by going to the Body tab, change the param type from File to Text, then back to File and then re-selecting the file to send; somehow, this made it work again. Smells like a Postman bug, in that specific case, maybe?

How to Logout of an Application Where I Used OAuth2 To Login With Google?

If any one want it in Java, Here is my Answer, For this you have to call Another Thread.

Execute the setInterval function without delay the first time

Here's a wrapper to pretty-fy it if you need it:

(function() {
    var originalSetInterval = window.setInterval;

    window.setInterval = function(fn, delay, runImmediately) {
        if(runImmediately) fn();
        return originalSetInterval(fn, delay);

Set the third argument of setInterval to true and it'll run for the first time immediately after calling setInterval:

setInterval(function() { console.log("hello world"); }, 5000, true);

Or omit the third argument and it will retain its original behaviour:

setInterval(function() { console.log("hello world"); }, 5000);

Some browsers support additional arguments for setInterval which this wrapper doesn't take into account; I think these are rarely used, but keep that in mind if you do need them.

How to get just the parent directory name of a specific file

For Kotlin :

 fun getFolderName() {
            val uri: Uri
            val cursor: Cursor?
            uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
            val projection = arrayOf(MediaStore.Audio.AudioColumns.DATA)
            cursor = requireActivity().contentResolver.query(uri, projection, null, null, null)
            if (cursor != null) {
                column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Audio.AudioColumns.DATA)
            while (cursor!!.moveToNext()) {
                absolutePathOfImage = cursor.getString(column_index_data)
                val fileName: String = File(absolutePathOfImage)

Android background music service

Create a foreground service with the START_STICKY flag.

public int onStartCommand(Intent startIntent, int flags, int startId) {
   if (startIntent != null) {
       String action = startIntent.getAction();
       String command = startIntent.getStringExtra(CMD_NAME);
       if (ACTION_CMD.equals(action)) {
           if (CMD_PAUSE.equals(command)) {
               if (mPlayback != null && mPlayback.isPlaying()) {
           } else if (CMD_PLAY.equals(command)) {
               ArrayList<Track> queue = new ArrayList<>();
               for (Parcelable input : startIntent.getParcelableArrayListExtra(ARG_QUEUE)) {
                   queue.add((Track) Parcels.unwrap(input));
               int index = startIntent.getIntExtra(ARG_INDEX, 0);
               playWithQueue(queue, index);

   return START_STICKY;

This can then be called from any activity to play some music

Intent intent = new Intent(MusicService.ACTION_CMD, fileUrlToPlay, activity,
intent.putParcelableArrayListExtra(MusicService.ARG_QUEUE, tracks)
intent.putExtra(MusicService.ARG_INDEX, position)
intent.putExtra(MusicService.CMD_NAME, MusicService.CMD_PLAY)

You can bind to the service using bindService and to make the Service pause/stop from the corresponding activity lifecycle methods.

Here's a good tutorial about Playing music in the background on Android

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

I want to add something on @Michael Laffargue's post:

jqXHR.done() is faster!

jqXHR.success() have some load time in callback and sometimes can overkill script. I find that on hard way before.


Using jqXHR.done(), and jqXHR.always() you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:

/* Initialize some your AJAX function */
function call_ajax(attr){
    var settings=$.extend({
        call            : 'users',
        option          : 'list'
    }, attr );

    return $.ajax({
        type: "POST",
        url: "//",
        data: settings,
        cache : false

/* .... Somewhere in your code ..... */

    /* ... */
    id : 10,
    option : 'edit_user'
    change : {
          name : 'John Doe'
    /* ... */



JavaScript query string

function decode(s) {
    try {
        return decodeURIComponent(s).replace(/\r\n|\r|\n/g, "\r\n");
    } catch (e) {
        return "";
function getQueryString(win) {
    var qs =;
    var multimap = {};
    if (qs.length > 1) {
        qs = qs.substr(1);
        qs.replace(/([^=&]+)=([^&]*)/g, function(match, hfname, hfvalue) {
            var name = decode(hfname);
            var value = decode(hfvalue);
            if (name.length > 0) {
                if (!multimap.hasOwnProperty(name)) {
                    multimap[name] = [];
    return multimap;
var keys = getQueryString(window);
for (var i in keys) {
    if (keys.hasOwnProperty(i)) {
        for (var z = 0; z < keys[i].length; ++z) {
            alert(i + ":" + keys[i][z]);

MongoDB: Is it possible to make a case-insensitive query?

Starting with MongoDB 3.4, the recommended way to perform fast case-insensitive searches is to use a Case Insensitive Index.

I personally emailed one of the founders to please get this working, and he made it happen! It was an issue on JIRA since 2009, and many have requested the feature. Here's how it works:

A case-insensitive index is made by specifying a collation with a strength of either 1 or 2. You can create a case-insensitive index like this:

  { city: 1 },
    collation: {
      locale: 'en',
      strength: 2

You can also specify a default collation per collection when you create them:

db.createCollection('cities', { collation: { locale: 'en', strength: 2 } } );

In either case, in order to use the case-insensitive index, you need to specify the same collation in the find operation that was used when creating the index or the collection:

  { city: 'new york' }
  { locale: 'en', strength: 2 }

This will return "New York", "new york", "New york" etc.

Other notes

  • The answers suggesting to use full-text search are wrong in this case (and potentially dangerous). The question was about making a case-insensitive query, e.g. username: 'bill' matching BILL or Bill, not a full-text search query, which would also match stemmed words of bill, such as Bills, billed etc.

  • The answers suggesting to use regular expressions are slow, because even with indexes, the documentation states:

    "Case insensitive regular expression queries generally cannot use indexes effectively. The $regex implementation is not collation-aware and is unable to utilize case-insensitive indexes."

    $regex answers also run the risk of user input injection.

How to increase editor font size?

I have the latest version of Android Studio installed (3.6.1).

I navigated to: File->Settings->Editor->Font. The dialog displays a warning message (yellow triangle) indicating that the Font is defined in the color scheme.

(Editing the Font here had no effect.)

Editor Font

I clicked on the dialog's warning message link.

This navigated to: File->Settings->Editor->Color Scheme->Color Scheme Font.

(Now I could edit the Font for my current scheme.)

Editor Color Scheme Color Scheme Font

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("")) {
    /* or properties.loadFromXML(...) */

unique combinations of values in selected columns in pandas data frame and count

Slightly related, I was looking for the unique combinations and I came up with this method:

def unique_columns(df,columns):

    result = pd.Series(index = df.index)

    groups = meta_data_csv.groupby(by = columns)
    for name,group in groups:
       is_unique = len(group) == 1
       result.loc[group.index] = is_unique

    assert not result.isnull().any()

    return result

And if you only want to assert that all combinations are unique:


How to add 10 minutes to my (String) time?

You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.

String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());

Output :


ant build.xml file doesn't exist

Using ant debug after building build.xml file :

in your cmd your root should be your project at first then use the ant debug command e.g:

c:\testApp>ant debug 

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

I just ran into this and found that changing this in the .env file from to localhost fixed it.


Excel: the Incredible Shrinking and Expanding Controls

We just solved this on a company level by adding the following module to all macro enabled workbooks:

Option Explicit

Type ButtonSizeType
    topPosition As Single
    leftPosition As Single
    height As Single
    width As Single
End Type

Public myButton As ButtonSizeType

Sub GetButtonSize(cb As MSForms.CommandButton)
' Save original button size to solve windows bug that changes the button size to
' adjust to screen resolution, when not in native resolution mode of screen
    myButton.topPosition =
    myButton.leftPosition = cb.Left
    myButton.height = cb.height
    myButton.width = cb.width
End Sub

Sub SetButtonSize(cb As MSForms.CommandButton)
' Restore original button size to solve windows bug that changes the button size to
' adjust to screen resolution, when not in native resolution mode of screen = myButton.topPosition
    cb.Left = myButton.leftPosition
    cb.height = myButton.height
    cb.width = myButton.width
End Sub

Just call them in the beginning and end of your code like this:

Private Sub CommandButton1_Click()

Application.ScreenUpdating = False
' Turn off ScreenUpdating to make sure the user dosn't see the buttons flicker
GetButtonSize CommandButton1 ' Saves original button size
' Do cool things
SetButtonSize CommandButton1 ' Restores original button size

Application.ScreenUpdating = True
' Turn ScreenUpdating back on when you're done
End Sub

When should iteritems() be used instead of items()?

As the dictionary documentation for python 2 and python 3 would tell you, in python 2 items returns a list, while iteritems returns a iterator.

In python 3, items returns a view, which is pretty much the same as an iterator.

If you are using python 2, you may want to user iteritems if you are dealing with large dictionaries and all you want to do is iterate over the items (not necessarily copy them to a list)

Jquery each - Stop loop and return object

Try this ...

  someArray = new Array();
  someArray[0] = 't5';
  someArray[1] = 'z12';
  someArray[2] = 'b88';
  someArray[3] = 's55';
  someArray[4] = 'e51';
  someArray[5] = 'o322';
  someArray[6] = 'i22';
  someArray[7] = 'k954';  

  var test =  findXX('o322'); 

function findXX(word)
  for(var i in someArray){

    if(someArray[i] == word)
      return someArray[i]; //<---  stop the loop!

Get the new record primary key ID from MySQL insert query?

i used return $this->db->insert_id(); for Codeigniter

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I my case \xe2 was a which should be replaced by '.

In general I recommend to convert UTF-8 to ASCII using e.g.

However if you want to keep UTF-8 you can use

#-*- mode: python -*-
# -*- coding: utf-8 -*-

How to specify an element after which to wrap in css flexbox?

The only thing that appears to work is to set flex-wrap: wrap; on the container and them somehow make the child you want to break out after to fill the full width, so width: 100%; should work.

If, however, you can't stretch the element to 100% (for example, if it's an <img>), you can apply a margin to it, like width: 50px; margin-right: calc(100% - 50px).

What is the best way to left align and right align two div tags?

You can do it with few lines of CSS code. You can align all div's which you want to appear next to each other to right.

<div class="div_r">First Element</div>
<div class="div_r">Second Element</div>


How to draw a line with matplotlib?

As of matplotlib 3.3, you can do this with plt.axline((x1, y1), (x2, y2)).

auto refresh for every 5 mins

Page should be refresh auto using meta tag

<meta http-equiv="Refresh" content="60"> 

content value in seconds.after one minute page should be refresh

How to find path of active app.config file?

Try this


Why can't I use a list as a dict key in python?

Your awnser can be found here:

Why Lists Can't Be Dictionary Keys

Newcomers to Python often wonder why, while the language includes both a tuple and a list type, tuples are usable as a dictionary keys, while lists are not. This was a deliberate design decision, and can best be explained by first understanding how Python dictionaries work.

Source & more info:

where to place CASE WHEN column IS NULL in this query

Try this:

CASE WHEN table3.col3 IS NULL THEN table2.col3 ELSE table3.col3 END as col4

The as col4 should go at the end of the CASE the statement. Also note that you're missing the END too.

Another probably more simple option would be:

IIf([table3.col3] Is Null,[table2.col3],[table3.col3])

Just to clarify, MS Access does not support COALESCE. If it would that would be the best way to go.

Edit after radical question change:

To turn the query into SQL Server then you can use COALESCE (so it was technically answered before too):

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
COALESCE(dbo.EU_Admin3.EUID, dbo.EU_Admin2.EUID)
FROM dbo.AdminID

BTW, your CASE statement was missing a , before the field. That's why it didn't work.

Getting vertical gridlines to appear in line plot in matplotlib

plt.gca().xaxis.grid(True) proved to be the solution for me

If Else in LINQ

This might work...

from p in db.products
    select new
        Owner = (p.price > 0 ?
            from q in db.Users select q.Name :
            from r in db.ExternalUsers select r.Name)

C++ error: "Array must be initialized with a brace enclosed initializer"

You can't initialize arrays like this:

int cipher[Array_size][Array_size]=0;

The syntax for 2D arrays is:

int cipher[Array_size][Array_size]={{0}};

Note the curly braces on the right hand side of the initialization statement.

for 1D arrays:

int tomultiply[Array_size]={0};

Editor does not contain a main type

If it is maven project please check the java file is created under src/main/java

If you are not getting please change the JRE path and create the java files in above folder structure

Background position, margin-top?

If you mean you want the background image itself to be offset by 50 pixels from the top, like a background margin, then just switch out the top for 50px and you're set.

#thedivstatus {
    background-image: url("imagestatus.gif");
    background-position: right 50px;
    background-repeat: no-repeat;

How to find out when a particular table was created in Oracle?


Grant Select on a view not base table when base table is in a different database

As you state in one of your comments that the table in question is in a different database, then ownership chaining applies. I suspect there is a break in the chain somewhere - check that link for full details.

Chosen Jquery Plugin - getting selected values

I believe the problem occurs when targeting by ID, because Chosen will copy the ID from the original select onto it's newly created div, leaving you with 2 elements of the same (now not-unique) ID on the current page.

When targeting Chosen by ID, use a selector specific to the select:

$( 'select#yourID' ).on( 'change', function() {
    console.log( $( this ).val() );
} );

...instead of...

$( '#yourID' ).on( 'change', function() {
    console.log( $( this ).val() );
} );

This works because Chosen mirrors its selected items back to the original (now hidden) select element, even in multi-mode.

(It also continues to work with or without Chosen, say... if you decide to go a different direction in your application.)

How do I share a global variable between c files?

file 1:

int x = 50;

file 2:

extern int x;

printf("%d", x);