Programs & Examples On #Vsm

docker cannot start on windows

with the recent update of docker, I had an issue which was docker app hanged at startup. I resolved this by terminating wsl.exe using taskmanager.

enter image description here

PostgreSQL Exception Handling

To catch the error message and its code:

do $$       
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    raise notice 'The transaction is in an uncommittable state. '
                 'Transaction was rolled back';

    raise notice '% %', SQLERRM, SQLSTATE;

end; $$ 
language 'plpgsql';

Haven't found the line number yet

UPDATE April, 16, 2019

As suggested by Diego Scaravaggi, for Postgres 9.2 and up, use GET STACKED DIAGNOSTICS:

do language plpgsql $$
declare
    v_state   TEXT;
    v_msg     TEXT;
    v_detail  TEXT;
    v_hint    TEXT;
    v_context TEXT;
begin

    create table yyy(a int);
    create table yyy(a int); -- this will cause an error

exception when others then 

    get stacked diagnostics
        v_state   = returned_sqlstate,
        v_msg     = message_text,
        v_detail  = pg_exception_detail,
        v_hint    = pg_exception_hint,
        v_context = pg_exception_context;

    raise notice E'Got exception:
        state  : %
        message: %
        detail : %
        hint   : %
        context: %', v_state, v_msg, v_detail, v_hint, v_context;

    raise notice E'Got exception:
        SQLSTATE: % 
        SQLERRM: %', SQLSTATE, SQLERRM;     

    raise notice '%', message_text; -- invalid. message_text is contextual to GET STACKED DIAGNOSTICS only

end; $$;

Result:

NOTICE:  Got exception:
        state  : 42P07
        message: relation "yyy" already exists
        detail : 
        hint   : 
        context: SQL statement "create table yyy(a int)"
PL/pgSQL function inline_code_block line 11 at SQL statement
NOTICE:  Got exception:
        SQLSTATE: 42P07 
        SQLERRM: relation "yyy" already exists

ERROR:  column "message_text" does not exist
LINE 1: SELECT message_text
               ^
QUERY:  SELECT message_text
CONTEXT:  PL/pgSQL function inline_code_block line 33 at RAISE
SQL state: 42703

Aside from GET STACKED DIAGNOSTICS is SQL standard-compliant, its diagnostics variables (e.g., message_text) are contextual to GSD only. So if you have a field named message_text in your table, there's no chance that GSD can interfere with your field's value.

Still no line number though.

Download a file with Android, and showing the progress in a ProgressDialog

While I was starting to learn android development, I had learnt that ProgressDialog is the way to go. There is the setProgress method of ProgressDialog which can be invoked to update the progress level as the file gets downloaded.

The best I have seen in many apps is that they customize this progress dialog's attributes to give a better look and feel to the progress dialog than the stock version. Good to keeping the user engaged with some animation of like frog, elephant or cute cats/puppies. Any animation with in the progress dialog attracts users and they don't feel like being kept waiting for long.

How to convert string to IP address and vice versa

I was able to convert string to DWORD and back with this code:

char strAddr[] = "127.0.0.1"
DWORD ip = inet_addr(strAddr); // ip contains 16777343 [0x0100007f in hex]

struct in_addr paddr;
paddr.S_un.S_addr = ip;

char *strAdd2 = inet_ntoa(paddr); // strAdd2 contains the same string as strAdd

I am working in a maintenance project of old MFC code, so converting deprecated functions calls is not applicable.

Why can't Python parse this JSON data?

If you're using Python3, you can try changing your (connection.json file) JSON to:

{
  "connection1": {
    "DSN": "con1",
    "UID": "abc",
    "PWD": "1234",
    "connection_string_python":"test1"
  }
  ,
  "connection2": {
    "DSN": "con2",
    "UID": "def",
    "PWD": "1234"
  }
}

Then using the following code:

connection_file = open('connection.json', 'r')
conn_string = json.load(connection_file)
conn_string['connection1']['connection_string_python'])
connection_file.close()
>>> test1

Big-oh vs big-theta

Because there are algorithms whose best-case is quick, and thus it's technically a big O, not a big Theta.

Big O is an upper bound, big Theta is an equivalence relation.

How to easily map c++ enums to strings

Here is an attempt to get << and >> stream operators on enum automatically with an one line macro command only...

Definitions:

#include <string>
#include <iostream>
#include <stdexcept>
#include <algorithm>
#include <iterator>
#include <sstream>
#include <vector>

#define MAKE_STRING(str, ...) #str, MAKE_STRING1_(__VA_ARGS__)
#define MAKE_STRING1_(str, ...) #str, MAKE_STRING2_(__VA_ARGS__)
#define MAKE_STRING2_(str, ...) #str, MAKE_STRING3_(__VA_ARGS__)
#define MAKE_STRING3_(str, ...) #str, MAKE_STRING4_(__VA_ARGS__)
#define MAKE_STRING4_(str, ...) #str, MAKE_STRING5_(__VA_ARGS__)
#define MAKE_STRING5_(str, ...) #str, MAKE_STRING6_(__VA_ARGS__)
#define MAKE_STRING6_(str, ...) #str, MAKE_STRING7_(__VA_ARGS__)
#define MAKE_STRING7_(str, ...) #str, MAKE_STRING8_(__VA_ARGS__)
#define MAKE_STRING8_(str, ...) #str, MAKE_STRING9_(__VA_ARGS__)
#define MAKE_STRING9_(str, ...) #str, MAKE_STRING10_(__VA_ARGS__)
#define MAKE_STRING10_(str) #str

#define MAKE_ENUM(name, ...) MAKE_ENUM_(, name, __VA_ARGS__)
#define MAKE_CLASS_ENUM(name, ...) MAKE_ENUM_(friend, name, __VA_ARGS__)

#define MAKE_ENUM_(attribute, name, ...) name { __VA_ARGS__ }; \
    attribute std::istream& operator>>(std::istream& is, name& e) { \
        const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
        std::string str; \
        std::istream& r = is >> str; \
        const size_t len = sizeof(name##Str)/sizeof(name##Str[0]); \
        const std::vector<std::string> enumStr(name##Str, name##Str + len); \
        const std::vector<std::string>::const_iterator it = std::find(enumStr.begin(), enumStr.end(), str); \
        if (it != enumStr.end())\
            e = name(it - enumStr.begin()); \
        else \
            throw std::runtime_error("Value \"" + str + "\" is not part of enum "#name); \
        return r; \
    }; \
    attribute std::ostream& operator<<(std::ostream& os, const name& e) { \
        const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \
        return (os << name##Str[e]); \
    }

Usage:

// Declare global enum
enum MAKE_ENUM(Test3, Item13, Item23, Item33, Itdsdgem43);

class Essai {
public:
    // Declare enum inside class
    enum MAKE_CLASS_ENUM(Test, Item1, Item2, Item3, Itdsdgem4);

};

int main() {
    std::cout << Essai::Item1 << std::endl;

    Essai::Test ddd = Essai::Item1;
    std::cout << ddd << std::endl;

    std::istringstream strm("Item2");
    strm >> ddd;

    std::cout << (int) ddd << std::endl;
    std::cout << ddd << std::endl;
}

Not sure about the limitations of this scheme though... comments are welcome!

How to check for empty array in vba macro

As you are dealing with a string array, have you considered Join?

If Len(Join(FileNamesList)) > 0 Then

What's wrong with nullable columns in composite primary keys?

A primary key defines a unique identifier for every row in a table: when a table has a primary key, you have a guranteed way to select any row from it.

A unique constraint does not necessarily identify every row; it just specifies that if a row has values in its columns, then they must be unique. This is not sufficient to uniquely identify every row, which is what a primary key must do.

html script src="" triggering redirection with button

I was having this problem but i found out that it was a permissions problem I changed my permissions to 0744 and now it works. I don't know if this was your problem but it worked for me.

How can I brew link a specific version?

If you have installed, for example, php 5.4 it could be switched in the following way to php 5.5:

$ php --version
PHP 5.4.32 (cli) (built: Aug 26 2014 15:14:01) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

$ brew unlink php54

$ brew switch php55 5.5.16

$ php --version
PHP 5.5.16 (cli) (built: Sep  9 2014 14:27:18) 
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies

Plotting time in Python with Matplotlib

You can also plot the timestamp, value pairs using pyplot.plot (after parsing them from their string representation). (Tested with matplotlib versions 1.2.0 and 1.3.1.)

Example:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

Resulting image:

Line Plot


Here's the same as a scatter plot:

import datetime
import random
import matplotlib.pyplot as plt

# make up some data
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.scatter(x,y)
# beautify the x-labels
plt.gcf().autofmt_xdate()

plt.show()

Produces an image similar to this:

Scatter Plot

Importing Maven project into Eclipse

I want to import existing maven project into eclipse. I found 2 ways to do it, one is through running from command line mvn eclipse:eclipse and another is to install maven eclipse plugin from eclipse. What is the difference between the both and which one is preferable?

The maven-eclipse-plugin is a Maven plugin and has always been there (one of the first plugin available with Maven 1, one of the first plugin migrated to Maven 2). It has been during a long time the only decent way to integrateimport an existing maven project with Eclipse. Actually, it doesn't provide real integration, it just generates the .project and .classpath files (it has also WTP support) from a Maven project. I've used this plugin during years and was very happy with it (and very unsatisfied at this time by Eclipse plugins for Maven like m2eclipse).

The m2eclipse plugin is one of the Eclipse plugins for Maven. It's actually the first and most mature of the projects aimed at integrating Maven within the Eclipse IDE (this has not always been the case, it was not really usable ~2 years ago, see the feedback in Mevenide vs. M2Eclipse, Q for Eclipse/IAM). But, even if I do not use things like creating a Maven project from Eclipse or the POM editor or other fancy wizards, I have to say that this plugin is now totally usable, provides very smooth integration, has nice features... In other words, I finally switched to it :) I'd now recommend it to any user (advanced or beginners).

If I install maven eclipse plugin through the eclipse menu Help -> Install New Software, do I still need to modify my pom.xml to include the maven eclipse plugin in the plugins section?

This question is a bit confusing but the answer is no. With the m2eclipse plugin installed, just right-click the package explorer and Import... > Maven projects to import an existing maven project into Eclipse.

Is there a method that tells my program to quit?

The actual way to end a program, is to call

raise SystemExit

It's what sys.exit does, anyway.

A plain SystemExit, or with None as a single argument, sets the process' exit code to zero. Any non-integer exception value (raise SystemExit("some message")) prints the exception value to sys.stderr and sets the exit code to 1. An integer value sets the process' exit code to the value:

$ python -c "raise SystemExit(4)"; echo $?
4

MongoDB - Update objects in a document's array (nested updating)

There is no way to do this in single query. You have to search the document in first query:

If document exists:

db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Else

db.bar.update( {user_id : 123456 } , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

No need to add condition {$ne : "my_item_two" }.

Also in multithreaded enviourment you have to be careful that only one thread can execute the second (insert case, if document did not found) at a time, otherwise duplicate embed documents will be inserted.

Benefits of inline functions in C++?

Why not make all functions inline by default? Because it's an engineering trade off. There are at least two types of "optimization": speeding up the program and reducing the size (memory footprint) of the program. Inlining generally speeds things up. It gets rid of the function call overhead, avoiding pushing then pulling parameters from the stack. However, it also makes the memory footprint of the program bigger, because every function call must now be replaced with the full code of the function. To make things even more complicated, remember that the CPU stores frequently used chunks of memory in a cache on the CPU for ultra-rapid access. If you make the program's memory image big enough, your program won't be able to use the cache efficiently, and in the worst case inlining could actually slow your program down. To some extent the compiler can calculate what the trade offs are, and may be able to make better decisions than you can, just looking at the source code.

Insert data to MySql DB and display if insertion is success or failure

According to the book PHP and MySQL for Dynamic Web Sites (4th edition)

Example:

$r = mysqli_query($dbc, $q);

For simple queries like INSERT, UPDATE, DELETE, etc. (which do not return records), the $r variable—short for result—will be either TRUE or FALSE, depending upon whether the query executed successfully.

Keep in mind that “executed successfully” means that it ran without error; it doesn’t mean that the query’s execution necessarily had the desired result; you’ll need to test for that.

Then how to test?

While the mysqli_num_rows() function will return the number of rows generated by a SELECT query, mysqli_affected_rows() returns the number of rows affected by an INSERT, UPDATE, or DELETE query. It’s used like so:

$num = mysqli_affected_rows($dbc);

Unlike mysqli_num_rows(), the one argument the function takes is the database connection ($dbc), not the results of the previous query ($r).

mkdir -p functionality in Python

Function declaration;

import os
def mkdir_p(filename):

    try:
        folder=os.path.dirname(filename)  
        if not os.path.exists(folder):  
            os.makedirs(folder)
        return True
    except:
        return False

usage :

filename = "./download/80c16ee665c8/upload/backup/mysql/2014-12-22/adclient_sql_2014-12-22-13-38.sql.gz"

if (mkdir_p(filename):
    print "Created dir :%s" % (os.path.dirname(filename))

Android : difference between invisible and gone?

when you make it Gone every time of compilation of program the component gets initialized that means you are removing the component from layout and when you make it invisible the component it will take the same space in the layout but every time you dont need to initialize it.

if you set Visibility=Gone then you have to initialize the component..like

eg Button _mButton = new Button(this);

_mButton = (Button)findViewByid(R.id.mButton);

so it will take more time as compared to Visibility = invisible.

Special characters like @ and & in cURL POST data

Double quote (" ") the entire URL .It works.

curl "http://www.mysite.com?name=john&passwd=@31&3*J"

Getting first and last day of the current month

var now = DateTime.Now;
var first = new DateTime(now.Year, now.Month, 1);
var last = first.AddMonths(1).AddDays(-1);

You could also use DateTime.DaysInMonth method:

var last = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));

Java: Literal percent sign in printf statement

You can use StringEscapeUtils from Apache Commons Logging utility or escape manually using code for each character.

Preferred method to store PHP arrays (json_encode vs serialize)

JSON is better if you want to backup Data and restore it on a different machine or via FTP.

For example with serialize if you store data on a Windows server, download it via FTP and restore it on a Linux one it could not work any more due to the charachter re-encoding, because serialize stores the length of the strings and in the Unicode > UTF-8 transcoding some 1 byte charachter could became 2 bytes long making the algorithm crash.

Is putting a div inside an anchor ever correct?

Depending on the version of HTML you're catering to:

  • HTML 5 states that the <a> element "may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links)".

  • HTML 4.01 specifies that <a> elements may only contain inline elements. A <div> is a block element, so it may not appear inside an <a>.

    Of course you are at liberty to style an inline element such that it appears to be a block, or indeed style a block so that it is rendered inline. The use of the terms inline and block in HTML refers to the relationship of the elements to the semantic structure of the document, whereas the same terms in CSS are related more to the visual styling of the elements. If you make inline elements display in a blocky manner, that's fine.

    However you should ensure that the structure of the document still makes sense when CSS is not present, for example when accessed via an assistive technology such as a screen reader - or indeed when examined by the mighty Googlebot.

Difference between Console.Read() and Console.ReadLine()?

These are the methods of system.console

  • ReadKey() (returns a character): reads only one single character from the standard input stream or command line. Usually used when you're giving options to the user in the console to select from, such as select A, B or C. Another prominent example, Press Y or n to continue.
  • ReadLine() (returns a string): or Console.Readline() reads a single line from the standard input stream or the command line. As an example, it can be used to ask the user enter their name or age. It reads all the character till we press enter.
  • Read() (returns an int): or Console.Read() reads only one single character from the standard input stream. Similar to ReadKey except that it returns an integer. It returns the next character from the input stream, or returns (-1) if there is no more character to be read.

(There are more system.console methods like write() and writeline() as well which are used to write in command line, behaving similarly as read() and readline() methods)

This was clearly described with examples in the MSDN documentation (links are included above).

What is the difference between putting a property on application.yml or bootstrap.yml in spring boot?

Bootstrap.yml is the first file loaded when you start spring boot application and application.property is loaded when application starts. So, you keep, may be your config server's credentials etc., in bootstrap.yml which is required during loading application and then in application.properties you keep may be database URL etc.

How can I control Chromedriver open window size?

try this

using System.Drawing;
driver.Manage().Window.Size = new Size(width, height);

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

The best way to remove duplicate values from NSMutableArray in Objective-C?

just use this simple code :

NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];

since nsset doesn't allow duplicate values and all objects returns an array

Remove a HTML tag but keep the innerHtml

The simplest way to remove inner html elements and return only text would the JQuery .text() function.

Example:

var text = $('<p>A nice house was found in <b>Toronto</b></p>');

alert( text.html() );
//Outputs A nice house was found in <b>Toronto</b>

alert( text.text() );
////Outputs A nice house was found in Toronto

jsFiddle Demo

Is there a unique Android device ID?

Get the device ID only once, and then store it in a database or a file. In this case, if it is the first boot of the app, it generates an ID and stores it. Next time, it will only take the ID stored in the file.

Bootstrap 3 Gutter Size

I've been stuck with this problem, my solution was creating a mixin which allows me to specify in SCSS, the actual gutter size I want ...

Solution: 1)

@mixin add-gutter($size) {
    margin-right: -$size;
    margin-left: -$size;

    > [class*="col-"] {
        padding-right: $size;
        padding-left: $size;
    }
}



.that-special-row{
    @include add-gutter(7px);
}

And to use it...

<div class="row that-special-row"></div>

The actual solution came about from this issue mentionned on github, which I believe addresses the same problem.

Solution: 2)

Another solution, would be simply to create your custom CSS class

.small-gutters {
    margin-right: -10px;
    margin-left: -10px;
    > [class*="col-"] {
      padding-right: 10px;
      padding-left: 10px;
    }
  }

Hope that helps!

Can I dynamically add HTML within a div tag from C# on load event?

You want to put code in the master page code behind that inserts HTML into the contents of a page that is using that master page?

I would not search for the control via FindControl as this is a fragile solution that could easily be broken if the name of the control changed.

Your best bet is to declare an event in the master page that any child page could handle. The event could pass the HTML as an EventArg.

Interface vs Abstract Class (general OO)

Interface:

Does not contain Impleamentations Interface can inherit from a number of interfaces(Multiple inheritance supported) Members are automatically public May contain properties, methods, events and indexers

Abstract Class:

May/mayn't contain Implementations; At least one member will not be implemented. A Class may inherit from a single Base class; multiple inheritance not allowed. Members have access modifiers May contain fields, properties, constructors, destructors, methods, events and indexers

These are the key differences between Abstract Class and Interfaces.

How to Convert UTC Date To Local time Zone in MySql Select Query

 select convert_tz(now(),@@session.time_zone,'+05:30')

replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994

to format into desired time format, eg:

 select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p') 

you will get similar to this -> Dec 17 2014 10:39:56 AM

Match multiline text using regular expression

str.matches(regex) behaves like Pattern.matches(regex, str) which attempts to match the entire input sequence against the pattern and returns

true if, and only if, the entire input sequence matches this matcher's pattern

Whereas matcher.find() attempts to find the next subsequence of the input sequence that matches the pattern and returns

true if, and only if, a subsequence of the input sequence matches this matcher's pattern

Thus the problem is with the regex. Try the following.

String test = "User Comments: This is \t a\ta \ntest\n\n message \n";

String pattern1 = "User Comments: [\\s\\S]*^test$[\\s\\S]*";
Pattern p = Pattern.compile(pattern1, Pattern.MULTILINE);
System.out.println(p.matcher(test).find());  //true

String pattern2 = "(?m)User Comments: [\\s\\S]*^test$[\\s\\S]*";
System.out.println(test.matches(pattern2));  //true

Thus in short, the (\\W)*(\\S)* portion in your first regex matches an empty string as * means zero or more occurrences and the real matched string is User Comments: and not the whole string as you'd expect. The second one fails as it tries to match the whole string but it can't as \\W matches a non word character, ie [^a-zA-Z0-9_] and the first character is T, a word character.

What jsf component can render a div tag?

In JSF 2.2 it's possible to use passthrough elements:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:jsf="http://xmlns.jcp.org/jsf">
    ...
    <div jsf:id="id1" />
    ...
</html>

The requirement is to have at least one attribute in the element using jsf namespace.

Run a shell script with an html button

This is how it look like in pure bash

cat /usr/lib/cgi-bin/index.cgi

#!/bin/bash
echo Content-type: text/html
echo ""
## make POST and GET stings
## as bash variables available
if [ ! -z $CONTENT_LENGTH ] && [ "$CONTENT_LENGTH" -gt 0 ] && [ $CONTENT_TYPE != "multipart/form-data" ]; then
read -n $CONTENT_LENGTH POST_STRING <&0
eval `echo "${POST_STRING//;}"|tr '&' ';'`
fi
eval `echo "${QUERY_STRING//;}"|tr '&' ';'`

echo  "<!DOCTYPE html>"
echo  "<html>"
echo  "<head>"
echo  "</head>"

if [[ "$vote" = "a" ]];then
echo "you pressed A"
  sudo /usr/local/bin/run_a.sh
elif [[ "$vote" = "b" ]];then
echo "you pressed B"
  sudo /usr/local/bin/run_b.sh
fi

echo  "<body>"
echo  "<div id=\"content-container\">"
echo  "<div id=\"content-container-center\">"
echo  "<form id=\"choice\" name='form' method=\"POST\" action=\"/\">"
echo  "<button id=\"a\" type=\"submit\" name=\"vote\" class=\"a\" value=\"a\">A</button>"
echo  "<button id=\"b\" type=\"submit\" name=\"vote\" class=\"b\" value=\"b\">B</button>"
echo  "</form>"
echo  "<div id=\"tip\">"
echo  "</div>"
echo  "</div>"
echo  "</div>"
echo  "</div>"
echo  "</body>"
echo  "</html>"

Build with https://github.com/tinoschroeter/bash_on_steroids

Are one-line 'if'/'for'-statements good Python style?

Well,

if "exam" in "example": print "yes!"

Is this an improvement? No. You could even add more statements to the body of the if-clause by separating them with a semicolon. I recommend against that though.

jQuery val is undefined?

try: $('#editorTitle').attr('value') ?

How to view files in binary from bash?

You can open emacs (in terminal mode, using emacs -nw for instance), and then use Hexl mode: M-x hexl-mode.

https://www.gnu.org/software/emacs/manual/html_node/emacs/Editing-Binary-Files.html

Java Date cut off time information

Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();

ssl.SSLError: tlsv1 alert protocol version

For python2 users on MacOS (python@2 formula won't be found), as brew stopped support of python2 you need to use such command! But don't forget to unlink old python if it was pre-installed.

brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/86a44a0a552c673a05f11018459c9f5faae3becc/Formula/[email protected]

If you've done some mistake, simply brew uninstall python@2 old way, and try again.

thank you hyperknot (answer here)

jQuery AJAX form data serialize using PHP

Change your code as follows -

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm");
$("#smt").click(function(){
$.ajax({
        type:"POST",
        url:form.attr("action"),
        data:form.serialize(),

        success: function(response){
        if(response == 1){
              $("#err").html("Hi Tony");//updated
        }  else {
            $("#err").html("I dont know you.");//updated
        }
        }
    });
});
});
</script>

PHP -

<?php
$user=$_POST['user'];
$pass=$_POST['pass'];

if($user=="tony")
{
    echo 1;   
}
else
{
    echo 0;    
}
?>

Adding a newline character within a cell (CSV)

I have the same issue, when I try to export the content of email to csv and still keep it break line when importing to excel.

I export the conent as this: ="Line 1"&CHAR(10)&"Line 2"

When I import it to excel(google), excel understand it as string. It still not break new line.

We need to trigger excel to treat it as formula by: Format -> Number | Scientific.

This is not the good way but it resolve my issue.

How do I space out the child elements of a StackPanel?

I improved on Elad Katz' answer.

  • Add LastItemMargin property to MarginSetter to specially handle the last item
  • Add Spacing attached property with Vertical and Horizontal properties that adds spacing between items in vertical and horizontal lists and eliminates any trailing margin at the end of the list

Source code in gist.

Example:

<StackPanel Orientation="Horizontal" foo:Spacing.Horizontal="5">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

<StackPanel Orientation="Vertical" foo:Spacing.Vertical="5">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

<!-- Same as vertical example above -->
<StackPanel Orientation="Vertical" foo:MarginSetter.Margin="0 0 0 5" foo:MarginSetter.LastItemMargin="0">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

Update React component every second

The following code is a modified example from React.js website.

Original code is available here: https://reactjs.org/#a-simple-component

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      seconds: parseInt(props.startTimeInSeconds, 10) || 0
    };
  }

  tick() {
    this.setState(state => ({
      seconds: state.seconds + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  formatTime(secs) {
    let hours   = Math.floor(secs / 3600);
    let minutes = Math.floor(secs / 60) % 60;
    let seconds = secs % 60;
    return [hours, minutes, seconds]
        .map(v => ('' + v).padStart(2, '0'))
        .filter((v,i) => v !== '00' || i > 0)
        .join(':');
  }

  render() {
    return (
      <div>
        Timer: {this.formatTime(this.state.seconds)}
      </div>
    );
  }
}

ReactDOM.render(
  <Timer startTimeInSeconds="300" />,
  document.getElementById('timer-example')
);

Maximum number of rows of CSV data in excel sheet

CSV files have no limit of rows you can add to them. Excel won't hold more that the 1 million lines of data if you import a CSV file having more lines.

Excel will actually ask you whether you want to proceed when importing more than 1 million data rows. It suggests to import the remaining data by using the text import wizard again - you will need to set the appropriate line offset.

Install a .NET windows service without InstallUtil.exe

Here is a class I use when writing services. I usually have an interactive screen that comes up when the service is not called. From there I use the class as needed. It allows for multiple named instances on the same machine -hence the InstanceID field

Sample Call

  IntegratedServiceInstaller Inst = new IntegratedServiceInstaller();
  Inst.Install("MySvc", "My Sample Service", "Service that executes something",
                    _InstanceID,
// System.ServiceProcess.ServiceAccount.LocalService,      // this is more secure, but only available in XP and above and WS-2003 and above
  System.ServiceProcess.ServiceAccount.LocalSystem,       // this is required for WS-2000
  System.ServiceProcess.ServiceStartMode.Automatic);
  if (controller == null)
  {
    controller = new System.ServiceProcess.ServiceController(String.Format("MySvc_{0}", _InstanceID), ".");
                }
                if (controller.Status == System.ServiceProcess.ServiceControllerStatus.Running)
                {
                    Start_Stop.Text = "Stop Service";
                    Start_Stop_Debugging.Enabled = false;
                }
                else
                {
                    Start_Stop.Text = "Start Service";
                    Start_Stop_Debugging.Enabled = true;
                }

The class itself

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;

namespace MySvc
{
    class IntegratedServiceInstaller
    {
        public void Install(String ServiceName, String DisplayName, String Description,
            String InstanceID,
            System.ServiceProcess.ServiceAccount Account, 
            System.ServiceProcess.ServiceStartMode StartMode)
        {
            //http://www.theblacksparrow.com/
            System.ServiceProcess.ServiceProcessInstaller ProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
            ProcessInstaller.Account = Account;

            System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();

            System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext();
            string processPath = Process.GetCurrentProcess().MainModule.FileName;
            if (processPath != null && processPath.Length > 0)
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(processPath);

                String path = String.Format("/assemblypath={0}", fi.FullName);
                String[] cmdline = { path };
                Context = new System.Configuration.Install.InstallContext("", cmdline);
            }

            SINST.Context = Context;
            SINST.DisplayName = String.Format("{0} - {1}", DisplayName, InstanceID);
            SINST.Description = String.Format("{0} - {1}", Description, InstanceID);
            SINST.ServiceName = String.Format("{0}_{1}", ServiceName, InstanceID);
            SINST.StartType = StartMode;
            SINST.Parent = ProcessInstaller;

            // http://bytes.com/forum/thread527221.html
            SINST.ServicesDependedOn = new String[] { "Spooler", "Netlogon", "Netman" };

            System.Collections.Specialized.ListDictionary state = new System.Collections.Specialized.ListDictionary();
            SINST.Install(state);

            // http://www.dotnet247.com/247reference/msgs/43/219565.aspx
            using (RegistryKey oKey = Registry.LocalMachine.OpenSubKey(String.Format(@"SYSTEM\CurrentControlSet\Services\{0}_{1}", ServiceName, InstanceID), true))
            {
                try
                {
                    Object sValue = oKey.GetValue("ImagePath");
                    oKey.SetValue("ImagePath", sValue);
                }
                catch (Exception Ex)
                {
                    System.Windows.Forms.MessageBox.Show(Ex.Message);
                }
            }

        }
        public void Uninstall(String ServiceName, String InstanceID)
        {
            //http://www.theblacksparrow.com/
            System.ServiceProcess.ServiceInstaller SINST = new System.ServiceProcess.ServiceInstaller();

            System.Configuration.Install.InstallContext Context = new System.Configuration.Install.InstallContext("c:\\install.log", null);
            SINST.Context = Context;
            SINST.ServiceName = String.Format("{0}_{1}", ServiceName, InstanceID);
            SINST.Uninstall(null);
        }
    }
}

Creating default object from empty value in PHP?

If you put "@" character begin of the line then PHP doesn't show any warning/notice for this line. For example:

$unknownVar[$someStringVariable]->totalcall = 10; // shows a warning message that contains: Creating default object from empty value

For preventing this warning for this line you must put "@" character begin of the line like this:

@$unknownVar[$someStringVariable]->totalcall += 10; // no problem. created a stdClass object that name is $unknownVar[$someStringVariable] and created a properti that name is totalcall, and it's default value is 0.
$unknownVar[$someStringVariable]->totalcall += 10; // you don't need to @ character anymore.
echo $unknownVar[$someStringVariable]->totalcall; // 20

I'm using this trick when developing. I don't like disable all warning messages becouse if you don't handle warnings correctly then they will become a big error in future.

how do I give a div a responsive height

For the height of a div to be responsive, it must be inside a parent element with a defined height to derive it's relative height from.

If you set the height of the container holding the image and text box on the right, you can subsequently set the heights of its two children to be something like 75% and 25%.

However, this will get a bit tricky when the site layout gets narrower and things will get wonky. Try setting the padding on .contentBg to something like 5.5%.

My suggestion is to use Media Queries to tweak the padding at different screen sizes, then bump everything into a single column when appropriate.

How to get next/previous record in MySQL?

Here we have a way to fetch previous and next records using single MySQL query. Where 5 is the id of current record.

select * from story where catagory=100 and  (
    id =(select max(id) from story where id < 5 and catagory=100 and order by created_at desc) 
    OR 
    id=(select min(id) from story where id > 5 and catagory=100 order by created_at desc) )

Run git pull over all subdirectories

I combined points from several comments and answers:

find . -maxdepth 1 -type d -name .git -execdir git pull \;

Fastest way to ping a network range and return responsive hosts?

This is python code for the ping in range of the 192.168.0.0-192.168.0.100. You can change for loop as you comfort.

# -*- coding: utf-8 -*-
import socket
import os
import sys

up_ip =[] #list to store the ip-addresses of server online
for x in range(100):  #here range is 0-100. You can change the range according to your comfort

    server_ip = '192.168.0.'+ str(x)
    print "Trying ,server_ip,... \n"

    rep = os.system('ping -c 1 ' + server_ip)

    if rep == 0:
        up_ip.append(server_ip)
        print '******************* Server Is Up **************** \n'
    else:
        print 'server is down \n'

print up_ip

ImportError: No module named MySQLdb

I got this issue when I was working on SQLAlchemy. The default dialect used by SQLAlchemy for MySQL is mysql+mysqldb.

engine = create_engine('mysql+mysqldb://scott:tiger@localhost/foo')

I got the "No module named MySQLdb" error when the above command was executed. To fix it I installed the mysql-python module and the issue was fixed.

sudo pip install mysql-python

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

Try this

<client>
  <endpoint>
    <identity>
      <servicePrincipalName value="" />
    </identity>
  </endpoint>
</client>

I've encountered this error before when working in a webfarm and this fixed it for me.

How to change font-color for disabled input?

The following gets you pretty close in IE8 and works in other browsers too.

In your html:

<input type="text" 
       readonly="readonly"    <!-- disallow editting -->
       onfocus="this.blur();" <!-- prevent focus -->
       tabindex="-1"          <!-- disallow tabbing -->
       class="disabledInput"  <!-- change the color with CSS -->
       />

In your CSS:

.disabledInput {
    color: black;
}

In IE8, there is a slight amount of border color change on hover. Some CSS for input.disabledInput:hover could probably take care of this.

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

Let's dissect it. There are three parts:

  1. cd -- This is change directory command.
  2. /d -- This switch makes cd change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0. (%~d0 Changs active drive, cd %~p0 change the directory).
  3. %~dp0 -- This can be dissected further into three parts:
    1. %0 -- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.
    2. %~0 -- The ~ there strips double quotes (") around the expanded argument.
    3. %dp0 -- The d and p there are modifiers of the expansion. The d forces addition of a drive letter and the p adds full path.

SQLAlchemy insert or update example

I try lots of ways and finally try this:

def db_persist(func):
    def persist(*args, **kwargs):
        func(*args, **kwargs)
        try:
            session.commit()
            logger.info("success calling db func: " + func.__name__)
            return True
        except SQLAlchemyError as e:
            logger.error(e.args)
            session.rollback()
            return False

    return persist

and :

@db_persist
def insert_or_update(table_object):
    return session.merge(table_object)

Can I use return value of INSERT...RETURNING in another INSERT?

You can do so starting with Postgres 9.1:

with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows

In the meanwhile, if you're only interested in the id, you can do so with a trigger:

create function t1_ins_into_t2()
  returns trigger
as $$
begin
  insert into table2 (val) values (new.id);
  return new;
end;
$$ language plpgsql;

create trigger t1_ins_into_t2
  after insert on table1
for each row
execute procedure t1_ins_into_t2();

ggplot2: sorting a plot

You need to make the x-factor into an ordered factor with the ordering you want, e.g

x <- data.frame("variable"=letters[1:5], "value"=rnorm(5)) ## example data
x <- x[with(x,order(-value)), ] ## Sorting
x$variable <- ordered(x$variable, levels=levels(x$variable)[unclass(x$variable)])

ggplot(x, aes(x=variable,y=value)) + geom_bar() +
   scale_y_continuous("",formatter="percent") + coord_flip()

I don't know any better way to do the ordering operation. What I have there will only work if there are no duplicate levels for x$variable.

Package signatures do not match the previously installed version

In my case the issue was I had installed an app with the package name let's say com.example.package using android studio on my device. I created another app with the same package name and was trying to install it on my device. That is what was causing the problem. So just check on your device whether another app with the same package name already exists or not.

Pandas groupby month and year

Why not keep it simple?!

GB=DF.groupby([(DF.index.year),(DF.index.month)]).sum()

giving you,

print(GB)
        abc  xyz
2013 6   80  250
     8   40   -5
2014 1   25   15
     2   60   80

and then you can plot like asked using,

GB.plot('abc','xyz',kind='scatter')

MySQL timestamp select date range

Whenever possible, avoid applying functions to a column in the where clause:

SELECT *
  FROM table_name
 WHERE timestamp >= UNIX_TIMESTAMP('2010-10-01 00:00:00') 
   AND timestamp <  UNIX_TIMESTAMP('2010-11-01 00:00:00');

Applying a function to the timestamp column (e.g., FROM_UNIXTIME(timestamp) = ...) makes indexing much harder.

jQuery iframe load() event?

Without code in iframe + animate:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">

function resizeIframe(obj) {

    jQuery(document).ready(function($) {

        $(obj).animate({height: obj.contentWindow.document.body.scrollHeight + 'px'}, 500)

    });

}    
</script>
<iframe width="100%" src="iframe.html" height="0" frameborder="0" scrolling="no" onload="resizeIframe(this)" >

How do I update a Tomcat webapp without restarting the entire service?

There are multiple easy ways.

  1. Just touch web.xml of any webapp.

    touch /usr/share/tomcat/webapps/<WEBAPP-NAME>/WEB-INF/web.xml
    

You can also update a particular jar file in WEB-INF/lib and then touch web.xml, rather than building whole war file and deploying it again.

  1. Delete webapps/YOUR_WEB_APP directory, Tomcat will start deploying war within 5 seconds (assuming your war file still exists in webapps folder).

  2. Generally overwriting war file with new version gets redeployed by tomcat automatically. If not, you can touch web.xml as explained above.

  3. Copy over an already exploded "directory" to your webapps folder

How can I check if a view is visible or not in Android?

You'd use the corresponding method getVisibility(). Method names prefixed with 'get' and 'set' are Java's convention for representing properties. Some language have actual language constructs for properties but Java isn't one of them. So when you see something labeled 'setX', you can be 99% certain there's a corresponding 'getX' that will tell you the value.

Why and when to use angular.copy? (Deep Copy)

I know its already answered, still i am just trying to make it simple. So angular.copy(data) you can use in case where you want to modify/change your received object by keeping its original values unmodified/unchanged.

For example: suppose i have made api call and got my originalObj, now i want to change the values of api originalObj for some case but i want the original values too so what i can do is, i can make a copy of my api originalObj in duplicateObj and modify duplicateObj this way my originalObj values will not change. In simple words duplicateObj modification will not reflect in originalObj unlike how js obj behave.

 $scope.originalObj={
            fname:'sudarshan',
            country:'India'
        }
        $scope.duplicateObj=angular.copy($scope.originalObj);
        console.log('----------originalObj--------------');
        console.log($scope.originalObj);
        console.log('-----------duplicateObj---------------');
        console.log($scope.duplicateObj);

        $scope.duplicateObj.fname='SUD';
        $scope.duplicateObj.country='USA';
        console.log('---------After update-------')
        console.log('----------originalObj--------------');
        console.log($scope.originalObj);
        console.log('-----------duplicateObj---------------');
        console.log($scope.duplicateObj);

Result is like....

    ----------originalObj--------------
manageProfileController.js:1183 {fname: "sudarshan", country: "India"}
manageProfileController.js:1184 -----------duplicateObj---------------
manageProfileController.js:1185 {fname: "sudarshan", country: "India"}
manageProfileController.js:1189 ---------After update-------
manageProfileController.js:1190 ----------originalObj--------------
manageProfileController.js:1191 {fname: "sudarshan", country: "India"}
manageProfileController.js:1192 -----------duplicateObj---------------
manageProfileController.js:1193 {fname: "SUD", country: "USA"}

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

How to create an array containing 1...N

Multiple ways using ES6

Using spread operator (...) and keys method

[ ...Array(N).keys() ].map( i => i+1);

Fill/Map

Array(N).fill().map((_, i) => i+1);

Array.from

Array.from(Array(N), (_, i) => i+1)

Array.from and { length: N } hack

Array.from({ length: N }, (_, i) => i+1)

Note about generalised form

All the forms above can produce arrays initialised to pretty much any desired values by changing i+1 to expression required (e.g. i*2, -i, 1+i*2, i%2 and etc). If expression can be expressed by some function f then the first form becomes simply

[ ...Array(N).keys() ].map(f)

Examples:

Array.from({length: 5}, (v, k) => k+1); 
// [1,2,3,4,5]

Since the array is initialized with undefined on each position, the value of v will be undefined

Example showcasing all the forms

_x000D_
_x000D_
let demo= (N) => {_x000D_
  console.log(_x000D_
    [ ...Array(N).keys() ].map(( i) => i+1),_x000D_
    Array(N).fill().map((_, i) => i+1) ,_x000D_
    Array.from(Array(N), (_, i) => i+1),_x000D_
    Array.from({ length: N }, (_, i) => i+1)_x000D_
  )_x000D_
}_x000D_
_x000D_
demo(5)
_x000D_
_x000D_
_x000D_

More generic example with custom initialiser function f i.e.

[ ...Array(N).keys() ].map((i) => f(i))

or even simpler

[ ...Array(N).keys() ].map(f)

_x000D_
_x000D_
let demo= (N,f) => {_x000D_
  console.log(_x000D_
    [ ...Array(N).keys() ].map(f),_x000D_
    Array(N).fill().map((_, i) => f(i)) ,_x000D_
    Array.from(Array(N), (_, i) => f(i)),_x000D_
    Array.from({ length: N }, (_, i) => f(i))_x000D_
  )_x000D_
}_x000D_
_x000D_
demo(5, i=>2*i+1)
_x000D_
_x000D_
_x000D_

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

How to disable scrolling temporarily?

Depending on what you want to achieve with the removed scroll you could just fix the element that you want to remove scroll from (on click, or whatever other trigger you'd like to temporarily deactivate scroll)

I was searching around for a "temp no scroll" solution and for my needs, this solved it

make a class

.fixed{
    position: fixed;
}

then with Jquery

var someTrigger = $('#trigger'); //a trigger button
var contentContainer = $('#content'); //element I want to temporarily remove scroll from

contentContainer.addClass('notfixed'); //make sure that the element has the "notfixed" class

//Something to trigger the fixed positioning. In this case we chose a button.
someTrigger.on('click', function(){

    if(contentContainer.hasClass('notfixed')){
        contentContainer.removeClass('notfixed').addClass('fixed');

    }else if(contentContainer.hasClass('fixed')){
        contentContainer.removeClass('fixed').addClass('notfixed');
    };
});

I found that this was a simple enough solution that works well on all browsers, and also makes for simple use on portable devices (i.e. iPhones, tablets etc). Since the element is temporarily fixed, there is no scroll :)

NOTE! Depending on the placement of your "contentContainer" element you might need to adjust it from the left. Which can easily be done by adding a css left value to that element when the fixed class is active

contentContainer.css({
    'left': $(window).width() - contentContainer.width()/2 //This would result in a value that is the windows entire width minus the element we want to "center" divided by two (since it's only pushed from one side)
});

Python regex to match dates

Well, from my understanding, simply for matching this format in a given string, I prefer this regular expression:

pattern='[0-9|/]+'

to match the format in a more strict way, the following works:

pattern='(?:[0-9]{2}/){2}[0-9]{2}'

Personally, I cannot agree with unutbu's answer since sometimes we use regular expression for "finding" and "extract", not only "validating".

Disabling Chrome cache for website development

Picture of reload menu

  1. Pull up the Chrome developer console by pressing F12 and then (with the console open):

  2. Right click (or hold left click) on the reload button at the top of the browser and select "Empty Cache and Hard Reload."

This will go beyond "Hard Reload" to empty the cache entirely, ensuring that anything downloaded via javascript or etc. will also avoid using the cache. You don't have to mess with settings or anything, it's a quick 1-shot solution.

How to copy a folder via cmd?

xcopy  "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i

Probably the problem is the space.Try with quotes.

Microsoft Excel ActiveX Controls Disabled?

Simplified instructions for end-users. Feel free to copy/paste the following.

Here’s how to fix the problem when it comes up:

  1. Close all your Office programs and files.
  2. Open Windows Explorer and type %TEMP% into the address bar, then press Enter. This will take you into the system temporary folder.
  3. Locate and delete the following folders: Excel8.0, VBE, Word8.0
  4. Now try to use your file again, it shouldn't have any problems.

You might need to wait until the problem occurs in order for this fix to work. Applying it prematurely (before the Windows Update gets installed on your system) won't help.

Make a nav bar stick

Just use z-index CSS property as described in the highest liked answer and the nav bar will stick to the top.

Example:

<div class="navigation">
 <nav>
   <ul>
    <li>Home</li>
    <li>Contact</li>
   </ul>
 </nav>

.navigation {
   /* fixed keyword is fine too */
   position: sticky;
   top: 0;
   z-index: 100;
   /* z-index works pretty much like a layer:
   the higher the z-index value, the greater
   it will allow the navigation tag to stay on top
   of other tags */
}

How to prevent column break within an element?

This answer might only apply to certain circumstances; If you set a height to your elements, this will be obeyed by the column styling. There-by keeping anything that is contained within that height to a row.

I had a list, like the op, but it contained two elements, items and buttons to act upon those items. I treated it like a table <ul> - table, <li> - table-row, <div> - table-cell put the UL in a 4 column layout. The columns were sometimes being split between the item and it's buttons. The trick I used was to give the Div elements a line height to cover the buttons.

How to specify the bottom border of a <tr>?

What I want to say here is like some kind of add-on on @Suciu Lucian's answer.

The weird situation I ran into is that when I apply the solution of @Suciu Lucian in my file, it works in Chrome but not in Safari (and did not try in Firefox). After I studied the guide of styling table border published by w3.org, I found something alternative:

table.myTable{
  border-spacing: 0;
}

table.myTable td{
  border-bottom:1px solid red;
}

Yes you have to style the td instead of the tr.

PostgreSQL: export resulting data from SQL query to Excel/CSV

In PostgreSQL 9.4 to create to file CSV with the header in Ubuntu:

COPY (SELECT * FROM tbl) TO '/home/user/Desktop/result_sql.csv' WITH CSV HEADER;

Note: The folder must be writable.

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

Details on return values and their meaning

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

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

return 0;

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

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

How do I clone a generic List in Java?

Why would you want to clone? Creating a new list usually makes more sense.

List<String> strs;
...
List<String> newStrs = new ArrayList<>(strs);

Job done.

Struct with template variables in C++

The problem is you can't template a typedef, also there is no need to typedef structs in C++.

The following will do what you need

template <typename T> 
struct array { 
  size_t x; 
  T *ary; 
}; 

Getting Google+ profile picture url with user_id

You can get the URL for the profile image using the people.get method of the Google+ API. That does require an extra round trip, but is the most reliable way to get the image.

You technically can also use the URL https://s2.googleusercontent.com/s2/photos/profile/{id}?sz={size} which will then redirect to the final URL. {id} is the Google user ID or one of the old Google Profiles usernames (they still exist for users who had them, but I don't think you can create new ones anymore). {size} is the desired size of the photo in pixels. I'm almost certain this is not a documented, supported feature, so I wouldn't rely on it for anything important as it may go away at anytime without notice. But for quick prototypes or small one-off applications, it may be sufficient.

How to upgrade glibc from version 2.13 to 2.15 on Debian?

I was able to install libc6 2.17 in Debian Wheezy by editing the recommendations in perror's answer:

IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1. Then you can stop x (slim) with sudo /etc/init.d/slim stop

(replace slim with mdm or lightdm or whatever)

Add the following line to the file /etc/apt/sources.list:

deb http://ftp.debian.org/debian experimental main

Should be changed to:

deb http://ftp.debian.org/debian sid main

Then follow the rest of perror's post:

Update your package database:

apt-get update

Install the eglibc package:

apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg

IMPORTANT
After done updating libc6, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main), or else you risk upgrading your whole distro to sid.

Hope this helps. It took me a while to figure out.

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Here's one slight alteration to the answers of a query that creates the table upon execution (i.e. you don't have to create the table first):

SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X

"Application tried to present modally an active controller"?

In my case i was trying to present the viewController (i have the reference of the viewController in the TabBarViewController) from different view controllers and it was crashing with the above message. In that case to avoid presenting you can use

viewController.isBeingPresented

!viewController.isBeingPresented {
          // Present your ViewController only if its not present to the user currently.
}

Might help someone.

Compare objects in Angular

I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.

BE MINDFUL, If you use angular.equals() on objects that have property obj.$something (property name starts with $) those properties will get ignored in comparison.

Example:

var obj1 = {
  $key0: "A",
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  $key0: "B"
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)

What does "both" mean in <div style="clear:both">

Both means "every item in a set of two things". The two things being "left" and "right"

What is the difference between MySQL, MySQLi and PDO?

Specifically, the MySQLi extension provides the following extremely useful benefits over the old MySQL extension..

OOP Interface (in addition to procedural) Prepared Statement Support Transaction + Stored Procedure Support Nicer Syntax Speed Improvements Enhanced Debugging

PDO Extension

PHP Data Objects extension is a Database Abstraction Layer. Specifically, this is not a MySQL interface, as it provides drivers for many database engines (of course including MYSQL).

PDO aims to provide a consistent API that means when a database engine is changed, the code changes to reflect this should be minimal. When using PDO, your code will normally "just work" across many database engines, simply by changing the driver you're using.

In addition to being cross-database compatible, PDO also supports prepared statements, stored procedures and more, whilst using the MySQL Driver.

MySQL - Get row number on select

SELECT @rn:=@rn+1 AS rank, itemID, ordercount
FROM (
  SELECT itemID, COUNT(*) AS ordercount
  FROM orders
  GROUP BY itemID
  ORDER BY ordercount DESC
) t1, (SELECT @rn:=0) t2;

Jquery DatePicker Set default date

use defaultDate()

Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current [[UI/Datepicker#option-dateFormat|dateFormat]], or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.

try this

$("[name=trainingStartFromDate]").datepicker({ dateFormat: 'dd-mm-yy', changeYear: true,defaultDate: new Date()});
$("[name=trainingStartToDate]").datepicker({ dateFormat: 'dd-mm-yy', changeYear: true,defaultDate: +15}); 

How to get all possible combinations of a list’s elements?

Have a look at itertools.combinations:

itertools.combinations(iterable, r)

Return r length subsequences of elements from the input iterable.

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

Since 2.6, batteries are included!

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Pythonic way to check if a list is sorted or not

A solution using assignment expressions (added in Python 3.8):

def is_sorted(seq):
    seq_iter = iter(seq)
    cur = next(seq_iter, None)
    return all((prev := cur) <= (cur := nxt) for nxt in seq_iter)

z = list(range(10))
print(z)
print(is_sorted(z))

import random
random.shuffle(z)
print(z)
print(is_sorted(z))

z = []
print(z)
print(is_sorted(z))

Gives:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
True
[1, 7, 5, 9, 4, 0, 8, 3, 2, 6]
False
[]
True

Histogram using gnuplot?

Be very careful: all of the answers on this page are implicitly taking the decision of where the binning starts - the left-hand edge of the left-most bin, if you like - out of the user's hands. If the user is combining any of these functions for binning data with his/her own decision about where binning starts (as is done on the blog which is linked to above) the functions above are all incorrect. With an arbitrary starting point for binning 'Min', the correct function is:

bin(x) = width*(floor((x-Min)/width)+0.5) + Min

You can see why this is correct sequentially (it helps to draw a few bins and a point somewhere in one of them). Subtract Min from your data point to see how far into the binning range it is. Then divide by binwidth so that you're effectively working in units of 'bins'. Then 'floor' the result to go to the left-hand edge of that bin, add 0.5 to go to the middle of the bin, multiply by the width so that you're no longer working in units of bins but in an absolute scale again, then finally add back on the Min offset you subtracted at the start.

Consider this function in action:

Min = 0.25 # where binning starts
Max = 2.25 # where binning ends
n = 2 # the number of bins
width = (Max-Min)/n # binwidth; evaluates to 1.0
bin(x) = width*(floor((x-Min)/width)+0.5) + Min

e.g. the value 1.1 truly falls in the left bin:

  • this function correctly maps it to the centre of the left bin (0.75);
  • Born2Smile's answer, bin(x)=width*floor(x/width), incorrectly maps it to 1;
  • mas90's answer, bin(x)=width*floor(x/width) + binwidth/2.0, incorrectly maps it to 1.5.

Born2Smile's answer is only correct if the bin boundaries occur at (n+0.5)*binwidth (where n runs over integers). mas90's answer is only correct if the bin boundaries occur at n*binwidth.

VBA: How to display an error message just like the standard error message which has a "Debug" button?

First the good news. This code does what you want (please note the "line numbers")

Sub a()
 10:    On Error GoTo ErrorHandler
 20:    DivisionByZero = 1 / 0
 30:    Exit Sub
 ErrorHandler:
 41: If Err.Number <> 0 Then
 42:    Msg = "Error # " & Str(Err.Number) & " was generated by " _
         & Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
 43:    MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
 44:    End If
 50:    Resume Next
 60: End Sub

When it runs, the expected MsgBox is shown:

alt text

And now the bad news:
Line numbers are a residue of old versions of Basic. The programming environment usually took charge of inserting and updating them. In VBA and other "modern" versions, this functionality is lost.

However, Here there are several alternatives for "automatically" add line numbers, saving you the tedious task of typing them ... but all of them seem more or less cumbersome ... or commercial.

HTH!

How to change the cursor into a hand when a user hovers over a list item?

All of the other responses suggest using the standard CSS pointer, however, there are two methods:

  1. Apply the CSS property cursor:pointer; to the elements. (This is the default style when a cursor hovers over a button.)

  2. Apply the CSS property cursor:url(pointer.png); using a custom graphic for your pointer. This may be more desirable if you want to ensure that the user experience is identical on all platforms (instead of allowing the browser/OS decide what your pointer cursor should look like). Note that fallback options may be added in case the image is not found, including secondary urls or any of the other options i.e. cursor:url(pointer.png,fallback.png,pointer);

Of course these may be applied to the list items in this manner li{cursor:pointer;}, as a class .class{cursor:pointer;}, or as a value for the style attribute of each element style="cursor:pointer;".

How can I invert color using CSS?

Add the same color of the background to the paragraph and then invert with CSS:

_x000D_
_x000D_
div {_x000D_
    background-color: #f00;_x000D_
}_x000D_
_x000D_
p { _x000D_
    color: #f00;_x000D_
    -webkit-filter: invert(100%);_x000D_
    filter: invert(100%);_x000D_
}
_x000D_
<div>_x000D_
    <p>inverted color</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

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

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

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

To get the entire path:

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

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

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

cout is not a member of std

I had a similar issue and it turned out that i had to add an extra entry in cmake to include the files.

Since i was also using the zmq library I had to add this to the included libraries as well.

When to use AtomicReference in Java?

Here is a use case for AtomicReference:

Consider this class that acts as a number range, and uses individual AtmomicInteger variables to maintain lower and upper number bounds.

public class NumberRange {
    // INVARIANT: lower <= upper
    private final AtomicInteger lower = new AtomicInteger(0);
    private final AtomicInteger upper = new AtomicInteger(0);

    public void setLower(int i) {
        // Warning -- unsafe check-then-act
        if (i > upper.get())
            throw new IllegalArgumentException(
                    "can't set lower to " + i + " > upper");
        lower.set(i);
    }

    public void setUpper(int i) {
        // Warning -- unsafe check-then-act
        if (i < lower.get())
            throw new IllegalArgumentException(
                    "can't set upper to " + i + " < lower");
        upper.set(i);
    }

    public boolean isInRange(int i) {
        return (i >= lower.get() && i <= upper.get());
    }
}

Both setLower and setUpper are check-then-act sequences, but they do not use sufficient locking to make them atomic. If the number range holds (0, 10), and one thread calls setLower(5) while another thread calls setUpper(4), with some unlucky timing both will pass the checks in the setters and both modifications will be applied. The result is that the range now holds (5, 4)an invalid state. So while the underlying AtomicIntegers are thread-safe, the composite class is not. This can be fixed by using a AtomicReference instead of using individual AtomicIntegers for upper and lower bounds.

public class CasNumberRange {
    // Immutable
    private static class IntPair {
        final int lower;  // Invariant: lower <= upper
        final int upper;

        private IntPair(int lower, int upper) {
            this.lower = lower;
            this.upper = upper;
        }
    }

    private final AtomicReference<IntPair> values = 
            new AtomicReference<IntPair>(new IntPair(0, 0));

    public int getLower() {
        return values.get().lower;
    }

    public void setLower(int lower) {
        while (true) {
            IntPair oldv = values.get();
            if (lower > oldv.upper)
                throw new IllegalArgumentException(
                    "Can't set lower to " + lower + " > upper");
            IntPair newv = new IntPair(lower, oldv.upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }

    public int getUpper() {
        return values.get().upper;
    }

    public void setUpper(int upper) {
        while (true) {
            IntPair oldv = values.get();
            if (upper < oldv.lower)
                throw new IllegalArgumentException(
                    "Can't set upper to " + upper + " < lower");
            IntPair newv = new IntPair(oldv.lower, upper);
            if (values.compareAndSet(oldv, newv))
                return;
        }
    }
}

Creating a PHP header/footer

Just create the header.php file, and where you want to use it do:

<?php
include('header.php');
?>

Same with the footer. You don't need php tags in these files if you just have html.

See more about include here:

http://php.net/manual/en/function.include.php

How do I install the yaml package for Python?

There are three YAML capable packages. Syck (pip install syck) which implements the YAML 1.0 specification from 2002; PyYAML (pip install pyyaml) which follows the YAML 1.1 specification from 2004; and ruamel.yaml which follows the latest (YAML 1.2, from 2009) specification.

You can install the YAML 1.2 compatible package with pip install ruamel.yaml or if you are running a modern version of Debian/Ubuntu (or derivative) with:

sudo apt-get install python-ruamel.yaml

Android saving file to external storage

Click Here for full description and source code

public void saveImage(Context mContext, Bitmap bitmapImage) {

  File sampleDir = new File(Environment.getExternalStorageDirectory() + "/" + "ApplicationName");

  TextView tvImageLocation = (TextView) findViewById(R.id.tvImageLocation);
  tvImageLocation.setText("Image Store At : " + sampleDir);

  if (!sampleDir.exists()) {
      createpathForImage(mContext, bitmapImage, sampleDir);
  } else {
      createpathForImage(mContext, bitmapImage, sampleDir);
  }
}

Errno 13 Permission denied Python

Your user don't have the right permissions to read the file, since you used open() without specifying a mode.

Since you're using Windows, you should read a little more about File and Folder Permissions.

Also, if you want to play with your file permissions, you should right-click it, choose Properties and select Security tab.

Or if you want to be a little more hardcore, you can run your script as admin.

SO Related Questions:

C# Form.Close vs Form.Dispose

Using usingis a pretty good way:

using (MyForm foo = new MyForm())
{
    if (foo.ShowDialog() == DialogResult.OK)
    {
        // your code
    }
}

How to select a dropdown value in Selenium WebDriver using Java

I have not tried in Selenium, but for Galen test this is working,

var list = driver.findElementByID("periodID"); // this will return web element

list.click(); // this will open the dropdown list.

list.typeText("14w"); // this will select option "14w".

You can try this in selenium, the galen and selenium working are similar.

no debugging symbols found when using gdb

Replace -ggdb with -g and make sure you aren't stripping the binary with the strip command.

How to convert a private key to an RSA private key?

To Convert BEGIN OPENSSH PRIVATE KEY to BEGIN RSA PRIVATE KEY:

ssh-keygen -p -m PEM -f ~/.ssh/id_rsa

SQL statement to select all rows from previous day

subdate(now(),1) will return yesterdays timestamp The below code will select all rows with yesterday's timestamp

Select * FROM `login` WHERE `dattime` <= subdate(now(),1) AND `dattime` > subdate(now(),2)

How do I change the android actionbar title and icon

Go to manifest in which specific activity you want to change Action bar Title name and write android:label="Title name"

Convert unix time to readable date in pandas dataframe

These appear to be seconds since epoch.

In [20]: df = DataFrame(data['values'])

In [21]: df.columns = ["date","price"]

In [22]: df
Out[22]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 358 entries, 0 to 357
Data columns (total 2 columns):
date     358  non-null values
price    358  non-null values
dtypes: float64(1), int64(1)

In [23]: df.head()
Out[23]: 
         date  price
0  1349720105  12.08
1  1349806505  12.35
2  1349892905  12.15
3  1349979305  12.19
4  1350065705  12.15
In [25]: df['date'] = pd.to_datetime(df['date'],unit='s')

In [26]: df.head()
Out[26]: 
                 date  price
0 2012-10-08 18:15:05  12.08
1 2012-10-09 18:15:05  12.35
2 2012-10-10 18:15:05  12.15
3 2012-10-11 18:15:05  12.19
4 2012-10-12 18:15:05  12.15

In [27]: df.dtypes
Out[27]: 
date     datetime64[ns]
price           float64
dtype: object

How to git reset --hard a subdirectory?

If the size of the subdirectory is not particularly huge, AND you wish to stay away from the CLI, here's a quick solution to manually reset the sub-directory:

  1. Switch to master branch and copy the sub-directory to be reset.
  2. Now switch back to your feature branch and replace the sub-directory with the copy you just created in step 1.
  3. Commit the changes.

Cheers. You just manually reset a sub-directory in your feature branch to be same as that of master branch !!

How do I make a file:// hyperlink that works in both IE and Firefox?

Paste following link to directly under link button click event, otherwise use javascript to call code behind function

Protected Sub lnkOpen_Click(ByVal sender As Object, ByVal e As EventArgs) 
    System.Diagnostics.Process.Start(FilePath)
End Sub

Numpy first occurrence of value greater than existing value

given the sorted content of your array, there is an even faster method: searchsorted.

import time
N = 10000
aa = np.arange(-N,N)
%timeit np.searchsorted(aa, N/2)+1
%timeit np.argmax(aa>N/2)
%timeit np.where(aa>N/2)[0][0]
%timeit np.nonzero(aa>N/2)[0][0]

# Output
100000 loops, best of 3: 5.97 µs per loop
10000 loops, best of 3: 46.3 µs per loop
10000 loops, best of 3: 154 µs per loop
10000 loops, best of 3: 154 µs per loop

Where is the documentation for the values() method of Enum?

The method is implicitly defined (i.e. generated by the compiler).

From the JLS:

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**
* Returns an array containing the constants of this enum 
* type, in the order they're declared.  This method may be
* used to iterate over the constants as follows:
*
*    for(E c : E.values())
*        System.out.println(c);
*
* @return an array containing the constants of this enum 
* type, in the order they're declared
*/
public static E[] values();

/**
* Returns the enum constant of this type with the specified
* name.
* The string must match exactly an identifier used to declare
* an enum constant in this type.  (Extraneous whitespace 
* characters are not permitted.)
* 
* @return the enum constant with the specified name
* @throws IllegalArgumentException if this enum type has no
* constant with the specified name
*/
public static E valueOf(String name);

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

Nothing else was working for me. This one did. This might help someone.

<div class="clearfix">
  <span class="float-left">Float left</span>
  <span class="float-right">Float right</span>
</div>

Wrapping everything in clearfix div is the key.

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

What's the use of ob_start() in php?

I use this so I can break out of PHP with a lot of HTML but not render it. It saves me from storing it as a string which disables IDE color-coding.

<?php
ob_start();
?>
<div>
    <span>text</span>
    <a href="#">link</a>
</div>
<?php
$content = ob_get_clean();
?>

Instead of:

<?php
$content = '<div>
    <span>text</span>
    <a href="#">link</a>
</div>';
?>

phpMyAdmin on MySQL 8.0

Another idea: as long as the phpmyadmin and other php tools don't work with it, just add this line to your file /etc/mysql/my.cnf

default_authentication_plugin = mysql_native_password

See also: Mysql Ref

I know that this is a security issue, but what to do if the tools don't work with caching_sha2_password?

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

change type of input field with jQuery

Type properties can't be changed you need to replace or overlay the input with a text input and send the value to the password input on submit.

jQuery or JavaScript auto click

You haven't provided your javascript code, but the usual cause of this type of issue is not waiting till the page is loaded. Remember that most javascript is executed before the DOM is loaded, so code trying to manipulate it won't work.

To run code after the page has finished loading, use the $(document).ready callback:

$(document).ready(function(){
  $('#some-id').trigger('click');
});

Get top first record from duplicate records having no unique identity

YOur best bet is to fix the datbase design and add the identioty column to the table. Why do you havea table without one in the first place? Especially one with duplicate records! Clearly the database itself needs redesigning.

And why do you have to have this in a view, why isn't your solution with the temp table a valid solution? Views are not usually a really good thing to do to a perfectly nice database.

Maximum number of threads in a .NET app?

I would recommend running ThreadPool.GetMaxThreads method in debug

ThreadPool.GetMaxThreads(out int workerThreadsCount, out int ioThreadsCount);

Docs and examples: https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadpool.getmaxthreads?view=netframework-4.8

ImageView in circular through xml

If you use Material Design in your app then use this

<com.google.android.material.card.MaterialCardView
            android:layout_width="75dp"
            android:layout_height="75dp"
            app:cardCornerRadius="50dp"
            app:strokeWidth="1dp"
            app:strokeColor="@color/black">
            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:id="@+id/circular_image"
                android:scaleType="fitCenter"
                android:src="@drawable/your_img" />
        </com.google.android.material.card.MaterialCardView>

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

Had the same problem, solved it by getting the appropriate webdriver from: https://chromedriver.chromium.org/downloads

You can know the exact version of your chrome browser by entering the link:

chrome://settings/help

How to call a parent method from child class in javascript?

Well in order to do this, you are not limited with the Class abstraction of ES6. Accessing the parent constructor's prototype methods is possible through the __proto__ property (I am pretty sure there will be fellow JS coders to complain that it's depreciated) which is depreciated but at the same time discovered that it is actually an essential tool for sub-classing needs (especially for the Array sub-classing needs though). So while the __proto__ property is still available in all major JS engines that i know, ES6 introduced the Object.getPrototypeOf() functionality on top of it. The super() tool in the Class abstraction is a syntactical sugar of this.

So in case you don't have access to the parent constructor's name and don't want to use the Class abstraction you may still do as follows;

function ChildObject(name) {
    // call the parent's constructor
    ParentObject.call(this, name);
    this.myMethod = function(arg) {
    //this.__proto__.__proto__.myMethod.call(this,arg);
    Object.getPrototypeOf(Object.getPrototypeOf(this)).myMethod.call(this,arg);
    }
}

making a paragraph in html contain a text from a file

You'll want to use either JavaScript or a server-side language like PHP, ASP...etc

(supposedly can be done with HTML <embed> tag, which makes sense, but I haven't used, since PHP...etc is so simple/common)

Javascript can work: Here's a link to someone doing something similar via javascript on stackoverflow: How do I load the contents of a text file into a javascript variable?

PHP (as example of server-side language) is the easiest way to go though:

<div><p><?php include('myFile.txt'); ?></p></div>

To use this (if you're unfamiliar with PHP), you can:

1) check if you have php on your server

2) change the file extension of your .html file to .php

3) paste the code from my PHP example somewhere in the body of your newly-renamed PHP file

Computational complexity of Fibonacci Sequence

The proof answers are good, but I always have to do a few iterations by hand to really convince myself. So I drew out a small calling tree on my whiteboard, and started counting the nodes. I split my counts out into total nodes, leaf nodes, and interior nodes. Here's what I got:

IN | OUT | TOT | LEAF | INT
 1 |   1 |   1 |   1  |   0
 2 |   1 |   1 |   1  |   0
 3 |   2 |   3 |   2  |   1
 4 |   3 |   5 |   3  |   2
 5 |   5 |   9 |   5  |   4
 6 |   8 |  15 |   8  |   7
 7 |  13 |  25 |  13  |  12
 8 |  21 |  41 |  21  |  20
 9 |  34 |  67 |  34  |  33
10 |  55 | 109 |  55  |  54

What immediately leaps out is that the number of leaf nodes is fib(n). What took a few more iterations to notice is that the number of interior nodes is fib(n) - 1. Therefore the total number of nodes is 2 * fib(n) - 1.

Since you drop the coefficients when classifying computational complexity, the final answer is ?(fib(n)).

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

Here's a javascript implementation that works with web-kit:

var isHovering = false;

var el = $(".elem").mouseover(function(){
    isHovering = true;
    spin();
}).mouseout(function(){
    isHovering = false;
});

var spin = function(){
    if(isHovering){
        el.removeClass("spin");

        setTimeout(function(){
            el.addClass("spin");

            setTimeout(spin, 1500);
        }, 0);
    }
};
spin();

JSFiddle: http://jsfiddle.net/4Vz63/161/

Barf.

How to disable JavaScript in Chrome Developer Tools?

The quickest way is problably this one:

  • F12 to open the dev console
  • ctrl + shift + p to open the command tool (windows)
  • Type 'disable javascript' and hit enter

What is difference between Errors and Exceptions?

An Error "indicates serious problems that a reasonable application should not try to catch."

while

An Exception "indicates conditions that a reasonable application might want to catch."

Error along with RuntimeException & their subclasses are unchecked exceptions. All other Exception classes are checked exceptions.

Checked exceptions are generally those from which a program can recover & it might be a good idea to recover from such exceptions programmatically. Examples include FileNotFoundException, ParseException, etc. A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller

On the other hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException, ClassCastException, etc. Many applications will use try-catch or throws clause for RuntimeExceptions & their subclasses but from the language perspective it is not required to do so. Do note that recovery from a RuntimeException is generally possible but the guys who designed the class/exception deemed it unnecessary for the end programmer to check for such exceptions.

Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError, StackOverflowError, etc.

Do note that although Errors are unchecked exceptions, we shouldn't try to deal with them, but it is ok to deal with RuntimeExceptions(also unchecked exceptions) in code. Checked exceptions should be handled by the code.

How do I check that multiple keys are in a dict in a single pass?

In the case of determining whether only some keys match, this works:

any_keys_i_seek = ["key1", "key2", "key3"]

if set(my_dict).intersection(any_keys_i_seek):
    # code_here
    pass

Yet another option to find if only some keys match:

any_keys_i_seek = ["key1", "key2", "key3"]

if any_keys_i_seek & my_dict.keys():
    # code_here
    pass

Can a local variable's memory be accessed outside its scope?

You never throw a C++ exception by accessing invalid memory. You are just giving an example of the general idea of referencing an arbitrary memory location. I could do the same like this:

unsigned int q = 123456;

*(double*)(q) = 1.2;

Here I am simply treating 123456 as the address of a double and write to it. Any number of things could happen:

  1. q might in fact genuinely be a valid address of a double, e.g. double p; q = &p;.
  2. q might point somewhere inside allocated memory and I just overwrite 8 bytes in there.
  3. q points outside allocated memory and the operating system's memory manager sends a segmentation fault signal to my program, causing the runtime to terminate it.
  4. You win the lottery.

The way you set it up it is a bit more reasonable that the returned address points into a valid area of memory, as it will probably just be a little further down the stack, but it is still an invalid location that you cannot access in a deterministic fashion.

Nobody will automatically check the semantic validity of memory addresses like that for you during normal program execution. However, a memory debugger such as valgrind will happily do this, so you should run your program through it and witness the errors.

How to upgrade all Python packages with pip

This seems more concise.

pip list --outdated | cut -d ' ' -f1 | xargs -n1 pip install -U

Explanation:

pip list --outdated gets lines like these

urllib3 (1.7.1) - Latest: 1.15.1 [wheel]
wheel (0.24.0) - Latest: 0.29.0 [wheel]

In cut -d ' ' -f1, -d ' ' sets "space" as the delimiter, -f1 means to get the first column.

So the above lines becomes:

urllib3
wheel

then pass them to xargs to run the command, pip install -U, with each line as appending arguments

-n1 limits the number of arguments passed to each command pip install -U to be 1

CASE statement in SQLite query

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

or

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

Check out the documentation (The CASE expression):

http://www.sqlite.org/lang_expr.html

How to convert minutes to Hours and minutes (hh:mm) in java

Try this code:

import java.util.Scanner;

public class BasicElement {
    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        int hours;
        System.out.print("Enter the hours to convert:");
        hours =input.nextInt();
        int d=hours/24;
        int m=hours%24;
        System.out.println(d+"days"+" "+m+"hours");     

    }
}

how to get a list of dates between two dates in java

Recommending date streams

In Java 9, you can use following new method, LocalDate::datesUntil:

LocalDate start = LocalDate.of(2017, 2, 1);
LocalDate end = LocalDate.of(2017, 2, 28);

Stream<LocalDate> dates = start.datesUntil(end.plusDays(1));
List<LocalDate> list = dates.collect(Collectors.toList());

The new method datesUntil(...) works with an exclusive end date, hence the shown hack to add a day.

Once you have obtained a stream you can exploit all the features offered by java.util.stream- or java.util.function-packages. Working with streams has become so simple compared with earlier approaches based on customized for- or while-loops.


Or if you look for a stream-based solution which operates on inclusive dates by default but can also be configured otherwise then you might find the class DateInterval in my library Time4J interesting because it offers a lot of special features around date streams including a performant spliterator which is faster than in Java-9:

PlainDate start = PlainDate.of(2017,  2, 1);
PlainDate end = start.with(PlainDate.DAY_OF_MONTH.maximized());
Stream<PlainDate> stream = DateInterval.streamDaily(start, end);

Or even simpler in case of full months:

Stream<PlainDate> februaryDates = CalendarMonth.of(2017, 2).streamDaily();
List<LocalDate> list = 
    februaryDates.map(PlainDate::toTemporalAccessor).collect(Collectors.toList());

How to make a list of n numbers in Python and randomly select any number?

You can try this code

import random
N = 5
count_list = range(1,N+1)
random.shuffle(count_list)

while count_list:
    value = count_list.pop()
    # do whatever you want with 'value'

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

How about using Postgres built-in array functions? At least on 8.4 this works out of the box:

SELECT company_id, array_to_string(array_agg(employee), ',')
FROM mytable
GROUP BY company_id;

How do I login and authenticate to Postgresql after a fresh install?

The error your are getting is because your-ubuntu-username is not a valid Postgres user.

You need to tell psql what database username to use

psql -U postgres

You may also need to specify the database to connect to

psql -U postgres -d <dbname>

How to extract Month from date in R

you can convert it into date format by-

new_date<- as.Date(old_date, "%m/%d/%Y")} 

from new_date, you can get the month by strftime()

month<- strftime(new_date, "%m")

old_date<- "01/01/1979"
new_date<- as.Date(old_date, "%m/%d/%Y")
new_date
#[1] "1979-01-01"
month<- strftime(new_date,"%m")
month
#[1] "01"
year<- strftime(new_date, "%Y")
year
#[1] "1979"

How can I generate a 6 digit unique number?

Try this using uniqid and hexdec,

echo hexdec(uniqid());

Java: how to represent graphs?

Even at the time of this question, over 3 years ago, Sage (which is completely free) existed and was pretty good at graph theory. But, in 2012 it is about the best graph theory tool there is. Thus, Sage already has a huge amount of graph theory material built in, including other free and open source stuff that is out there. So, simply messing around with various things to learn more is easy as no programming is required.

And, if you are interested in the programming part as well, first Sage is open source so you can see any code that already exists. And, second, you can re-program any function you want if you really want to practice, or you can be the first to program something that does not already exist. In the latter case, you can even submit that new functionality and make Sage better for all other users.

At this time, this answer may not be that useful to the OP (since it has been 3 years), but hopefully it is useful to any one else who sees this question in the future.

How do I do word Stemming or Lemmatization?

The most current version of the stemmer in NLTK is Snowball.

You can find examples on how to use it here:

http://nltk.googlecode.com/svn/trunk/doc/api/nltk.stem.snowball2-pysrc.html#demo

What is the current directory in a batch file?

Say you were opening a file in your current directory. The command would be:

 start %cd%\filename.filetype

I hope I answered your question.

MySQL INNER JOIN select only one row from second table

There are two problems with your query:

  1. Every table and subquery needs a name, so you have to name the subquery INNER JOIN (SELECT ...) AS p ON ....
  2. The subquery as you have it only returns one row period, but you actually want one row for each user. For that you need one query to get the max date and then self-join back to get the whole row.

Assuming there are no ties for payments.date, try:

    SELECT u.*, p.* 
    FROM (
        SELECT MAX(p.date) AS date, p.user_id 
        FROM payments AS p
        GROUP BY p.user_id
    ) AS latestP
    INNER JOIN users AS u ON latestP.user_id = u.id
    INNER JOIN payments AS p ON p.user_id = u.id AND p.date = latestP.date
    WHERE u.package = 1

Wampserver icon not going green fully, mysql services not starting up?

I've got a very similar problem, after a lot trying even the solutions in this question I concluded with THIS OTHER ANSWER.

I didn't replicated it here because it is NOT A CORRECT THING TO DO.

Basically is about re-installing MySQL (or the entire package) being sure to delete very well the old my-sql-data very well (back it up if you might need it) and stick on using 32 bit versions.

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

How to view the current heap size that an application is using?

Personal favourite for when jvisualvm is overkill or you need cli-only: jvmtop

JvmTop 0.8.0 alpha   amd64  8 cpus, Linux 2.6.32-27, load avg 0.12
https://github.com/patric-r/jvmtop

PID MAIN-CLASS      HPCUR HPMAX NHCUR NHMAX    CPU     GC    VM USERNAME   #T DL
3370 rapperSimpleApp  165m  455m  109m  176m  0.12%  0.00% S6U37 web        21
11272 ver.resin.Resin [ERROR: Could not attach to VM]
27338 WatchdogManager   11m   28m   23m  130m  0.00%  0.00% S6U37 web        31
19187 m.jvmtop.JvmTop   20m 3544m   13m  130m  0.93%  0.47% S6U37 web        20
16733 artup.Bootstrap  159m  455m  166m  304m  0.12%  0.00% S6U37 web        46

How SID is different from Service name in Oracle tnsnames.ora

what is a SID and Service name

please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm

In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)"

When I have to use one or another? Why do I need two of them?

Consider below mapping in a RAC Environment,

SID      SERVICE_NAME
bob1    bob
bob2    bob
bob3    bob
bob4    bob

if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME.

Please refer, https://community.oracle.com/thread/4049517

Calculate execution time of a SQL query?

I found this one more helpful and simple

DECLARE @StartTime datetime,@EndTime datetime   
SELECT @StartTime=GETDATE() 
--Your Query to be run goes here--  
SELECT @EndTime=GETDATE()   
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in milliseconds]   

Java - Check Not Null/Empty else assign default value

In Java 9, if you have an object which has another object as property and that nested objects has a method yielding a string, then you can use this construct to return an empty string if the embeded object is null :

String label = Optional.ofNullable(org.getDiffusion()).map(Diffusion::getLabel).orElse("")

In this example :

  • org is an instance of an object of type Organism
  • Organism has a Diffusion property (another object)
  • Diffusion has a String label property (and getLabel() getter).

With this example, if org.getDiffusion() is not null, then it returns the getLabel property of its Diffusion object (this returns a String). Otherwise, it returns an empty string.

Check if a PHP cookie exists and if not set its value

Answer

You can't according to the PHP manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

Work around

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {
    setcookie('lg', 'ro');
    $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];

Set variable with multiple values and use IN

Ideally you shouldn't be splitting strings in T-SQL at all.

Barring that change, on older versions before SQL Server 2016, create a split function:

CREATE FUNCTION dbo.SplitStrings
(
    @List      nvarchar(max), 
    @Delimiter nvarchar(2)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
  RETURN ( WITH x(x) AS
    (
      SELECT CONVERT(xml, N'<root><i>' 
        + REPLACE(@List, @Delimiter, N'</i><i>') 
        + N'</i></root>')
    )
    SELECT Item = LTRIM(RTRIM(i.i.value(N'.',N'nvarchar(max)')))
      FROM x CROSS APPLY x.nodes(N'//root/i') AS i(i)
  );
GO

Now you can say:

DECLARE @Values varchar(1000);

SET @Values = 'A, B, C';

SELECT blah
  FROM dbo.foo
  INNER JOIN dbo.SplitStrings(@Values, ',') AS s
    ON s.Item = foo.myField;

On SQL Server 2016 or above (or Azure SQL Database), it is much simpler and more efficient, however you do have to manually apply LTRIM() to take away any leading spaces:

DECLARE @Values varchar(1000) = 'A, B, C';

SELECT blah
  FROM dbo.foo
  INNER JOIN STRING_SPLIT(@Values, ',') AS s
    ON LTRIM(s.value) = foo.myField;

jQuery UI Tabs - How to Get Currently Selected Tab Index

In case anybody has tried to access tabs from within an iframe, you may notice it's not possible. The div of the tab never gets marked as selected, just as hidden or not hidden. The link itself is the only piece marked as selected.

<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-focus"><a href="#tabs-4">Tab 5</a></li>

The following will get you the href value of the link which should be the same as the id for your tab container:

jQuery('.ui-tabs-selected a',window.parent.document).attr('href')

This should also work in place of: $tabs.tabs('option', 'selected');

It's better in the sense that instead of just getting the index of the tab, it gives you the actual id of the tab.

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

Install gcc.

If you're on linux, use the package manager.

If you're on Windows, use MinGW.

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

Okay, the .NET 2.0 answers:

If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.)

If you do need to clone the values, you can use something like this:

public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>
   (Dictionary<TKey, TValue> original) where TValue : ICloneable
{
    Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,
                                                            original.Comparer);
    foreach (KeyValuePair<TKey, TValue> entry in original)
    {
        ret.Add(entry.Key, (TValue) entry.Value.Clone());
    }
    return ret;
}

That relies on TValue.Clone() being a suitably deep clone as well, of course.

Factorial in numpy and scipy

    from numpy import prod

    def factorial(n):
        print prod(range(1,n+1))

or with mul from operator:

    from operator import mul

    def factorial(n):
        print reduce(mul,range(1,n+1))

or completely without help:

    def factorial(n):
        print reduce((lambda x,y: x*y),range(1,n+1))

Declaring variable workbook / Worksheet vba

If the worksheet you want to retrieve exists at compile-time in ThisWorkbook (i.e. the workbook that contains the VBA code you're looking at), then the simplest and most consistently reliable way to refer to that Worksheet object is to use its code name:

Debug.Print Sheet1.Range("A1").Value

You can set the code name to anything you need (as long as it's a valid VBA identifier), independently of its "tab name" (which the user can modify at any time), by changing the (Name) property in the Properties toolwindow (F4):

Sheet1 properties

The Name property refers to the "tab name" that the user can change on a whim; the (Name) property refers to the code name of the worksheet, and the user can't change it without accessing the Visual Basic Editor.

VBA uses this code name to automatically declare a global-scope Worksheet object variable that your code gets to use anywhere to refer to that sheet, for free.

In other words, if the sheet exists in ThisWorkbook at compile-time, there's never a need to declare a variable for it - the variable is already there!


If the worksheet is created at run-time (inside ThisWorkbook or not), then you need to declare & assign a Worksheet variable for it.

Use the Worksheets property of a Workbook object to retrieve it:

Dim wb As Workbook
Set wb = Application.Workbooks.Open(path)

Dim ws As Worksheet
Set ws = wb.Worksheets(nameOrIndex)

Important notes...

  • Both the name and index of a worksheet can easily be modified by the user (accidentally or not), unless workbook structure is protected. If workbook isn't protected, you simply cannot assume that the name or index alone will give you the specific worksheet you're after - it's always a good idea to validate the format of the sheet (e.g. verify that cell A1 contains some specific text, or that there's a table with a specific name, that contains some specific column headings).

  • Using the Sheets collection contains Worksheet objects, but can also contain Chart instances, and a half-dozen more legacy sheet types that are not worksheets. Assigning a Worksheet reference from whatever Sheets(nameOrIndex) returns, risks throwing a type mismatch run-time error for that reason.

  • Not qualifying the Worksheets collection is an implicit ActiveWorkbook reference - meaning the Worksheets collection is pulling from whatever workbook is active at the moment the instruction is executing. Such implicit references make the code frail and bug-prone, especially if the user can navigate and interact with the Excel UI while code is running.

  • Unless you mean to activate a specific sheet, you never need to call ws.Activate in order to do 99% of what you want to do with a worksheet. Just use your ws variable instead.

What is sharding and why is it important?

Sharding is just another name for "horizontal partitioning" of a database. You might want to search for that term to get it clearer.

From Wikipedia:

Horizontal partitioning is a design principle whereby rows of a database table are held separately, rather than splitting by columns (as for normalization). Each partition forms part of a shard, which may in turn be located on a separate database server or physical location. The advantage is the number of rows in each table is reduced (this reduces index size, thus improves search performance). If the sharding is based on some real-world aspect of the data (e.g. European customers vs. American customers) then it may be possible to infer the appropriate shard membership easily and automatically, and query only the relevant shard.

Some more information about sharding:

Firstly, each database server is identical, having the same table structure. Secondly, the data records are logically split up in a sharded database. Unlike the partitioned database, each complete data record exists in only one shard (unless there's mirroring for backup/redundancy) with all CRUD operations performed just in that database. You may not like the terminology used, but this does represent a different way of organizing a logical database into smaller parts.

Update: You wont break MVC. The work of determining the correct shard where to store the data would be transparently done by your data access layer. There you would have to determine the correct shard based on the criteria which you used to shard your database. (As you have to manually shard the database into some different shards based on some concrete aspects of your application.) Then you have to take care when loading and storing the data from/into the database to use the correct shard.

Maybe this example with Java code makes it somewhat clearer (it's about the Hibernate Shards project), how this would work in a real world scenario.

To address the "why sharding": It's mainly only for very large scale applications, with lots of data. First, it helps minimizing response times for database queries. Second, you can use more cheaper, "lower-end" machines to host your data on, instead of one big server, which might not suffice anymore.

How to delete object from array inside foreach loop?

I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

Below format try if number is like

ex 1 suppose number like 10.1 if apply below format it will be come as 10.10

ex 2 suppose number like .02 if apply below format it will be come as 0.02

ex 3 suppose number like 0.2 if apply below format it will be come as 0.20

to_char(round(to_number(column_name)/10000000,2),'999999999990D99') as column_name

How do I use hexadecimal color strings in Flutter?

String hexString = "45a3df";
Color(int.parse("0xff${hexString}"));

Don't know why this is being downed, this was the solution for me.
Only way that didn't require additional steps

CSS table-cell equal width

HTML

<div class="table">
    <div class="table_cell">Cell-1</div>
    <div class="table_cell">Cell-2 Cell-2 Cell-2 Cell-2Cell-2 Cell-2</div>
    <div class="table_cell">Cell-3Cell-3 Cell-3Cell-3 Cell-3Cell-3</div>
    <div class="table_cell">Cell-4Cell-4Cell-4 Cell-4Cell-4Cell-4 Cell-4Cell-4Cell-4Cell-4</div>
</div>?

CSS

.table{
    display:table;
    width:100%;
    table-layout:fixed;
}
.table_cell{
    display:table-cell;
    width:100px;
    border:solid black 1px;
}

DEMO.

Animate change of view background color on Android

If you want color animation like this,

Enter image description here

this code will help you:

ValueAnimator anim = ValueAnimator.ofFloat(0, 1);   
anim.setDuration(2000);

float[] hsv;
int runColor;
int hue = 0;
hsv = new float[3]; // Transition color
hsv[1] = 1;
hsv[2] = 1;
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {

        hsv[0] = 360 * animation.getAnimatedFraction();

        runColor = Color.HSVToColor(hsv);
        yourView.setBackgroundColor(runColor);
    }
});

anim.setRepeatCount(Animation.INFINITE);

anim.start();

How do I center a Bootstrap div with a 'spanX' class?

Update

As of BS3 there's a .center-block helper class. From the docs:

// Classes
.center-block {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

// Usage as mixins
.element {
  .center-block();
}

There is hidden complexity in this seemingly simple problem. All the answers given have some issues.

1. Create a Custom Class (Major Gotcha)

Create .col-centred class, but there is a major gotcha.

.col-centred {
   float: none !important;
   margin: 0 auto;
}

<!-- Bootstrap 3 -->
<div class="col-lg-6 col-centred">
  Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 col-centred">
  Centred content.
</div>

The Gotcha

Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.

The Fixes

You can resolve this issue by using a clearfix element. Using z-index to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.

<div class="row">
  <div class="col-lg-12">
    I get overlapped by `col-lg-7 centered` unless there's a clearfix.
  </div>
  <div class="clearfix"></div>
  <div class="col-lg-7 centred">
  </div>
</div>

Or you can isolate the centred column in its own row.

<div class="row">
  <div class="col-lg-12">
  </div>
</div>
<div class="row">
  <div class="col-lg-7 centred">
    Look I am in my own row.
  </div>
</div>

2. Use col-lg-offset-x or spanx-offset (Major Gotcha)

<!-- Bootstrap 3 -->
<div class="col-lg-6 col-lg-offset-3">
  Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 span-offset-3">
  Centred content.
</div>

The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).

Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.

3. Create an Inner Centred Column

This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.

.col-centred {
   margin: 0 auto;
}

<div class="row">
  <div class="col-lg-12">
    <div class="centred">
        Look I am in my own row.
    </div>
  </div>
</div>

How to define custom exception class in Java, the easiest way?

Exception class has two constructors

  • public Exception() -- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.
  • public Exception(String s) -- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.

Convert array of integers to comma-separated string

int[] arr = new int[5] {1,2,3,4,5};

You can use Linq for it

String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);

How do I check if a C++ string is an int?

I have modified paercebal's method to meet my needs:

typedef std::string String;    

bool isInt(const String& s, int base){
   if(s.empty() || std::isspace(s[0])) return false ;
   char * p ;
   strtol(s.c_str(), &p, base) ;
   return (*p == 0) ;
}


bool isPositiveInt(const String& s, int base){
   if(s.empty() || std::isspace(s[0]) || s[0]=='-') return false ;
   char * p ;
   strtol(s.c_str(), &p, base) ;
   return (*p == 0) ;
}


bool isNegativeInt(const String& s, int base){
   if(s.empty() || std::isspace(s[0]) || s[0]!='-') return false ;
   char * p ;
   strtol(s.c_str(), &p, base) ;
   return (*p == 0) ;
}

Note:

  1. You can check for various bases (binary, oct, hex and others)
  2. Make sure you don't pass 1, negative value or value >36 as base.
  3. If you pass 0 as the base, it will auto detect the base i.e for a string starting with 0x will be treated as hex and string starting with 0 will be treated as oct. The characters are case-insensitive.
  4. Any white space in string will make it return false.

How to use timeit module

for me, this is the fastest way:

import timeit
def foo():
    print("here is my code to time...")


timeit.timeit(stmt=foo, number=1234567)

How to change cursor from pointer to finger using jQuery?

It is very straight forward

HTML

<input type="text" placeholder="some text" />
<input type="button" value="button" class="button"/>
<button class="button">Another button</button>

jQuery

$(document).ready(function(){
  $('.button').css( 'cursor', 'pointer' );

  // for old IE browsers
  $('.button').css( 'cursor', 'hand' ); 
});

Check it out on JSfiddle

How to use bootstrap-theme.css with bootstrap 3?

Bootstrap-theme.css is the additional CSS file, which is optional for you to use. It gives 3D effects on the buttons and some other elements.

How to stop event propagation with inline onclick attribute?

This worked for me

<script>
function cancelBubble(e) {
 var evt = e ? e:window.event;
 if (evt.stopPropagation)    evt.stopPropagation();
 if (evt.cancelBubble!=null) evt.cancelBubble = true;
}
</script>

<div onclick="alert('Click!')">
  <div onclick="cancelBubble(event)">Something inside the other div</div>
</div>

Regular expression to match exact number of characters?

Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:

^([A-Z]{3})$

The {3} indicates that the [A-Z] must appear exactly 3 times.

Javascript to check whether a checkbox is being checked or unchecked

function enter_comment(super_id) {
    if (!(document.getElementById(super_id).checked)) {
        alert('selected checkbox is unchecked now')
    } else {
        alert('selected checkbox is checked now');
    }
}

<input type="checkbox" name="a" id="1" value="1" onclick="enter_comment(this.value)" />

<input type="checkbox" name="b" id="2" value="2" onclick="enter_comment(this.value)" />

Should I use != or <> for not equal in T-SQL?

I preferred using != instead of <> because sometimes I use the <s></s> syntax to write SQL commands. Using != is more handy to avoid syntax errors in this case.

How to hide element label by element id in CSS?

Without a class or an id, and with your specific html:

table tr td label {display:none}

Otherwise if you have jQuery

$('label[for="foo"]').css('display', 'none');

How to select between brackets (or quotes or ...) in Vim?

For selecting within single quotes use vi'.

For selecting within parenthesis use vi(.

Javascript require() function giving ReferenceError: require is not defined

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

IE 6+ .......... compatible ?
Firefox 2+ ..... compatible ?
Safari 3.2+ .... compatible ?
Chrome 3+ ...... compatible ?
Opera 10+ ...... compatible ?

http://requirejs.org/docs/download.html

Add this to your project: https://requirejs.org/docs/release/2.3.5/minified/require.js

and take a look at this http://requirejs.org/docs/api.html

Changing the default title of confirm() in JavaScript?

I know this is not possible for alert(), so I guess it is not possible for confirm either. Reason is security: it is not allowed for you to change it so you wouldn't present yourself as some system process or something.

WiX tricks and tips

Keep all IDs in separate namespaces

  • Features begin with F. Examples: F.Documentation, F.Binaries, F.SampleCode.
  • Components begin with C. Ex: C.ChmFile, C.ReleaseNotes, C.LicenseFile, C.IniFile, C.Registry
  • CustomActions are CA. Ex: CA.LaunchHelp, CA.UpdateReadyDlg, CA.SetPropertyX
  • Files are Fi.
  • Directories are Di.
  • and so on.

I find this helps immensely in keeping track of all the various id's in all the various categories.

Renaming a branch in GitHub

Here is what worked for me:

  1. Create the new branch first:

    git push github newname :refs/heads/newname
    
  2. On the GitHub site, go to settings and change the Default branch to newname

  3. Delete the oldname

    git push github --delete oldname
    

How do I add space between items in an ASP.NET RadioButtonList

I know this is an old question but I did it like:

<asp:RadioButtonList runat="server" ID="myrbl" RepeatDirection="Horizontal" CssClass="rbl"> 

Use this as your class:

.rbl input[type="radio"]
{
   margin-left: 10px;
   margin-right: 1px;
}

SQL Server convert string to datetime

UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)

For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:

https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

How to upsert (update or insert) in SQL Server 2005

Try to check for existence:

IF NOT EXISTS (SELECT * FROM dbo.Employee WHERE ID = @SomeID)

    INSERT INTO dbo.Employee(Col1, ..., ColN)
    VALUES(Val1, .., ValN)

ELSE

    UPDATE dbo.Employee
    SET Col1 = Val1, Col2 = Val2, ...., ColN = ValN
    WHERE ID = @SomeID

You could easily wrap this into a stored procedure and just call that stored procedure from the outside (e.g. from a programming language like C# or whatever you're using).

Update: either you can just write this entire statement in one long string (doable - but not really very useful) - or you can wrap it into a stored procedure:

CREATE PROCEDURE dbo.InsertOrUpdateEmployee
       @ID INT,
       @Name VARCHAR(50),
       @ItemName VARCHAR(50),  
       @ItemCatName VARCHAR(50),
       @ItemQty DECIMAL(15,2)
AS BEGIN
    IF NOT EXISTS (SELECT * FROM dbo.Table1 WHERE ID = @ID)
       INSERT INTO dbo.Table1(ID, Name, ItemName, ItemCatName, ItemQty)
       VALUES(@ID, @Name, @ItemName, @ItemCatName, @ItemQty)
    ELSE
       UPDATE dbo.Table1
       SET Name = @Name,
           ItemName = @ItemName,
           ItemCatName = @ItemCatName,
           ItemQty = @ItemQty
       WHERE ID = @ID
END

and then just call that stored procedure from your ADO.NET code

Printing object properties in Powershell

# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName

npm - "Can't find Python executable "python", you can set the PYTHON env variable."

You got to add python to your PATH variable. One thing you can do is Edit your Path variable now and add

;%PYTHON%;

Your variable PYTHON should point to the root directory of your python installation.

Deleting multiple elements from a list

If you're deleting multiple non-adjacent items, then what you describe is the best way (and yes, be sure to start from the highest index).

If your items are adjacent, you can use the slice assignment syntax:

a[2:10] = []

Java program to get the current date without timestamp

You could use

// Format a string containing a date.
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;

Calendar c = GregorianCalendar.getInstance();
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"

Have a look at the Formatter API documentation.

Shell command to tar directory excluding certain files/folders

After reading all this good answers for different versions and having solved the problem for myself, I think there are very small details that are very important, and rare to GNU/Linux general use, that aren't stressed enough and deserves more than comments.

So I'm not going to try to answer the question for every case, but instead, try to register where to look when things doesn't work.

IT IS VERY IMPORTANT TO NOTICE:

  1. THE ORDER OF THE OPTIONS MATTER: it is not the same put the --exclude before than after the file option and directories to backup. This is unexpected at least to me, because in my experience, in GNU/Linux commands, usually the order of the options doesn't matter.
  2. Different tar versions expects this options in different order: for instance, @Andrew's answer indicates that in GNU tar v 1.26 and 1.28 the excludes comes last, whereas in my case, with GNU tar 1.29, it's the other way.
  3. THE TRAILING SLASHES MATTER: at least in GNU tar 1.29, it shouldn't be any.

In my case, for GNU tar 1.29 on Debian stretch, the command that worked was

tar --exclude="/home/user/.config/chromium" --exclude="/home/user/.cache" -cf file.tar  /dir1/ /home/ /dir3/

The quotes didn't matter, it worked with or without them.

I hope this will be useful to someone.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

You can try define in your LINQ expression only the field's that you will need.

Example. Imagine that you have an Model with Id, Name, Phone and Picture (byte array) and need to load from json into an select list.

LINQ Query:

var listItems = (from u in Users where u.name.Contains(term) select u).ToList();

The problem here is "select u" that get all fields. So, if you have big pictures, booomm.

How to solve? very, very simple.

var listItems = (from u in Users where u.name.Contains(term) select new {u.Id, u.Name}).ToList();

The best practices is select only the field that you will use.

Remember. This is a simple tip, but can help many ASP.NET MVC developpers.

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

Works for any number from 0 to 999999999.

This program gets a number from the user, divides it into three parts and stores them separately in an array. The three numbers are passed through a function that convert them into words. Then it adds "million" to the first part and "thousand" to the second part.

#include <iostream>
using namespace std;
int buffer = 0, partFunc[3] = {0, 0, 0}, part[3] = {0, 0, 0}, a, b, c, d;
long input, nFake = 0;
const char ones[][20] = {"",       "one",       "two",      "three",
                         "four",    "five",      "six",      "seven",
                         "eight",   "nine",      "ten",      "eleven",
                         "twelve",  "thirteen",  "fourteen", "fifteen",
                         "sixteen", "seventeen", "eighteen", "nineteen"};
const char tens[][20] = {"",     "ten",   "twenty",  "thirty", "forty",
                         "fifty", "sixty", "seventy", "eighty", "ninety"};
void convert(int funcVar);
int main() {
  cout << "Enter the number:";
  cin >> input;
  nFake = input;
  buffer = 0;
  while (nFake) {
    part[buffer] = nFake % 1000;
    nFake /= 1000;
    buffer++;
  }
  if (buffer == 0) {
    cout << "Zero.";
  } else if (buffer == 1) {
    convert(part[0]);
  } else if (buffer == 2) {
    convert(part[1]);
    cout << " thousand,";
    convert(part[0]);
  } else {
    convert(part[2]);
    cout << " million,";

    if (part[1]) {
      convert(part[1]);
      cout << " thousand,";
    } else {
      cout << "";
    }
    convert(part[0]);
  }
  system("pause");
  return (0);
}

void convert(int funcVar) {
  buffer = 0;
  if (funcVar >= 100) {
    a = funcVar / 100;
    b = funcVar % 100;
    if (b)
      cout << " " << ones[a] << " hundred and";
    else
      cout << " " << ones[a] << " hundred ";
    if (b < 20)
      cout << " " << ones[b];
    else {
      c = b / 10;
      cout << " " << tens[c];
      d = b % 10;
      cout << " " << ones[d];
    }
  } else {
    b = funcVar;
    if (b < 20)
      cout << ones[b];
    else {
      c = b / 10;
      cout << tens[c];
      d = b % 10;
      cout << " " << ones[d];
    }
  }
}

How to POST URL in data of a curl request

Perhaps you don't have to include the single quotes:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"

Update: Reading curl's manual, you could actually separate both fields with two --data:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"

You could also try --data-binary:

curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"

And --data-urlencode:

curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"

No line-break after a hyphen

Late to the party, but I think this is actually the most elegant. Use the WORD JOINER Unicode character &#8288; on either side of your hyphen, or em dash, or any character.

So, like so:

&#8288;—&#8288;

This will join the symbol on both ends to its neighbors (without adding a space) and prevent line breaking.

What causes a java.lang.StackOverflowError

What actually causes a java.lang.StackOverflowError is typically unintentional recursion. For me it's often when I intended to call a super method for the overidden method. Such as in this case:

public class Vehicle {
    public void accelerate(float acceleration, float maxVelocity) {
        // set the acceleration
    }
}

public class SpaceShip extends Vehicle {
    @Override
    public void accelerate(float acceleration, float maxVelocity) {
        // update the flux capacitor and call super.accelerate
        // oops meant to call super.accelerate(acceleration, maxVelocity);
        // but accidentally wrote this instead. A StackOverflow is in our future.
        this.accelerate(acceleration, maxVelocity); 
    }
}

First, it's useful to know what happens behind the scenes when we call a function. The arguments and the address of where the method was called is pushed on the stack (see http://en.wikipedia.org/wiki/Stack_(abstract_data_type)#Runtime_memory_management) so that the called method can access the arguments and so that when the called method is completed, execution can continue after the call. But since we are calling this.accelerate(acceleration, maxVelocity) recursively (recursion is loosely when a method calls itself. For more info see http://en.wikipedia.org/wiki/Recursion_(computer_science)) we are in a situation known as infinite recursion and we keep piling the arguments and return address on the call stack. Since the call stack is finite in size, we eventually run out of space. The running out of space on the call stack is known as overflow. This is because we are trying to use more stack space than we have and the data literally overflows the stack. In the Java programming language, this results in the runtime exception java.lang.StackOverflow and will immediately halt the program.

The above example is somewhat simplified (although it happens to me more than I'd like to admit.) The same thing can happen in a more round about way making it a bit harder to track down. However, in general, the StackOverflow is usually pretty easy to resolve, once it occurs.

In theory, it is also possible to have a stack overflow without recursion, but in practice, it would appear to be a fairly rare event.