Programs & Examples On #Pointers

Data type that "points to" another value stored in memory. A pointer variable contains a memory address of some other entity (variable or function or other entity). This tag should be used for questions involving the use of pointers, not references. The most common programming languages using pointers are C, C++, Go, and assembly languages. Use a specific language tag. Other helpful tags are method, function, struct, etc. describing the use of pointer.

Meaning of "referencing" and "dereferencing" in C

Referencing

& is the reference operator. It will refer the memory address to the pointer variable.

Example:

int *p;
int a=5;
p=&a; // Here Pointer variable p refers to the address of integer variable a.

Dereferencing

Dereference operator * is used by the pointer variable to directly access the value of the variable instead of its memory address.

Example:

int *p;
int a=5;
p=&a;
int value=*p; // Value variable will get the value of variable a that pointer variable p pointing to.

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

How does delete[] know it's an array?

delete or delete[] would probably both free the memory allocated (memory pointed), but the big difference is that delete on an array won't call the destructor of each element of the array.

Anyway, mixing new/new[] and delete/delete[] is probably UB.

What is a smart pointer and when should I use one?

A smart pointer is a class, a wrapper of a normal pointer. Unlike normal pointers, smart point’s life circle is based on a reference count (how many time the smart pointer object is assigned). So whenever a smart pointer is assigned to another one, the internal reference count plus plus. And whenever the object goes out of scope, the reference count minus minus.

Automatic pointer, though looks similar, is totally different from smart pointer. It is a convenient class that deallocates the resource whenever an automatic pointer object goes out of variable scope. To some extent, it makes a pointer (to dynamically allocated memory) works similar to a stack variable (statically allocated in compiling time).

C++ passing an array pointer as a function argument

This is another method . Passing array as a pointer to the function
void generateArray(int *array,  int size) {
    srand(time(0));
    for (int j=0;j<size;j++)
        array[j]=(0+rand()%9);
}

int main(){
    const int size=5;
    int a[size];
    generateArray(a, size);
    return 0;
}

How to assign pointer address manually in C programming language?

Your code would be like this:

int *p = (int *)0x28ff44;

int needs to be the type of the object that you are referencing or it can be void.

But be careful so that you don't try to access something that doesn't belong to your program.

How to find the 'sizeof' (a pointer pointing to an array)?

No, you can't use sizeof(ptr) to find the size of array ptr is pointing to.

Though allocating extra memory(more than the size of array) will be helpful if you want to store the length in extra space.

What is the difference between const int*, const int * const, and int const *?

Like pretty much everyone pointed out:

What’s the difference between const X* p, X* const p and const X* const p?

You have to read pointer declarations right-to-left.

  • const X* p means "p points to an X that is const": the X object can't be changed via p.

  • X* const p means "p is a const pointer to an X that is non-const": you can't change the pointer p itself, but you can change the X object via p.

  • const X* const p means "p is a const pointer to an X that is const": you can't change the pointer p itself, nor can you change the X object via p.

error: invalid type argument of ‘unary *’ (have ‘int’)

Since c is holding the address of an integer pointer, its type should be int**:

int **c;
c = &a;

The entire program becomes:

#include <stdio.h>                                                              
int main(){
    int b=10;
    int *a;
    a=&b;
    int **c;
    c=&a;
    printf("%d",(**c));   //successfully prints 10
    return 0;
}

malloc an array of struct pointers

IMHO, this looks better:

Chess *array = malloc(size * sizeof(Chess)); // array of pointers of size `size`

for ( int i =0; i < SOME_VALUE; ++i )
{
    array[i] = (Chess) malloc(sizeof(Chess));
}

What EXACTLY is meant by "de-referencing a NULL pointer"?

Dereferencing just means reading the memory value at a given address. So when you have a pointer to something, to dereference the pointer means to read or write the data that the pointer points to.

In C, the unary * operator is the dereferencing operator. If x is a pointer, then *x is what x points to. The unary & operator is the address-of operator. If x is anything, then &x is the address at which x is stored in memory. The * and & operators are inverses of each other: if x is any data, and y is any pointer, then these equations are always true:

*(&x) == x
&(*y) == y

A null pointer is a pointer that does not point to any valid data (but it is not the only such pointer). The C standard says that it is undefined behavior to dereference a null pointer. This means that absolutely anything could happen: the program could crash, it could continue working silently, or it could erase your hard drive (although that's rather unlikely).

In most implementations, you will get a "segmentation fault" or "access violation" if you try to do so, which will almost always result in your program being terminated by the operating system. Here's one way a null pointer could be dereferenced:

int *x = NULL;  // x is a null pointer
int y = *x;     // CRASH: dereference x, trying to read it
*x = 0;         // CRASH: dereference x, trying to write it

And yes, dereferencing a null pointer is pretty much exactly like a NullReferenceException in C# (or a NullPointerException in Java), except that the langauge standard is a little more helpful here. In C#, dereferencing a null reference has well-defined behavior: it always throws a NullReferenceException. There's no way that your program could continue working silently or erase your hard drive like in C (unless there's a bug in the language runtime, but again that's incredibly unlikely as well).

Array of char* should end at '\0' or "\0"?

Well, technically '\0' is a character while "\0" is a string, so if you're checking for the null termination character the former is correct. However, as Chris Lutz points out in his answer, your comparison won't work in it's current form.

When to use malloc for char pointers

malloc is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:

char *literal = "foo";

However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc:

char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);

Pointers, smart pointers or shared pointers?

the term "smart pointer" includes shared pointers, auto pointers, locking pointers and others. you meant to say auto pointer (more ambiguously known as "owning pointer"), not smart pointer.

Dumb pointers (T*) are never the best solution. They make you do explicit memory management, which is verbose, error prone, and sometimes nigh impossible. But more importantly, they don't signal your intent.

Auto pointers delete the pointee at destruction. For arrays, prefer encapsulations like vector and deque. For other objects, there's very rarely a need to store them on the heap - just use locals and object composition. Still the need for auto pointers arises with functions that return heap pointers -- such as factories and polymorphic returns.

Shared pointers delete the pointee when the last shared pointer to it is destroyed. This is useful when you want a no-brainer, open-ended storage scheme where expected lifetime and ownership can vary widely depending on the situation. Due to the need to keep an (atomic) counter, they're a bit slower than auto pointers. Some say half in jest that shared pointers are for people who can't design systems -- judge for yourself.

For an essential counterpart to shared pointers, look up weak pointers too.

Returning an array using C

Your method will return a local stack variable that will fail badly. To return an array, create one outside the function, pass it by address into the function, then modify it, or create an array on the heap and return that variable. Both will work, but the first doesn't require any dynamic memory allocation to get it working correctly.

void returnArray(int size, char *retArray)
{
  // work directly with retArray or memcpy into it from elsewhere like
  // memcpy(retArray, localArray, size); 
}

#define ARRAY_SIZE 20

int main(void)
{
  char foo[ARRAY_SIZE];
  returnArray(ARRAY_SIZE, foo);
}

Reason to Pass a Pointer by Reference in C++?

I have had to use code like this to provide functions to allocate memory to a pointer passed in and return its size because my company "object" to me using the STL

 int iSizeOfArray(int* &piArray) {
    piArray = new int[iNumberOfElements];
    ...
    return iNumberOfElements;
 }

It is not nice, but the pointer must be passed by reference (or use double pointer). If not, memory is allocated to a local copy of the pointer if it is passed by value which results in a memory leak.

Error: stray '\240' in program

I got the same error when I just copied the complete line but when I rewrite the code again i.e. instead of copy-paste, writing it completely then the error was no longer present.

Conclusion: There might be some unacceptable words to the language got copied giving rise to this error.

How do pointer-to-pointer's work in C? (and when might you use them?)

You have a variable that contains an address of something. That's a pointer.

Then you have another variable that contains the address of the first variable. That's a pointer to pointer.

Correct format specifier to print pointer or address?

p is the conversion specifier to print pointers. Use this.

int a = 42;

printf("%p\n", (void *) &a);

Remember that omitting the cast is undefined behavior and that printing with p conversion specifier is done in an implementation-defined manner.

What exactly is nullptr?

0 used to be the only integer value that could be used as a cast-free initializer for pointers: you can not initialize pointers with other integer values without a cast. You can consider 0 as a consexpr singleton syntactically similar to an integer literal. It can initiate any pointer or integer. But surprisingly, you'll find that it has no distinct type: it is an int. So how come 0 can initialize pointers and 1 cannot? A practical answer was we need a means of defining pointer null value and direct implicit conversion of int to a pointer is error-prone. Thus 0 became a real freak weirdo beast out of the prehistoric era. nullptr was proposed to be a real singleton constexpr representation of null value to initialize pointers. It can not be used to directly initialize integers and eliminates ambiguities involved with defining NULL in terms of 0. nullptr could be defined as a library using std syntax but semantically looked to be a missing core component. NULL is now deprecated in favor of nullptr, unless some library decides to define it as nullptr.

Length of array in function argument

Best example is here

thanks #define SIZE 10

void size(int arr[SIZE])
{
    printf("size of array is:%d\n",sizeof(arr));
}

int main()
{
    int arr[SIZE];
    size(arr);
    return 0;
}

Passing a 2D array to a C++ function

You can do something like this...

#include<iostream>

using namespace std;

//for changing values in 2D array
void myFunc(double *a,int rows,int cols){
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            *(a+ i*rows + j)+=10.0;
        }
    }
}

//for printing 2D array,similar to myFunc
void printArray(double *a,int rows,int cols){
    cout<<"Printing your array...\n";
    for(int i=0;i<rows;i++){
        for(int j=0;j<cols;j++){
            cout<<*(a+ i*rows + j)<<"  ";
        }
    cout<<"\n";
    }
}

int main(){
    //declare and initialize your array
    double a[2][2]={{1.5 , 2.5},{3.5 , 4.5}};

    //the 1st argument is the address of the first row i.e
    //the first 1D array
    //the 2nd argument is the no of rows of your array
    //the 3rd argument is the no of columns of your array
    myFunc(a[0],2,2);

    //same way as myFunc
    printArray(a[0],2,2);

    return 0;
}

Your output will be as follows...

11.5  12.5
13.5  14.5

What is the difference between char * const and const char *?

I presume you mean const char * and char * const .

The first, const char *, is a pointer to a constant character. The pointer itself is mutable.

The second, char * const is a constant pointer to a character. The pointer cannot change, the character it points to can.

And then there is const char * const where the pointer and character cannot change.

What is the size of a pointer?

Pointers are not always the same size on the same architecture.

You can read more on the concept of "near", "far" and "huge" pointers, just as an example of a case where pointer sizes differ...

http://en.wikipedia.org/wiki/Intel_Memory_Model#Pointer_sizes

Function Pointers in Java

Relative to most people here I am new to java but since I haven't seen a similar suggestion I have another alternative to suggest. Im not sure if its a good practice or not, or even suggested before and I just didn't get it. I just like it since I think its self descriptive.

 /*Just to merge functions in a common name*/
 public class CustomFunction{ 
 public CustomFunction(){}
 }

 /*Actual functions*/
 public class Function1 extends CustomFunction{
 public Function1(){}
 public void execute(){...something here...}
 }

 public class Function2 extends CustomFunction{
 public Function2(){}
 public void execute(){...something here...}
 }

 .....
 /*in Main class*/
 CustomFunction functionpointer = null;

then depending on the application, assign

 functionpointer = new Function1();
 functionpointer = new Function2();

etc.

and call by

 functionpointer.execute();

How to compare pointers?

The == operator on pointers will compare their numeric address and hence determine if they point to the same object.

Is it safe to delete a NULL pointer?

delete performs the check anyway, so checking it on your side adds overhead and looks uglier. A very good practice is setting the pointer to NULL after delete (helps avoiding double deletion and other similar memory corruption problems).

I'd also love if delete by default was setting the parameter to NULL like in

#define my_delete(x) {delete x; x = NULL;}

(I know about R and L values, but wouldn't it be nice?)

C++ Array Of Pointers

I would do it something along these lines:

class Foo{
...
};

int main(){
  Foo* arrayOfFoo[100]; //[1]

  arrayOfFoo[0] = new Foo; //[2]
}

[1] This makes an array of 100 pointers to Foo-objects. But no Foo-objects are actually created.

[2] This is one possible way to instantiate an object, and at the same time save a pointer to this object in the first position of your array.

Testing pointers for validity (C/C++)

AFAIK there is no way. You should try to avoid this situation by always setting pointers to NULL after freeing memory.

Reversing a string in C

You can actually do something like this:

#include <string.h>

void reverse(char *);

int main(void){
 char name[7] = "walter";
 reverse(name);
 printf("%s", name);
}

void reverse(char *s) {
  size_t len = strlen(s);
  char *a = s;
  char *b = &s[(int)len - 1];
  char tmp;
  for (; a < b; ++a, --b) {
    tmp = *a;
    *a = *b;
    *b = tmp;
  }
}

Difference between char* and const char*?

The question is what's the difference between

char *name

which points to a constant string literal, and

const char *cname

I.e. given

char *name = "foo";

and

const char *cname = "foo";

There is not much difference between the 2 and both can be seen as correct. Due to the long legacy of C code, the string literals have had a type of char[], not const char[], and there are lots of older code that likewise accept char * instead of const char *, even when they do not modify the arguments.

The principal difference of the 2 in general is that *cname or cname[n] will evaluate to lvalues of type const char, whereas *name or name[n] will evaluate to lvalues of type char, which are modifiable lvalues. A conforming compiler is required to produce a diagnostics message if target of the assignment is not a modifiable lvalue; it need not produce any warning on assignment to lvalues of type char:

name[0] = 'x'; // no diagnostics *needed*
cname[0] = 'x'; // a conforming compiler *must* produce a diagnostic message

The compiler is not required to stop the compilation in either case; it is enough that it produces a warning for the assignment to cname[0]. The resulting program is not a correct program. The behaviour of the construct is undefined. It may crash, or even worse, it might not crash, and might change the string literal in memory.

What's the difference between a null pointer and a void pointer?

A null pointer is guaranteed to not compare equal to a pointer to any object. It's actual value is system dependent and may vary depending on the type. To get a null int pointer you would do

int* p = 0;

A null pointer will be returned by malloc on failure.

We can test if a pointer is null, i.e. if malloc or some other function failed simply by testing its boolean value:

if (p) {
    /* Pointer is not null */
} else {
    /* Pointer is null */
}

A void pointer can point to any type and it is up to you to handle how much memory the referenced objects consume for the purpose of dereferencing and pointer arithmetic.

Dynamically allocating an array of objects

The constructor of your A object allocates another object dynamically and stores a pointer to that dynamically allocated object in a raw pointer.

For that scenario, you must define your own copy constructor , assignment operator and destructor. The compiler generated ones will not work correctly. (This is a corollary to the "Law of the Big Three": A class with any of destructor, assignment operator, copy constructor generally needs all 3).

You have defined your own destructor (and you mentioned creating a copy constructor), but you need to define both of the other 2 of the big three.

An alternative is to store the pointer to your dynamically allocated int[] in some other object that will take care of these things for you. Something like a vector<int> (as you mentioned) or a boost::shared_array<>.

To boil this down - to take advantage of RAII to the full extent, you should avoid dealing with raw pointers to the extent possible.

And since you asked for other style critiques, a minor one is that when you are deleting raw pointers you do not need to check for 0 before calling delete - delete handles that case by doing nothing so you don't have to clutter you code with the checks.

Typedef function pointer?

If you can use C++11 you may want to use std::function and using keyword.

using FunctionFunc = std::function<void(int arg1, std::string arg2)>;

Pointer to 2D arrays in C

Both your examples are equivalent. However, the first one is less obvious and more "hacky", while the second one clearly states your intention.

int (*pointer)[280];
pointer = tab1;

pointer points to an 1D array of 280 integers. In your assignment, you actually assign the first row of tab1. This works since you can implicitly cast arrays to pointers (to the first element).

When you are using pointer[5][12], C treats pointer as an array of arrays (pointer[5] is of type int[280]), so there is another implicit cast here (at least semantically).

In your second example, you explicitly create a pointer to a 2D array:

int (*pointer)[100][280];
pointer = &tab1;

The semantics are clearer here: *pointer is a 2D array, so you need to access it using (*pointer)[i][j].

Both solutions use the same amount of memory (1 pointer) and will most likely run equally fast. Under the hood, both pointers will even point to the same memory location (the first element of the tab1 array), and it is possible that your compiler will even generate the same code.

The first solution is "more advanced" since one needs quite a deep understanding on how arrays and pointers work in C to understand what is going on. The second one is more explicit.

What is uintptr_t data type

It's an unsigned integer type exactly the size of a pointer. Whenever you need to do something unusual with a pointer - like for example invert all bits (don't ask why) you cast it to uintptr_t and manipulate it as a usual integer number, then cast back.

Swapping pointers in C (char, int)

void intSwap (int *pa, int *pb){
    int temp = *pa;
    *pa = *pb;
    *pb = temp;
}

You need to know the following -

int a = 5; // an integer, contains value
int *p; // an integer pointer, contains address
p = &a; // &a means address of a
a = *p; // *p means value stored in that address, here 5

void charSwap(char* a, char* b){
    char temp = *a;
    *a = *b;
    *b = temp;
}

So, when you swap like this. Only the value will be swapped. So, for a char* only their first char will swap.

Now, if you understand char* (string) clearly, then you should know that, you only need to exchange the pointer. It'll be easier to understand if you think it as an array instead of string.

void stringSwap(char** a, char** b){
    char *temp = *a;
    *a = *b;
    *b = temp;
}

So, here you are passing double pointer because starting of an array itself is a pointer.

NULL vs nullptr (Why was it replaced?)

Here is Bjarne Stroustrup's wordings,

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

Convert iterator to pointer?

If your function really takes vector<int> * (a pointer to vector), then you should pass &foo since that will be a pointer to the vector. Obviously that will not simply solve your problem, but you cannot directly convert an iterator to a vector, since the memory at the address of the iterator will not directly address a valid vector.

You can construct a new vector by calling the vector constructor:

template <class InputIterator> vector(InputIterator, InputIterator)

This constructs a new vector by copying the elements between the two iterators. You would use it roughly like this:

bar(std::vector<int>(foo.begin()+1, foo.end());

C++ pass an array by reference

Like the other answer says, put the & after the *.

This brings up an interesting point that can be confusing sometimes: types should be read from right to left. For example, this is (starting from the rightmost *) a pointer to a constant pointer to an int.

int * const *x;

What you wrote would therefore be a pointer to a reference, which is not possible.

Function pointer as parameter

Replace void *disconnectFunc; with void (*disconnectFunc)(); to declare function pointer type variable. Or even better use a typedef:

typedef void (*func_t)(); // pointer to function with no args and void return
...
func_t fptr; // variable of pointer to function
...
void D::setDisconnectFunc( func_t func )
{
    fptr = func;
}

void D::disconnected()
{
    fptr();
    connected = false;
}

C free(): invalid pointer

You can't call free on the pointers returned from strsep. Those are not individually allocated strings, but just pointers into the string s that you've already allocated. When you're done with s altogether, you should free it, but you do not have to do that with the return values of strsep.

Pass by pointer & Pass by reference

In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.

Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.

Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.

References have a couple more advantages compared to pointers (e. g. they can't be NULL, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.

How do you pass a function as a parameter in C?

Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:

void foo(int bar(int, int));

is equivalent to this:

void foo(int (*bar)(int, int));

Why should I use a pointer rather than the object itself?

This is has been discussed at length, but in Java everything is a pointer. It makes no distinction between stack and heap allocations (all objects are allocated on the heap), so you don't realize you're using pointers. In C++, you can mix the two, depending on your memory requirements. Performance and memory usage is more deterministic in C++ (duh).

Function pointer as a member of a C struct

Maybe I am missing something here, but did you allocate any memory for that PString before you accessed it?

PString * initializeString() {
    PString *str;
    str = (PString *) malloc(sizeof(PString));
    str->length = &length;
    return str;
}

C pointer to array/array of pointers disambiguation

Here's how I interpret it:

int *something[n];

Note on precedence: array subscript operator ([]) has higher priority than dereference operator (*).

So, here we will apply the [] before *, making the statement equivalent to:

int *(something[i]);

Note on how a declaration makes sense: int num means num is an int, int *ptr or int (*ptr) means, (value at ptr) is an int, which makes ptr a pointer to int.

This can be read as, (value of the (value at ith index of the something)) is an integer. So, (value at the ith index of something) is an (integer pointer), which makes the something an array of integer pointers.

In the second one,

int (*something)[n];

To make sense out of this statement, you must be familiar with this fact:

Note on pointer representation of array: somethingElse[i] is equivalent to *(somethingElse + i)

So, replacing somethingElse with (*something), we get *(*something + i), which is an integer as per declaration. So, (*something) given us an array, which makes something equivalent to (pointer to an array).

Deleting a pointer in C++

I believe you're not fully understanding how pointers work.
When you have a pointer pointing to some memory there are three different things you must understand:
- there is "what is pointed" by the pointer (the memory)
- this memory address
- not all pointers need to have their memory deleted: you only need to delete memory that was dynamically allocated (used new operator).

Imagine:

int *ptr = new int; 
// ptr has the address of the memory.
// at this point, the actual memory doesn't have anything.
*ptr = 8;
// you're assigning the integer 8 into that memory.
delete ptr;
// you are only deleting the memory.
// at this point the pointer still has the same memory address (as you could
//   notice from your 2nd test) but what inside that memory is gone!

When you did

ptr = NULL;
// you didn't delete the memory
// you're only saying that this pointer is now pointing to "nowhere".
// the memory that was pointed by this pointer is now lost.

C++ allows that you try to delete a pointer that points to null but it doesn't actually do anything, just doesn't give any error.

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

12 is a compile-time constant which can not be changed unlike the data referenced by int&. What you can do is

const int& z = 12;

When should I use the new keyword in C++?

Without the new keyword you're storing that on call stack. Storing excessively large variables on stack will lead to stack overflow.

Pointers in C: when to use the ampersand and the asterisk?

I was looking through all the wordy explanations so instead turned to a video from University of New South Wales for rescue.Here is the simple explanation: if we have a cell that has address x and value 7, the indirect way to ask for address of value 7 is &7 and the indirect way to ask for value at address x is *x.So (cell: x , value: 7) == (cell: &7 , value: *x) .Another way to look into it: John sits at 7th seat.The *7th seat will point to John and &John will give address/location of the 7th seat. This simple explanation helped me and hope it will help others as well. Here is the link for the excellent video: click here.

Here is another example:

#include <stdio.h>

int main()
{ 
    int x;            /* A normal integer*/
    int *p;           /* A pointer to an integer ("*p" is an integer, so p
                       must be a pointer to an integer) */

    p = &x;           /* Read it, "assign the address of x to p" */
    scanf( "%d", &x );          /* Put a value in x, we could also use p here */
    printf( "%d\n", *p ); /* Note the use of the * to get the value */
    getchar();
}

Add-on: Always initialize pointer before using them.If not, the pointer will point to anything, which might result in crashing the program because the operating system will prevent you from accessing the memory it knows you don't own.But simply putting p = &x;, we are assigning the pointer a specific location.

Pointer-to-pointer dynamic two-dimensional array

In both cases your inner dimension may be dynamically specified (i.e. taken from a variable), but the difference is in the outer dimension.

This question is basically equivalent to the following:

Is int* x = new int[4]; "better" than int x[4]?

The answer is: "no, unless you need to choose that array dimension dynamically."

What are the rules for casting pointers in C?

When thinking about pointers, it helps to draw diagrams. A pointer is an arrow that points to an address in memory, with a label indicating the type of the value. The address indicates where to look and the type indicates what to take. Casting the pointer changes the label on the arrow but not where the arrow points.

d in main is a pointer to c which is of type char. A char is one byte of memory, so when d is dereferenced, you get the value in that one byte of memory. In the diagram below, each cell represents one byte.

-+----+----+----+----+----+----+-
 |    | c  |    |    |    |    | 
-+----+----+----+----+----+----+-
       ^~~~
       | char
       d

When you cast d to int*, you're saying that d really points to an int value. On most systems today, an int occupies 4 bytes.

-+----+----+----+----+----+----+-
 |    | c  | ?1 | ?2 | ?3 |    | 
-+----+----+----+----+----+----+-
       ^~~~~~~~~~~~~~~~~~~
       | int
       (int*)d

When you dereference (int*)d, you get a value that is determined from these four bytes of memory. The value you get depends on what is in these cells marked ?, and on how an int is represented in memory.

A PC is little-endian, which means that the value of an int is calculated this way (assuming that it spans 4 bytes): * ((int*)d) == c + ?1 * 28 + ?2 * 2¹6 + ?3 * 2²4. So you'll see that while the value is garbage, if you print in in hexadecimal (printf("%x\n", *n)), the last two digits will always be 35 (that's the value of the character '5').

Some other systems are big-endian and arrange the bytes in the other direction: * ((int*)d) == c * 2²4 + ?1 * 2¹6 + ?2 * 28 + ?3. On these systems, you'd find that the value always starts with 35 when printed in hexadecimal. Some systems have a size of int that's different from 4 bytes. A rare few systems arrange int in different ways but you're extremely unlikely to encounter them.

Depending on your compiler and operating system, you may find that the value is different every time you run the program, or that it's always the same but changes when you make even minor tweaks to the source code.

On some systems, an int value must be stored in an address that's a multiple of 4 (or 2, or 8). This is called an alignment requirement. Depending on whether the address of c happens to be properly aligned or not, the program may crash.

In contrast with your program, here's what happens when you have an int value and take a pointer to it.

int x = 42;
int *p = &x;
-+----+----+----+----+----+----+-
 |    |         x         |    | 
-+----+----+----+----+----+----+-
       ^~~~~~~~~~~~~~~~~~~
       | int
       p

The pointer p points to an int value. The label on the arrow correctly describes what's in the memory cell, so there are no surprises when dereferencing it.

Pointer arithmetic for void pointer in C

Void pointers can point to any memory chunk. Hence the compiler does not know how many bytes to increment/decrement when we attempt pointer arithmetic on a void pointer. Therefore void pointers must be first typecast to a known type before they can be involved in any pointer arithmetic.

void *p = malloc(sizeof(char)*10);
p++; //compiler does how many where to pint the pointer after this increment operation

char * c = (char *)p;
c++;  // compiler will increment the c by 1, since size of char is 1 byte.

Passing references to pointers in C++

I know that it's posible to pass references of pointers, I did it last week, but I can't remember what the syntax was, as your code looks correct to my brain right now. However another option is to use pointers of pointers:

Myfunc(String** s)

C++ - Assigning null to a std::string

Literal 0 is of type int and you can't assign int to std::string. Use mValue.clear() or assign an empty string mValue="".

How to increment a pointer address and pointer's value?

checked the program and the results are as,

p++;    // use it then move to next int position
++p;    // move to next int and then use it
++*p;   // increments the value by 1 then use it 
++(*p); // increments the value by 1 then use it
++*(p); // increments the value by 1 then use it
*p++;   // use the value of p then moves to next position
(*p)++; // use the value of p then increment the value
*(p)++; // use the value of p then moves to next position
*++p;   // moves to the next int location then use that value
*(++p); // moves to next location then use that value

Are there benefits of passing by pointer over passing by reference in C++?

Not really. Internally, passing by reference is performed by essentially passing the address of the referenced object. So, there really aren't any efficiency gains to be had by passing a pointer.

Passing by reference does have one benefit, however. You are guaranteed to have an instance of whatever object/type that is being passed in. If you pass in a pointer, then you run the risk of receiving a NULL pointer. By using pass-by-reference, you are pushing an implicit NULL-check up one level to the caller of your function.

Method Call Chaining; returning a pointer vs a reference?

The difference between pointers and references is quite simple: a pointer can be null, a reference can not.

Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).

Here it looks like references are more appropriate.

Printing pointers in C

You can't change the value (i.e., address of) a static array. In technical terms, the lvalue of an array is the address of its first element. Hence s == &s. It's just a quirk of the language.

Pointer to a string in C?

The string is basically bounded from the place where it is pointed to (char *ptrChar;), to the null character (\0).

The char *ptrChar; actually points to the beginning of the string (char array), and thus that is the pointer to that string, so when you do like ptrChar[x] for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).

lvalue required as left operand of assignment error when using C++

When you have an assignment operator in a statement, the LHS of the operator must be something the language calls an lvalue. If the LHS of the operator does not evaluate to an lvalue, the value from the RHS cannot be assigned to the LHS.

You cannot use:

10 = 20;

since 10 does not evaluate to an lvalue.

You can use:

int i;
i = 20;

since i does evaluate to an lvalue.

You cannot use:

int i;
i + 1 = 20;

since i + 1 does not evaluate to an lvalue.

In your case, p + 1 does not evaluate to an lavalue. Hence, you cannot use

p + 1 = p;

Returning pointer from a function

Although returning a pointer to a local object is bad practice, it didn't cause the kaboom here. Here's why you got a segfault:

int *fun()
{
    int *point;
    *point=12;  <<<<<<  your program crashed here.
    return point;
}

The local pointer goes out of scope, but the real issue is dereferencing a pointer that was never initialized. What is the value of point? Who knows. If the value did not map to a valid memory location, you will get a SEGFAULT. If by luck it mapped to something valid, then you just corrupted memory by overwriting that place with your assignment to 12.

Since the pointer returned was immediately used, in this case you could get away with returning a local pointer. However, it is bad practice because if that pointer was reused after another function call reused that memory in the stack, the behavior of the program would be undefined.

int *fun()
{
    int point;
    point = 12;
    return (&point);
}

or almost identically:

int *fun()
{
    int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

Another bad practice but safer method would be to declare the integer value as a static variable, and it would then not be on the stack and would be safe from being used by another function:

int *fun()
{
    static int point;
    int *point_ptr;
    point_ptr = &point;
    *point_ptr = 12;
    return (point_ptr);
}

or

int *fun()
{
    static int point;
    point = 12;
    return (&point);
}

As others have mentioned, the "right" way to do this would be to allocate memory on the heap, via malloc.

How to cast/convert pointer to reference in C++

foo(*ob);

You don't need to cast it because it's the same Object type, you just need to dereference it.

Passing by reference in C

Because you're passing a pointer(memory address) to the variable p into the function f. In other words you are passing a pointer not a reference.

Directly assigning values to C Pointers

In the first example, ptr has not been initialized, so it points to an unspecified memory location. When you assign something to this unspecified location, your program blows up.

In the second example, the address is set when you say ptr = &q, so you're OK.

How to declare std::unique_ptr and what is the use of it?

From cppreference, one of the std::unique_ptr constructors is

explicit unique_ptr( pointer p ) noexcept;

So to create a new std::unique_ptr is to pass a pointer to its constructor.

unique_ptr<int> uptr (new int(3));

Or it is the same as

int *int_ptr = new int(3);
std::unique_ptr<int> uptr (int_ptr);

The different is you don't have to clean up after using it. If you don't use std::unique_ptr (smart pointer), you will have to delete it like this

delete int_ptr;

when you no longer need it or it will cause a memory leak.

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

static_cast is the first cast you should attempt to use. It does things like implicit conversions between types (such as int to float, or pointer to void*), and it can also call explicit conversion functions (or implicit ones). In many cases, explicitly stating static_cast isn't necessary, but it's important to note that the T(something) syntax is equivalent to (T)something and should be avoided (more on that later). A T(something, something_else) is safe, however, and guaranteed to call the constructor.

static_cast can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn't cast through virtual inheritance. It does not do checking, however, and it is undefined behavior to static_cast down a hierarchy to a type that isn't actually the type of the object.


const_cast can be used to remove or add const to a variable; no other C++ cast is capable of removing it (not even reinterpret_cast). It is important to note that modifying a formerly const value is only undefined if the original variable is const; if you use it to take the const off a reference to something that wasn't declared with const, it is safe. This can be useful when overloading member functions based on const, for instance. It can also be used to add const to an object, such as to call a member function overload.

const_cast also works similarly on volatile, though that's less common.


dynamic_cast is exclusively used for handling polymorphism. You can cast a pointer or reference to any polymorphic type to any other class type (a polymorphic type has at least one virtual function, declared or inherited). You can use it for more than just casting downwards – you can cast sideways or even up another chain. The dynamic_cast will seek out the desired object and return it if possible. If it can't, it will return nullptr in the case of a pointer, or throw std::bad_cast in the case of a reference.

dynamic_cast has some limitations, though. It doesn't work if there are multiple objects of the same type in the inheritance hierarchy (the so-called 'dreaded diamond') and you aren't using virtual inheritance. It also can only go through public inheritance - it will always fail to travel through protected or private inheritance. This is rarely an issue, however, as such forms of inheritance are rare.


reinterpret_cast is the most dangerous cast, and should be used very sparingly. It turns one type directly into another — such as casting the value from one pointer to another, or storing a pointer in an int, or all sorts of other nasty things. Largely, the only guarantee you get with reinterpret_cast is that normally if you cast the result back to the original type, you will get the exact same value (but not if the intermediate type is smaller than the original type). There are a number of conversions that reinterpret_cast cannot do, too. It's used primarily for particularly weird conversions and bit manipulations, like turning a raw data stream into actual data, or storing data in the low bits of a pointer to aligned data.


C-style cast and function-style cast are casts using (type)object or type(object), respectively, and are functionally equivalent. They are defined as the first of the following which succeeds:

  • const_cast
  • static_cast (though ignoring access restrictions)
  • static_cast (see above), then const_cast
  • reinterpret_cast
  • reinterpret_cast, then const_cast

It can therefore be used as a replacement for other casts in some instances, but can be extremely dangerous because of the ability to devolve into a reinterpret_cast, and the latter should be preferred when explicit casting is needed, unless you are sure static_cast will succeed or reinterpret_cast will fail. Even then, consider the longer, more explicit option.

C-style casts also ignore access control when performing a static_cast, which means that they have the ability to perform an operation that no other cast can. This is mostly a kludge, though, and in my mind is just another reason to avoid C-style casts.

How to access the contents of a vector from a pointer to the vector in C++?

Do you have a pointer to a vector because that's how you've coded it? You may want to reconsider this and use a (possibly const) reference. For example:

#include <iostream>
#include <vector>

using namespace std;

void foo(vector<int>* a)
{
    cout << a->at(0) << a->at(1) << a->at(2) << endl;
    // expected result is "123"
}

int main()
{
    vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    foo(&a);
}

While this is a valid program, the general C++ style is to pass a vector by reference rather than by pointer. This will be just as efficient, but then you don't have to deal with possibly null pointers and memory allocation/cleanup, etc. Use a const reference if you aren't going to modify the vector, and a non-const reference if you do need to make modifications.

Here's the references version of the above program:

#include <iostream>
#include <vector>

using namespace std;

void foo(const vector<int>& a)
{
    cout << a[0] << a[1] << a[2] << endl;
    // expected result is "123"
}

int main()
{
    vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    foo(a);
}

As you can see, all of the information contained within a will be passed to the function foo, but it will not copy an entirely new value, since it is being passed by reference. It is therefore just as efficient as passing by pointer, and you can use it as a normal value rather than having to figure out how to use it as a pointer or having to dereference it.

Are there pointers in php?

PHP can use something like pointers:

$y=array(&$x);

Now $y acts like a pointer to $x and $y[0] dereferences a pointer.

The value array(&$x) is just a value, so it can be passed to functions, stored in other arrays, copied to other variables, etc. You can even create a pointer to this pointer variable. (Serializing it will break the pointer, however.)

Constant pointer vs Pointer to constant

Please refer the following link for better understanding about the difference between Const pointer and Pointer on a constant value.

constant pointer vs pointer on a constant value

Is the sizeof(some pointer) always equal to four?

Even on a plain x86 32 bit platform, you can get a variety of pointer sizes, try this out for an example:

struct A {};

struct B : virtual public A {};

struct C {};

struct D : public A, public C {};

int main()
{
    cout << "A:" << sizeof(void (A::*)()) << endl;
    cout << "B:" << sizeof(void (B::*)()) << endl;
    cout << "D:" << sizeof(void (D::*)()) << endl;
}

Under Visual C++ 2008, I get 4, 12 and 8 for the sizes of the pointers-to-member-function.

Raymond Chen talked about this here.

What does "dereferencing" a pointer mean?

A pointer is a "reference" to a value.. much like a library call number is a reference to a book. "Dereferencing" the call number is physically going through and retrieving that book.

int a=4 ;
int *pA = &a ;
printf( "The REFERENCE/call number for the variable `a` is %p\n", pA ) ;

// The * causes pA to DEREFERENCE...  `a` via "callnumber" `pA`.
printf( "%d\n", *pA ) ; // prints 4.. 

If the book isn't there, the librarian starts shouting, shuts the library down, and a couple of people are set to investigate the cause of a person going to find a book that isn't there.

How to pass objects to functions in C++?

There are some differences in calling conventions in C++ and Java. In C++ there are technically speaking only two conventions: pass-by-value and pass-by-reference, with some literature including a third pass-by-pointer convention (that is actually pass-by-value of a pointer type). On top of that, you can add const-ness to the type of the argument, enhancing the semantics.

Pass by reference

Passing by reference means that the function will conceptually receive your object instance and not a copy of it. The reference is conceptually an alias to the object that was used in the calling context, and cannot be null. All operations performed inside the function apply to the object outside the function. This convention is not available in Java or C.

Pass by value (and pass-by-pointer)

The compiler will generate a copy of the object in the calling context and use that copy inside the function. All operations performed inside the function are done to the copy, not the external element. This is the convention for primitive types in Java.

An special version of it is passing a pointer (address-of the object) into a function. The function receives the pointer, and any and all operations applied to the pointer itself are applied to the copy (pointer), on the other hand, operations applied to the dereferenced pointer will apply to the object instance at that memory location, so the function can have side effects. The effect of using pass-by-value of a pointer to the object will allow the internal function to modify external values, as with pass-by-reference and will also allow for optional values (pass a null pointer).

This is the convention used in C when a function needs to modify an external variable, and the convention used in Java with reference types: the reference is copied, but the referred object is the same: changes to the reference/pointer are not visible outside the function, but changes to the pointed memory are.

Adding const to the equation

In C++ you can assign constant-ness to objects when defining variables, pointers and references at different levels. You can declare a variable to be constant, you can declare a reference to a constant instance, and you can define all pointers to constant objects, constant pointers to mutable objects and constant pointers to constant elements. Conversely in Java you can only define one level of constant-ness (final keyword): that of the variable (instance for primitive types, reference for reference types), but you cannot define a reference to an immutable element (unless the class itself is immutable).

This is extensively used in C++ calling conventions. When the objects are small you can pass the object by value. The compiler will generate a copy, but that copy is not an expensive operation. For any other type, if the function will not change the object, you can pass a reference to a constant instance (usually called constant reference) of the type. This will not copy the object, but pass it into the function. But at the same time the compiler will guarantee that the object is not changed inside the function.

Rules of thumb

This are some basic rules to follow:

  • Prefer pass-by-value for primitive types
  • Prefer pass-by-reference with references to constant for other types
  • If the function needs to modify the argument use pass-by-reference
  • If the argument is optional, use pass-by-pointer (to constant if the optional value should not be modified)

There are other small deviations from these rules, the first of which is handling ownership of an object. When an object is dynamically allocated with new, it must be deallocated with delete (or the [] versions thereof). The object or function that is responsible for the destruction of the object is considered the owner of the resource. When a dynamically allocated object is created in a piece of code, but the ownership is transfered to a different element it is usually done with pass-by-pointer semantics, or if possible with smart pointers.

Side note

It is important to insist in the importance of the difference between C++ and Java references. In C++ references are conceptually the instance of the object, not an accessor to it. The simplest example is implementing a swap function:

// C++
class Type; // defined somewhere before, with the appropriate operations
void swap( Type & a, Type & b ) {
   Type tmp = a;
   a = b;
   b = tmp;
}
int main() {
   Type a, b;
   Type old_a = a, old_b = b;
   swap( a, b );
   assert( a == old_b );
   assert( b == old_a ); 
}

The swap function above changes both its arguments through the use of references. The closest code in Java:

public class C {
   // ...
   public static void swap( C a, C b ) {
      C tmp = a;
      a = b;
      b = tmp;
   }
   public static void main( String args[] ) {
      C a = new C();
      C b = new C();
      C old_a = a;
      C old_b = b;
      swap( a, b ); 
      // a and b remain unchanged a==old_a, and b==old_b
   }
}

The Java version of the code will modify the copies of the references internally, but will not modify the actual objects externally. Java references are C pointers without pointer arithmetic that get passed by value into functions.

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

You have to name your struct like that:

typedef struct car_t {

   char

   wheel_t

} car_t;

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

You can't. Not with 100% accuracy, anyway. The pointer has no length/size but its own. All it does is point to a particular place in memory that holds a char. If that char is part of a string, then you can use strlen to determine what chars follow the one currently being pointed to, but that doesn't mean the array in your case is that big.
Basically:

A pointer is not an array, so it doesn't need to know what the size of the array is. A pointer can point to a single value, so a pointer can exist without there even being an array. It doesn't even care where the memory it points to is situated (Read only, heap or stack... doesn't matter). A pointer doesn't have a length other than itself. A pointer just is...
Consider this:

char beep = '\a';
void alert_user(const char *msg, char *signal); //for some reason
alert_user("Hear my super-awsome noise!", &beep); //passing pointer to single char!

void alert_user(const char *msg, char *signal)
{
    printf("%s%c\n", msg, *signal);
}

A pointer can be a single char, as well as the beginning, end or middle of an array...
Think of chars as structs. You sometimes allocate a single struct on the heap. That, too, creates a pointer without an array.

Using only a pointer, to determine how big an array it is pointing to is impossible. The closest you can get to it is using calloc and counting the number of consecutive \0 chars you can find through the pointer. Of course, that doesn't work once you've assigned/reassigned stuff to that array's keys and it also fails if the memory just outside of the array happens to hold \0, too. So using this method is unreliable, dangerous and just generally silly. Don't. Do. It.

Another analogy:
Think of a pointer as a road sign, it points to Town X. The sign doesn't know what that town looks like, and it doesn't know or care (or can care) who lives there. It's job is to tell you where to find Town X. It can only tell you how far that town is, but not how big it is. That information is deemed irrelevant for road-signs. That's something that you can only find out by looking at the town itself, not at the road-signs that are pointing you in its direction

So, using a pointer the only thing you can do is:

char a_str[] = "hello";//{h,e,l,l,o,\0}
char *arr_ptr = &a_str[0];
printf("Get length of string -> %d\n", strlen(arr_ptr));

But this, of course, only works if the array/string is \0-terminated.

As an aside:

int length = sizeof(a)/sizeof(char);//sizeof char is guaranteed 1, so sizeof(a) is enough

is actually assigning size_t (the return type of sizeof) to an int, best write:

size_t length = sizeof(a)/sizeof(*a);//best use ptr's type -> good habit

Since size_t is an unsigned type, if sizeof returns bigger values, the value of length might be something you didn't expect...

Regular cast vs. static_cast vs. dynamic_cast

static_cast

static_cast is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. static_cast performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:

void func(void *data) {
  // Conversion from MyClass* -> void* is implicit
  MyClass *c = static_cast<MyClass*>(data);
  ...
}

int main() {
  MyClass c;
  start_thread(&func, &c)  // func(&c) will be called
      .join();
}

In this example, you know that you passed a MyClass object, and thus there isn't any need for a runtime check to ensure this.

dynamic_cast

dynamic_cast is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a bad_cast exception is thrown in that case).

if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
  ...
} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
  ...
}

You cannot use dynamic_cast if you downcast (cast to a derived class) and the argument type is not polymorphic. For example, the following code is not valid, because Base doesn't contain any virtual function:

struct Base { };
struct Derived : Base { };
int main() {
  Derived d; Base *b = &d;
  dynamic_cast<Derived*>(b); // Invalid
}

An "up-cast" (cast to the base class) is always valid with both static_cast and dynamic_cast, and also without any cast, as an "up-cast" is an implicit conversion.

Regular Cast

These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast. Needless to say, this is much more powerful as it combines all of const_cast, static_cast and reinterpret_cast, but it's also unsafe, because it does not use dynamic_cast.

In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" static_cast sequence would give you a compile-time error for that.

Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

Return array in a function

In C++11, you can return std::array.

#include <array>
using namespace std;

array<int, 5> fillarr(int arr[])
{
    array<int, 5> arr2;
    for(int i=0; i<5; ++i) {
        arr2[i]=arr[i]*2;
    }
    return arr2;
}

error: ‘NULL’ was not declared in this scope

To complete the other answers: If you are using C++11, use nullptr, which is a keyword that means a void pointer pointing to null. (instead of NULL, which is not a pointer type)

char *array and char array[]

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

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

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

char string[] = "Some string";

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

string[1] = 'v';

Is valid in the latter case.
If you write:

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

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

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

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

What is the difference between NULL, '\0' and 0?

A one-L NUL, it ends a string.

A two-L NULL points to no thing.

And I will bet a golden bull

That there is no three-L NULLL.

How do you deal with NUL?

With arrays, why is it the case that a[5] == 5[a]?

Because array access is defined in terms of pointers. a[i] is defined to mean *(a + i), which is commutative.

Print the address or pointer for value in C

Since you already seem to have solved the basic pointer address display, here's how you would check the address of a double pointer:

char **a;
char *b;
char c = 'H';

b = &c;
a = &b;

You would be able to access the address of the double pointer a by doing:

printf("a points at this memory location: %p", a);
printf("which points at this other memory location: %p", *a);

Pointer to incomplete class type is not allowed

One thing to check for...

If your class is defined as a typedef:

typedef struct myclass { };

Then you try to refer to it as struct myclass anywhere else, you'll get Incomplete Type errors left and right. It's sometimes a mistake to forget the class/struct was typedef'ed. If that's the case, remove "struct" from:

typedef struct mystruct {}...

struct mystruct *myvar = value;

Instead use...

mystruct *myvar = value;

Common mistake.

How can I use pointers in Java?

Java does not have pointers like C has, but it does allow you to create new objects on the heap which are "referenced" by variables. The lack of pointers is to stop Java programs from referencing memory locations illegally, and also enables Garbage Collection to be automatically carried out by the Java Virtual Machine.

How to convert const char* to char* in C?

To be safe you don't break stuff (for example when these strings are changed in your code or further up), or crash you program (in case the returned string was literal for example like "hello I'm a literal string" and you start to edit it), make a copy of the returned string.

You could use strdup() for this, but read the small print. Or you can of course create your own version if it's not there on your platform.

Pointer to class data member "::*"

Here is an example where pointer to data members could be useful:

#include <iostream>
#include <list>
#include <string>

template <typename Container, typename T, typename DataPtr>
typename Container::value_type searchByDataMember (const Container& container, const T& t, DataPtr ptr) {
    for (const typename Container::value_type& x : container) {
        if (x->*ptr == t)
            return x;
    }
    return typename Container::value_type{};
}

struct Object {
    int ID, value;
    std::string name;
    Object (int i, int v, const std::string& n) : ID(i), value(v), name(n) {}
};

std::list<Object*> objects { new Object(5,6,"Sam"), new Object(11,7,"Mark"), new Object(9,12,"Rob"),
    new Object(2,11,"Tom"), new Object(15,16,"John") };

int main() {
    const Object* object = searchByDataMember (objects, 11, &Object::value);
    std::cout << object->name << '\n';  // Tom
}

printf formatting (%d versus %u)

The difference is simple: they cause different warning messages to be emitted when compiling:

1156942.c:7:31: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %d\n", &a); // prints "memory add=-12"
                               ^
1156942.c:8:31: warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘int *’ [-Wformat=]
     printf("memory address = %u\n", &a); // prints "memory add=65456"
                               ^

If you pass your pointer as a void* and use %p as the conversion specifier, then you get no error message:

#include <stdio.h>

int main()
{
    int a = 5;
    // check the memory address
    printf("memory address = %d\n", &a); /* wrong */
    printf("memory address = %u\n", &a); /* wrong */
    printf("memory address = %p\n", (void*)&a); /* right */
}

Arrow operator (->) usage in C

a->b is just short for (*a).b in every way (same for functions: a->b() is short for (*a).b()).

Pointer vs. Reference

A reference is similar to a pointer, except that you don’t need to use a prefix * to access the value referred to by the reference. Also, a reference cannot be made to refer to a different object after its initialization.

References are particularly useful for specifying function arguments.

for more information see "A Tour of C++" by "Bjarne Stroustrup" (2014) Pages 11-12

Using pointer to char array, values in that array can be accessed?

Use of pointer before character array

Normally, Character array is used to store single elements in it i.e 1 byte each

eg:

char a[]={'a','b','c'};

we can't store multiple value in it.

by using pointer before the character array we can store the multi dimensional array elements in the array

i.e.

char *a[]={"one","two","three"};
printf("%s\n%s\n%s",a[0],a[1],a[2]);

Why does the arrow (->) operator in C exist?

I'll interpret your question as two questions: 1) why -> even exists, and 2) why . does not automatically dereference the pointer. Answers to both questions have historical roots.

Why does -> even exist?

In one of the very first versions of C language (which I will refer as CRM for "C Reference Manual", which came with 6th Edition Unix in May 1975), operator -> had very exclusive meaning, not synonymous with * and . combination

The C language described by CRM was very different from the modern C in many respects. In CRM struct members implemented the global concept of byte offset, which could be added to any address value with no type restrictions. I.e. all names of all struct members had independent global meaning (and, therefore, had to be unique). For example you could declare

struct S {
  int a;
  int b;
};

and name a would stand for offset 0, while name b would stand for offset 2 (assuming int type of size 2 and no padding). The language required all members of all structs in the translation unit either have unique names or stand for the same offset value. E.g. in the same translation unit you could additionally declare

struct X {
  int a;
  int x;
};

and that would be OK, since the name a would consistently stand for offset 0. But this additional declaration

struct Y {
  int b;
  int a;
};

would be formally invalid, since it attempted to "redefine" a as offset 2 and b as offset 0.

And this is where the -> operator comes in. Since every struct member name had its own self-sufficient global meaning, the language supported expressions like these

int i = 5;
i->b = 42;  /* Write 42 into `int` at address 7 */
100->a = 0; /* Write 0 into `int` at address 100 */

The first assignment was interpreted by the compiler as "take address 5, add offset 2 to it and assign 42 to the int value at the resultant address". I.e. the above would assign 42 to int value at address 7. Note that this use of -> did not care about the type of the expression on the left-hand side. The left hand side was interpreted as an rvalue numerical address (be it a pointer or an integer).

This sort of trickery was not possible with * and . combination. You could not do

(*i).b = 42;

since *i is already an invalid expression. The * operator, since it is separate from ., imposes more strict type requirements on its operand. To provide a capability to work around this limitation CRM introduced the -> operator, which is independent from the type of the left-hand operand.

As Keith noted in the comments, this difference between -> and *+. combination is what CRM is referring to as "relaxation of the requirement" in 7.1.8: Except for the relaxation of the requirement that E1 be of pointer type, the expression E1->MOS is exactly equivalent to (*E1).MOS

Later, in K&R C many features originally described in CRM were significantly reworked. The idea of "struct member as global offset identifier" was completely removed. And the functionality of -> operator became fully identical to the functionality of * and . combination.

Why can't . dereference the pointer automatically?

Again, in CRM version of the language the left operand of the . operator was required to be an lvalue. That was the only requirement imposed on that operand (and that's what made it different from ->, as explained above). Note that CRM did not require the left operand of . to have a struct type. It just required it to be an lvalue, any lvalue. This means that in CRM version of C you could write code like this

struct S { int a, b; };
struct T { float x, y, z; };

struct T c;
c.b = 55;

In this case the compiler would write 55 into an int value positioned at byte-offset 2 in the continuous memory block known as c, even though type struct T had no field named b. The compiler would not care about the actual type of c at all. All it cared about is that c was an lvalue: some sort of writable memory block.

Now note that if you did this

S *s;
...
s.b = 42;

the code would be considered valid (since s is also an lvalue) and the compiler would simply attempt to write data into the pointer s itself, at byte-offset 2. Needless to say, things like this could easily result in memory overrun, but the language did not concern itself with such matters.

I.e. in that version of the language your proposed idea about overloading operator . for pointer types would not work: operator . already had very specific meaning when used with pointers (with lvalue pointers or with any lvalues at all). It was very weird functionality, no doubt. But it was there at the time.

Of course, this weird functionality is not a very strong reason against introducing overloaded . operator for pointers (as you suggested) in the reworked version of C - K&R C. But it hasn't been done. Maybe at that time there was some legacy code written in CRM version of C that had to be supported.

(The URL for the 1975 C Reference Manual may not be stable. Another copy, possibly with some subtle differences, is here.)

C pass int array pointer as parameter into a function

Using the really excellent example from Greggo, I got this to work as a bubble sort with passing an array as a pointer and doing a simple -1 manipulation.

#include<stdio.h>

void sub_one(int (*arr)[7])
{
     int i; 
     for(i=0;i<7;i++)
    {
        (*arr)[i] -= 1 ; // subtract 1 from each point
        printf("%i\n", (*arr)[i]);

    }

}   

int main()
{
    int a[]= { 180, 185, 190, 175, 200, 180, 181};
    int pos, j, i;
    int n=7;
    int temp;
    for (pos =0; pos < 7; pos ++){
        printf("\nPosition=%i Value=%i", pos, a[pos]);
    }
    for(i=1;i<=n-1;i++){
        temp=a[i];
        j=i-1;
        while((temp<a[j])&&(j>=0)) // while selected # less than a[j] and not j isn't 0
        {
            a[j+1]=a[j];    //moves element forward
            j=j-1;
        }
         a[j+1]=temp;    //insert element in proper place
    }

    printf("\nSorted list is as follows:\n");
    for(i=0;i<n;i++)
    {
        printf("%d\n",a[i]);
    }
    printf("\nmedian = %d\n", a[3]);
    sub_one(&a);

    return 0;
}

I need to read up on how to encapsulate pointers because that threw me off.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

Can I use if (pointer) instead of if (pointer != NULL)?

Explicitly checking for NULL could provide a hint to the compiler on what you are trying to do, ergo leading to being less error-prone.

enter image description here

C++ initial value of reference to non-const must be an lvalue

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);

C++ correct way to return pointer to array from function

Your code (which looks ok) doesn't return a pointer to an array. It returns a pointer to the first element of an array.

In fact that's usually what you want to do. Most manipulation of arrays are done via pointers to individual elements, not via pointers to the array as a whole.

You can define a pointer to an array, for example this:

double (*p)[42];

defines p as a pointer to a 42-element array of doubles. A big problem with that is that you have to specify the number of elements in the array as part of the type -- and that number has to be a compile-time constant. Most programs that deal with arrays need to deal with arrays of varying sizes; a given array's size won't vary after it's been created, but its initial size isn't necessarily known at compile time, and different array objects can have different sizes.

A pointer to the first element of an array lets you use either pointer arithmetic or the indexing operator [] to traverse the elements of the array. But the pointer doesn't tell you how many elements the array has; you generally have to keep track of that yourself.

If a function needs to create an array and return a pointer to its first element, you have to manage the storage for that array yourself, in one of several ways. You can have the caller pass in a pointer to (the first element of) an array object, probably along with another argument specifying its size -- which means the caller has to know how big the array needs to be. Or the function can return a pointer to (the first element of) a static array defined inside the function -- which means the size of the array is fixed, and the same array will be clobbered by a second call to the function. Or the function can allocate the array on the heap -- which makes the caller responsible for deallocating it later.

Everything I've written so far is common to C and C++, and in fact it's much more in the style of C than C++. Section 6 of the comp.lang.c FAQ discusses the behavior of arrays and pointers in C.

But if you're writing in C++, you're probably better off using C++ idioms. For example, the C++ standard library provides a number of headers defining container classes such as <vector> and <array>, which will take care of most of this stuff for you. Unless you have a particular reason to use raw arrays and pointers, you're probably better off just using C++ containers instead.

EDIT : I think you edited your question as I was typing this answer. The new code at the end of your question is, as you observer, no good; it returns a pointer to an object that ceases to exist as soon as the function returns. I think I've covered the alternatives.

Function stoi not declared

std::stoi was introduced in C++11. Make sure your compiler settings are correct and/or your compiler supports C++11.

How to sum up an array of integers in C#

An alternative also it to use the Aggregate() extension method.

var sum = arr.Aggregate((temp, x) => temp+x);

How to install plugins to Sublime Text 2 editor?

Installation code chunks for vanilla Sublime may change in the future.

This link would be the safest place to install plugin support to Sublime Text 2.

For Sublime Text 3 this link works has the code.

enter image description here

Efficiently counting the number of lines of a text file. (200mb+)

private static function lineCount($file) {
    $linecount = 0;
    $handle = fopen($file, "r");
    while(!feof($handle)){
        if (fgets($handle) !== false) {
                $linecount++;
        }
    }
    fclose($handle);
    return  $linecount;     
}

I wanted to add a little fix to the function above...

in a specific example where i had a file containing the word 'testing' the function returned 2 as a result. so i needed to add a check if fgets returned false or not :)

have fun :)

phpMyAdmin - The MySQL Extension is Missing

Your installation is missing some php modules, there should be a list of required modules in the phpmyadmin readme. If you recently enabled the modules, try restarting the apache service / daemon.

Edit: As it seems, there is no single "enable these modules" in the docs, so enable either mysql or mysqli in your php.ini (you might need to install it first).

The two messages are not important if you do not intend to upload or download compressed file within phpMyAdmin. If you do, enable the zlib and / or bz2 modules.

Remove an array element and shift the remaining ones

You can use memmove(), but you have to keep track of the array size yourself:

size_t array_size = 5;
int array[5] = {1, 2, 3, 4, 5};

// delete element at index 2
memmove(array + 2, array + 3, (array_size - 2 - 1) * sizeof(int));
array_size--;

In C++, though, it would be better to use a std::vector:

std::vector<int> array;
// initialize array...

// delete element at index 2
array.erase(array.begin() + 2);

How to write a large buffer into a binary file in C++, fast?

I see no difference between std::stream/FILE/device. Between buffering and non buffering.

Also note:

  • SSD drives "tend" to slow down (lower transfer rates) as they fill up.
  • SSD drives "tend" to slow down (lower transfer rates) as they get older (because of non working bits).

I am seeing the code run in 63 secondds.
Thus a transfer rate of: 260M/s (my SSD look slightly faster than yours).

64 * 1024 * 1024 * 8 /*sizeof(unsigned long long) */ * 32 /*Chunks*/

= 16G
= 16G/63 = 260M/s

I get a no increase by moving to FILE* from std::fstream.

#include <stdio.h>

using namespace std;

int main()
{
    
    FILE* stream = fopen("binary", "w");

    for(int loop=0;loop < 32;++loop)
    {
         fwrite(a, sizeof(unsigned long long), size, stream);
    }
    fclose(stream);

}

So the C++ stream are working as fast as the underlying library will allow.

But I think it is unfair comparing the OS to an application that is built on-top of the OS. The application can make no assumptions (it does not know the drives are SSD) and thus uses the file mechanisms of the OS for transfer.

While the OS does not need to make any assumptions. It can tell the types of the drives involved and use the optimal technique for transferring the data. In this case a direct memory to memory transfer. Try writing a program that copies 80G from 1 location in memory to another and see how fast that is.

Edit

I changed my code to use the lower level calls:
ie no buffering.

#include <fcntl.h>
#include <unistd.h>


const unsigned long long size = 64ULL*1024ULL*1024ULL;
unsigned long long a[size];
int main()
{
    int data = open("test", O_WRONLY | O_CREAT, 0777);
    for(int loop = 0; loop < 32; ++loop)
    {   
        write(data, a, size * sizeof(unsigned long long));
    }   
    close(data);
}

This made no diffference.

NOTE: My drive is an SSD drive if you have a normal drive you may see a difference between the two techniques above. But as I expected non buffering and buffering (when writting large chunks greater than buffer size) make no difference.

Edit 2:

Have you tried the fastest method of copying files in C++

int main()
{
    std::ifstream  input("input");
    std::ofstream  output("ouptut");

    output << input.rdbuf();
}

Active Directory LDAP Query by sAMAccountName and Domain

First, modify your search filter to only look for users and not contacts:

(&(objectCategory=person)(objectClass=user)(sAMAccountName=BTYNDALL))

You can enumerate all of the domains of a forest by connecting to the configuration partition and enumerating all the entries in the partitions container. Sorry I don't have any C# code right now but here is some vbscript code I've used in the past:

Set objRootDSE = GetObject("LDAP://RootDSE")
AdComm.Properties("Sort on") = "name"
AdComm.CommandText = "<LDAP://cn=Partitions," & _
    objRootDSE.Get("ConfigurationNamingContext") & ">;" & _
        "(&(objectcategory=crossRef)(systemFlags=3));" & _
            "name,nCName,dnsRoot;onelevel"
set AdRs = AdComm.Execute

From that you can retrieve the name and dnsRoot of each partition:

AdRs.MoveFirst
With AdRs
  While Not .EOF
    dnsRoot = .Fields("dnsRoot")

    Set objOption = Document.createElement("OPTION")
    objOption.Text = dnsRoot(0)
    objOption.Value = "LDAP://" & dnsRoot(0) & "/" & .Fields("nCName").Value
    Domain.Add(objOption)
    .MoveNext 
  Wend 
End With

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

Credit to @COOLGAMETUBE for tipping me off to what ended up working for me. His idea was good but I had a problem when Application.SetCompatibleTextRenderingDefault was called after the form was already created. So with a little change, this is working for me:


static class Program
{
    public static Form1 form1; // = new Form1(); // Place this var out of the constructor

/// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(form1 = new Form1()); } }

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

To stop seeing those cast_sender.js errors, edit the youtube link in the iframe src and change embed to v

Showing all session data at once?

echo "<pre>";
print_r($this->session->all_userdata());
echo "</pre>";

Display yet formatting then you can view properly.

Keyboard shortcut to clear cell output in Jupyter notebook

For versions less than 5:

Option 1 -- quick hack:

Change the cell type to raw then back to code: EscRY will discard the output.

Option 2 -- custom shortcut (without GUI):

For this, you need to edit the custom.js file which is typically located at ~/.jupyter/custom/custom.js (if it doesn't exist, create it).

In there, you have to add

require(['base/js/namespace']) {
    // setup 'ctrl-l' as shortcut for clearing current output
    Jupyter.keyboard_manager.command_shortcuts
           .add_shortcut('ctrl-l', 'jupyter-notebook:clear-cell-output');
}

You can add shortcut there for all the fancy things you like, since the 2nd argument can be a function (docs)

If you want mappings for other standard commands, you can dump a list of all available commands by running the following in your notebook:

from IPython.core.display import Javascript

js = """
  var jc_html = "";
  var jc_array = Object.keys(IPython.notebook.keyboard_manager.command_shortcuts.actions._actions);
  for (var i=0;i<jc_array.length;i++) {
    jc_html = jc_html + jc_array[i] + "<br >";
  }
  element.html(jc_html);
  """

Javascript(data=js, lib=None, css=None)

How to use ArrayList.addAll()?

You can use Google guava as such:

ImmutableList<char> dirs = ImmutableList.of('+', '-', '*', '^');

Selecting one row from MySQL using mysql_* API

Ultimately, I want to be able to echo out a signle field like so:

   $row['option_value']

So why don't you? It should work.

Cast Double to Integer in Java

I think it's impossible to understand the other answers without covering the pitfalls and reasoning behind it.

You cannot directly cast an Integer to a Double object. Also Double and Integer are immutable objects, so you cannot modify them in any way.

Each numeric class has a primitive alternative (Double vs double, Integer vs int, ...). Note that these primitives start with a lowercase character (e.g. int). That tells us that they aren't classes/objects. Which also means that they don't have methods. By contrast, the classes (e.g. Integer) act like boxes/wrappers around these primitives, which makes it possible to use them like objects.

Strategy:

To convert a Double to an Integer you would need to follow this strategy:

  1. Convert the Double object to a primitive double. (= "unboxing")
  2. Convert the primitive double to a primitive int. (= "casting")
  3. Convert the primitive int back to an Integer object. (= "boxing")

In code:

// starting point
Double myDouble = Double.valueOf(10.0);

// step 1: unboxing
double dbl = myDouble.doubleValue();

// step 2: casting
int intgr = (int) dbl;

// step 3: boxing
Integer val = Integer.valueOf(intgr);

Actually there is a shortcut. You can unbox immediately from a Double straight to a primitive int. That way, you can skip step 2 entirely.

Double myDouble = Double.valueOf(10.0);
Integer val = Integer.valueOf(myDouble.intValue()); // the simple way

Pitfalls:

However, there are a lot of things that are not covered in the code above. The code-above is not null-safe.

Double myDouble = null;
Integer val = Integer.valueOf(myDouble.intValue()); // will throw a NullPointerException

// a null-safe solution:
Integer val = (myDouble == null)? null : Integer.valueOf(myDouble.intValue());

Now it works fine for most values. However integers have a very small range (min/max value) compared to a Double. On top of that, doubles can also hold "special values", that integers cannot:

  • 1/0 = +infinity
  • -1/0 = -infinity
  • 0/0 = undefined (NaN)

So, depending on the application, you may want to add some filtering to avoid nasty Exceptions.

Then, the next shortcoming is the rounding strategy. By default Java will always round down. Rounding down makes perfect sense in all programming languages. Basically Java is just throwing away some of the bytes. In financial applications you will surely want to use half-up rounding (e.g.: round(0.5) = 1 and round(0.4) = 0).

// null-safe and with better rounding
long rounded = (myDouble == null)? 0L: Math.round(myDouble.doubleValue());
Integer val = Integer.valueOf(rounded);

Auto-(un)boxing

You could be tempted to use auto-(un)boxing in this, but I wouldn't. If you're already stuck now, then the next examples will not be that obvious neither. If you don't understand the inner workings of auto-(un)boxing then please don't use it.

Integer val1 = 10; // works
Integer val2 = 10.0; // doesn't work

Double val3 = 10; // doesn't work
Double val4 = 10.0; // works

Double val5 = null; 
double val6 = val5; // doesn't work (throws a NullPointerException)

I guess the following shouldn't be a surprise. But if it is, then you may want to read some article about casting in Java.

double val7 = (double) 10; // works
Double val8 = (Double) Integer.valueOf(10); // doesn't work
Integer val9 = (Integer) 9; // pure nonsense

Prefer valueOf:

Also, don't be tempted to use new Integer() constructor (as some other answers propose). The valueOf() methods are better because they use caching. It's a good habit to use these methods, because from time to time they will save you some memory.

long rounded = (myDouble == null)? 0L: Math.round(myDouble.doubleValue());
Integer val = new Integer(rounded); // waste of memory

Difference between $(this) and event.target?

There is a significant different in how jQuery handles the this variable with a "on" method

$("outer DOM element").on('click',"inner DOM element",function(){
  $(this) // refers to the "inner DOM element"
})

If you compare this with :-

$("outer DOM element").click(function(){
  $(this) // refers to the "outer DOM element"
})

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

  1. Make sure that the version of the m2e(clipse) plugin that you're running is at least 1.1.0

  2. Close maven project - right click "Close Project"

  3. Manualy remove all classpathentry with kind="var" in .classpath file
  4. Open project

or

  1. Remove maven project
  2. Manualy rmeove .classpath 4 Reimport project

Duplicate line in Visual Studio Code

Another 2 very usefull shortcuts are to move lines selected up and down, like sublime text does...

{
  "key" : "ctrl+shift+down", "command" : "editor.action.moveLinesDownAction",
  "when" : "editorTextFocus && !editorReadonly"
},

and

{
  "key" : "ctrl+shift+up", "command" : "editor.action.moveLinesUpAction",
  "when" : "editorTextFocus && !editorReadonly"
}

Check if AJAX response data is empty/blank/null/undefined/0

The following correct answer was provided in the comment section of the question by Felix Kling:

if (!$.trim(data)){   
    alert("What follows is blank: " + data);
}
else{   
    alert("What follows is not blank: " + data);
}

How to get height of <div> in px dimension

Although they vary slightly as to how they retrieve a height value, i.e some would calculate the whole element including padding, margin, scrollbar, etc and others would just calculate the element in its raw form.
You can try these ones:

javascript:

var myDiv = document.getElementById("myDiv");
myDiv.clientHeight;
myDiv.scrollHeight;
myDiv.offsetHeight;

or in jquery:

$("#myDiv").height();
$("#myDiv").innerHeight();
$("#myDiv").outerHeight();

Create file path from variables

Yes there is such a built-in function: os.path.join.

>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'

Insert a background image in CSS (Twitter Bootstrap)

body {
    background-image: url(your image link);
    background-position: center center;
    background-repeat: no-repeat;
    background-attachment:fixed;
    background-size: cover;
    background-color: #464646;
}

Match whitespace but not newlines

m/ /g just give space in / /, and it will work. Or use \S — it will replace all the special characters like tab, newlines, spaces, and so on.

How to do date/time comparison

Recent protocols prefer usage of RFC3339 per golang time package documentation.

In general RFC1123Z should be used instead of RFC1123 for servers that insist on that format, and RFC3339 should be preferred for new protocols. RFC822, RFC822Z, RFC1123, and RFC1123Z are useful for formatting; when used with time.Parse they do not accept all the time formats permitted by the RFCs.

cutOffTime, _ := time.Parse(time.RFC3339, "2017-08-30T13:35:00Z")
// POSTDATE is a date time field in DB (datastore)
query := datastore.NewQuery("db").Filter("POSTDATE >=", cutOffTime).

jQuery: how to trigger anchor link's click event

It worked for me:

     window.location = $('#myanchor').attr('href');

Set auto height and width in CSS/HTML for different screen sizes

Using bootstrap with a little bit of customization, the following seems to work for me:

I need 3 partitions in my container and I tried this:

CSS:

.row.content {height: 100%; width:100%; position: fixed; }
.sidenav {
  padding-top: 20px;
  border: 1px solid #cecece;
  height: 100%;
}
.midnav {
  padding: 0px;
}

HTML:

  <div class="container-fluid text-center"> 
    <div class="row content">
    <div class="col-md-2 sidenav text-left">Some content 1</div>
    <div class="col-md-9 midnav text-left">Some content 2</div>
    <div class="col-md-1 sidenav text-center">Some content 3</div>
    </div>
  </div>

What are MVP and MVC and what is the difference?

The simplest answer is how the view interacts with the model. In MVP the view is updated by the presenter, which acts as as intermediary between the view and the model. The presenter takes the input from the view, which retrieves the data from the model and then performs any business logic required and then updates the view. In MVC the model updates the view directly rather than going back through the controller.

NuGet Package Restore Not Working

I have run into this problem in two scenarios.

First, when I attempt to build my solution from the command line using msbuild.exe. Secondly, when I attempt to build the sln and the containing projects on my build server using TFS and CI.

I get errors claiming that references are missing. When inspecting both my local build directory and the TFS server's I see that the /packages folder is not created, and the nuget packages are not copied over. Following the instructions listed in Alexandre's answer http://nuget.codeplex.com/workitem/1879 also did not work for me.

I've enabled Restore Packages via VS2010 and I have seen builds only work from within VS2010. Again, using msbuild fails.My workaround is probably totally invalid, but for my environment this got everything working from a command line build locally, as well as from a CI build in TFS.

I went into .\nuget and changed this line in the .nuget\NuGet.targets file:

from:

<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" -o "$(PackagesDir)"</RestoreCommand>

to: (notice, without the quotes around the variables)

<RestoreCommand>$(NuGetCommand) install $(PackagesConfig) -source $(PackageSources) -o $(PackagesDir)</RestoreCommand>

I understand that if my directories have spaces in them, this will fail, but I don't have spaces in my directories and so this workaround got my builds to complete successfully...for the time being.

I will say that turning on diagnostic level logging in your build will help show what commands are being executed by msbuild. This is what led me to hacking the targets file temporarily.

mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

?php

/* Database config */

$db_host        = 'localhost';
$db_user        = '~';
$db_pass        = '~';
$db_database    = 'banners'; 

/* End config */


$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

?>

How to refresh activity after changing language (Locale) inside application

Call this method to change app locale:

public void settingLocale(Context context, String language) {

    Locale locale;

    Configuration config = new Configuration();

     if(language.equals(LANGUAGE_ENGLISH)) {

        locale = new Locale("en");

        Locale.setDefault(locale);

        config.locale = locale;

    }else if(language.equals(LANGUAGE_ARABIC)){

        locale = new Locale("hi");

        Locale.setDefault(locale);

        config.locale = locale;

    }

    context.getResources().updateConfiguration(config, null);

    // Here again set the text on view to reflect locale change

    // and it will pick resource from new locale

    tv1.setText(R.string.one); //tv1 is textview in my activity

}

Note: Put your strings in value and values- folder.

How to display a "busy" indicator with jQuery?

You can just show / hide a gif, but you can also embed that to ajaxSetup, so it's called on every ajax request.

$.ajaxSetup({
    beforeSend:function(){
        // show gif here, eg:
        $("#loading").show();
    },
    complete:function(){
        // hide gif here, eg:
        $("#loading").hide();
    }
});

One note is that if you want to do an specific ajax request without having the loading spinner, you can do it like this:

$.ajax({
   global: false,
   // stuff
});

That way the previous $.ajaxSetup we did will not affect the request with global: false.

More details available at: http://api.jquery.com/jQuery.ajaxSetup

Regular Expressions: Search in list

You can create an iterator in Python 3.x or a list in Python 2.x by using:

filter(r.match, list)

To convert the Python 3.x iterator to a list, simply cast it; list(filter(..)).

Get startup type of Windows service using PowerShell

It is possible with PowerShell 4.

Get-Service *spool* | select name,starttype | ft -AutoSize

screenshot

Doctrine - How to print out the real sql, not just the prepared statement?

I have created a Doctrine2 Logger that does exactly this. It "hydrates" the parametrized sql query with the values using Doctrine 2 own data type conversors.

<?php


namespace Drsm\Doctrine\DBAL\Logging;
use Doctrine\DBAL\Logging\SQLLogger,
    Doctrine\DBAL\Types\Type,
    Doctrine\DBAL\Platforms\AbstractPlatform;
/**
 * A SQL logger that logs to the standard output and
 * subtitutes params to get a ready to execute SQL sentence

 * @author  [email protected]
 */
class EchoWriteSQLWithoutParamsLogger implements SQLLogger

{
    const QUERY_TYPE_SELECT="SELECT";
    const QUERY_TYPE_UPDATE="UPDATE";
    const QUERY_TYPE_INSERT="INSERT";
    const QUERY_TYPE_DELETE="DELETE";
    const QUERY_TYPE_CREATE="CREATE";
    const QUERY_TYPE_ALTER="ALTER";

    private $dbPlatform;
    private $loggedQueryTypes;
    public function __construct(AbstractPlatform $dbPlatform, array $loggedQueryTypes=array()){
        $this->dbPlatform=$dbPlatform;
        $this->loggedQueryTypes=$loggedQueryTypes;
    }
    /**
     * {@inheritdoc}
     */
    public function startQuery($sql, array $params = null, array $types = null)

    {
        if($this->isLoggable($sql)){
            if(!empty($params)){
                foreach ($params as $key=>$param) {
                    $type=Type::getType($types[$key]);
                    $value=$type->convertToDatabaseValue($param,$this->dbPlatform);
                    $sql = join(var_export($value, true), explode('?', $sql, 2));
                }

            }
            echo $sql . " ;".PHP_EOL;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function stopQuery()
    {

    }
    private function isLoggable($sql){
        if (empty($this->loggedQueryTypes)) return true;
        foreach($this->loggedQueryTypes as $validType){
            if (strpos($sql, $validType) === 0) return true;
        }
        return false;
    }
}

Usage Example:; The following peace of code will echo on standard output any INSERT,UPDATE,DELETE SQL sentences generated with $em Entity Manager,

/**@var  \Doctrine\ORM\EntityManager $em */
$em->getConnection()
                ->getConfiguration()
                ->setSQLLogger(
                    new EchoWriteSQLWithoutParamsLogger(
                        $em->getConnection()->getDatabasePlatform(),
                        array(
                            EchoWriteSQLWithoutParamsLogger::QUERY_TYPE_UPDATE,
                            EchoWriteSQLWithoutParamsLogger::QUERY_TYPE_INSERT,
                            EchoWriteSQLWithoutParamsLogger::QUERY_TYPE_DELETE
                        )
                    )
                );

Confirmation dialog on ng-click - AngularJS

I created a module for this very thing that relies on the Angular-UI $modal service.

https://github.com/Schlogen/angular-confirm

How does inline Javascript (in HTML) work?

There seems to be a lot of bad practice being thrown around Event Handler Attributes. Bad practice is not knowing and using available features where it is most appropriate. The Event Attributes are fully W3C Documented standards and there is nothing bad practice about them. It's no different than placing inline styles, which is also W3C Documented and can be useful in times. Whether you place it wrapped in script tags or not, it's gonna be interpreted the same way.

https://www.w3.org/TR/html5/webappapis.html#event-handler-idl-attributes

C error: Expected expression before int

{ } -->

defines scope, so if(a==1) { int b = 10; } says, you are defining int b, for {}- this scope. For

if(a==1)
  int b =10;

there is no scope. And you will not be able to use b anywhere.

How/when to generate Gradle wrapper files?

  1. You will generate them once, but update them if you need a new feature or something from a plugin which in turn needs a newer gradle version.

    Easiest way to update: as of Gradle 2.2 you can just download and extract the complete or binary Gradle distribution, and run:

    $ <pathToExpandedZip>/bin/gradle wrapper
    

    No need to define a task, though you probably need some kind of build.gradle file.

    This will update or create the gradlew and gradlew.bat wrapper as well as gradle/wrapper/gradle-wrapper.properties and the gradle-wrapper.jar to provide the current version of gradle, wrapped.

  2. Those are all part of the wrapper.

  3. Some build.gradle files reference other files or files in subdirectories which are sub projects or modules. It gets a bit complicated, but if you have one project you basically need the one file.

  4. settings.gradle handles project, module and other kinds of names and settings, gradle.properties configures resusable variables for your gradle files if you like and you feel they would be clearer that way.

gpg decryption fails with no secret key error

I got the same error when trying to decrypt the key from a different user account via su - <otherUser>. (Like jayhendren suggests in his answer)

In my case, this happened because there would normally start a graphical pinentry prompt so I could enter the password to decrypt the key, but the su -ed to user had no access to the (graphical) X-Window-System that was currently running.

The solution was to simply issue in that same console (as the user under which the X Server was currently running):

xhost +local:

Which gives other local users access to the currently running (local) X-Server. After that, the pinentry prompt appeared, I could enter the password to decrypt the key and it worked...

Of course you can also forward X over ssh connections. For this look into ssh's -X parameter (client side) and X11Forwarding yes (server side).

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

Are the shift operators (<<, >>) arithmetic or logical in C?

TL;DR

Consider i and n to be the left and right operands respectively of a shift operator; the type of i, after integer promotion, be T. Assuming n to be in [0, sizeof(i) * CHAR_BIT) — undefined otherwise — we've these cases:

| Direction  |   Type   | Value (i) | Result                   |
| ---------- | -------- | --------- | ------------------------ |
| Right (>>) | unsigned |    = 0    | -8 ? (i ÷ 2n)            |
| Right      | signed   |    = 0    | -8 ? (i ÷ 2n)            |
| Right      | signed   |    < 0    | Implementation-defined†  |
| Left  (<<) | unsigned |    = 0    | (i * 2n) % (T_MAX + 1)   |
| Left       | signed   |    = 0    | (i * 2n) ‡               |
| Left       | signed   |    < 0    | Undefined                |

† most compilers implement this as arithmetic shift
‡ undefined if value overflows the result type T; promoted type of i


Shifting

First is the difference between logical and arithmetic shifts from a mathematical viewpoint, without worrying about data type size. Logical shifts always fills discarded bits with zeros while arithmetic shift fills it with zeros only for left shift, but for right shift it copies the MSB thereby preserving the sign of the operand (assuming a two's complement encoding for negative values).

In other words, logical shift looks at the shifted operand as just a stream of bits and move them, without bothering about the sign of the resulting value. Arithmetic shift looks at it as a (signed) number and preserves the sign as shifts are made.

A left arithmetic shift of a number X by n is equivalent to multiplying X by 2n and is thus equivalent to logical left shift; a logical shift would also give the same result since MSB anyway falls off the end and there's nothing to preserve.

A right arithmetic shift of a number X by n is equivalent to integer division of X by 2n ONLY if X is non-negative! Integer division is nothing but mathematical division and round towards 0 (trunc).

For negative numbers, represented by two's complement encoding, shifting right by n bits has the effect of mathematically dividing it by 2n and rounding towards -8 (floor); thus right shifting is different for non-negative and negative values.

for X = 0, X >> n = X / 2n = trunc(X ÷ 2n)

for X < 0, X >> n = floor(X ÷ 2n)

where ÷ is mathematical division, / is integer division. Let's look at an example:

37)10 = 100101)2

37 ÷ 2 = 18.5

37 / 2 = 18 (rounding 18.5 towards 0) = 10010)2 [result of arithmetic right shift]

-37)10 = 11011011)2 (considering a two's complement, 8-bit representation)

-37 ÷ 2 = -18.5

-37 / 2 = -18 (rounding 18.5 towards 0) = 11101110)2 [NOT the result of arithmetic right shift]

-37 >> 1 = -19 (rounding 18.5 towards -8) = 11101101)2 [result of arithmetic right shift]

As Guy Steele pointed out, this discrepancy has led to bugs in more than one compiler. Here non-negative (math) can be mapped to unsigned and signed non-negative values (C); both are treated the same and right-shifting them is done by integer division.

So logical and arithmetic are equivalent in left-shifting and for non-negative values in right shifting; it's in right shifting of negative values that they differ.

Operand and Result Types

Standard C99 §6.5.7:

Each of the operands shall have integer types.

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behaviour is undefined.

short E1 = 1, E2 = 3;
int R = E1 << E2;

In the above snippet, both operands become int (due to integer promotion); if E2 was negative or E2 = sizeof(int) * CHAR_BIT then the operation is undefined. This is because shifting more than the available bits is surely going to overflow. Had R been declared as short, the int result of the shift operation would be implicitly converted to short; a narrowing conversion, which may lead to implementation-defined behaviour if the value is not representable in the destination type.

Left Shift

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1×2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and non-negative value, and E1×2E2 is representable in the result type, then that is the resulting value; otherwise, the behaviour is undefined.

As left shifts are the same for both, the vacated bits are simply filled with zeros. It then states that for both unsigned and signed types it's an arithmetic shift. I'm interpreting it as arithmetic shift since logical shifts don't bother about the value represented by the bits, it just looks at it as a stream of bits; but the standard talks not in terms of bits, but by defining it in terms of the value obtained by the product of E1 with 2E2.

The caveat here is that for signed types the value should be non-negative and the resulting value should be representable in the result type. Otherwise the operation is undefined. The result type would be the type of the E1 after applying integral promotion and not the destination (the variable which is going to hold the result) type. The resulting value is implicitly converted to the destination type; if it is not representable in that type, then the conversion is implementation-defined (C99 §6.3.1.3/3).

If E1 is a signed type with a negative value then the behaviour of left shifting is undefined. This is an easy route to undefined behaviour which may easily get overlooked.

Right Shift

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined.

Right shift for unsigned and signed non-negative values are pretty straight forward; the vacant bits are filled with zeros. For signed negative values the result of right shifting is implementation-defined. That said, most implementations like GCC and Visual C++ implement right-shifting as arithmetic shifting by preserving the sign bit.

Conclusion

Unlike Java, which has a special operator >>> for logical shifting apart from the usual >> and <<, C and C++ have only arithmetic shifting with some areas left undefined and implementation-defined. The reason I deem them as arithmetic is due to the standard wording the operation mathematically rather than treating the shifted operand as a stream of bits; this is perhaps the reason why it leaves those areas un/implementation-defined instead of just defining all cases as logical shifts.

Array of strings in groovy

Most of the time you would create a list in groovy rather than an array. You could do it like this:

names = ["lucas", "Fred", "Mary"]

Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:

names = "lucas Fred Mary".split()

Can't connect to MySQL server error 111

If all the previous answers didn't give any solution, you should check your user privileges.

If you could login as root to mysql then you should add this:

CREATE USER 'root'@'192.168.1.100' IDENTIFIED BY  '***';
GRANT ALL PRIVILEGES ON * . * TO  'root'@'192.168.1.100' IDENTIFIED BY  '***' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;

Then try to connect again using mysql -ubeer -pbeer -h192.168.1.100. It should work.

Compile c++14-code with g++

The -std=c++14 flag is not supported on GCC 4.8. If you want to use C++14 features you need to compile with -std=c++1y. Using godbolt.org it appears that the earilest version to support -std=c++14 is GCC 4.9.0 or Clang 3.5.0

Invalid default value for 'dateAdded'

Change the type from datetime to timestamp and it will work! I had the same issue for mysql 5.5.56-MariaDB - MariaDB Server Hope it can help... sorry if depricated

JQuery, setTimeout not working

This accomplishes the same thing but is much simpler:

$(document).ready(function() {  
   $("#board").delay(1000).append(".");
});

You can chain a delay before almost any jQuery method.

Django: Calling .update() on a single model instance retrieved by .get()?

I don't know how good or bad this is, but you can try something like this:

try:
    obj = Model.objects.get(id=some_id)
except Model.DoesNotExist:
    obj = Model.objects.create()
obj.__dict__.update(your_fields_dict) 
obj.save()

How to sanity check a date in Java

tl;dr

Use the strict mode on java.time.DateTimeFormatter to parse a LocalDate. Trap for the DateTimeParseException.

LocalDate.parse(                   // Represent a date-only value, without time-of-day and without time zone.
    "31/02/2000" ,                 // Input string.
    DateTimeFormatter              // Define a formatting pattern to match your input string.
    .ofPattern ( "dd/MM/uuuu" )
    .withResolverStyle ( ResolverStyle.STRICT )  // Specify leniency in tolerating questionable inputs.
)

After parsing, you might check for reasonable value. For example, a birth date within last one hundred years.

birthDate.isAfter( LocalDate.now().minusYears( 100 ) )

Avoid legacy date-time classes

Avoid using the troublesome old date-time classes shipped with the earliest versions of Java. Now supplanted by the java.time classes.

LocalDate & DateTimeFormatter & ResolverStyle

The LocalDate class represents a date-only value without time-of-day and without time zone.

String input = "31/02/2000";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd/MM/uuuu" );
try {
    LocalDate ld = LocalDate.parse ( input , f );
    System.out.println ( "ld: " + ld );
} catch ( DateTimeParseException e ) {
    System.out.println ( "ERROR: " + e );
}

The java.time.DateTimeFormatter class can be set to parse strings with any of three leniency modes defined in the ResolverStyle enum. We insert a line into the above code to try each of the modes.

f = f.withResolverStyle ( ResolverStyle.LENIENT );

The results:

  • ResolverStyle.LENIENT
    ld: 2000-03-02
  • ResolverStyle.SMART
    ld: 2000-02-29
  • ResolverStyle.STRICT
    ERROR: java.time.format.DateTimeParseException: Text '31/02/2000' could not be parsed: Invalid date 'FEBRUARY 31'

We can see that in ResolverStyle.LENIENT mode, the invalid date is moved forward an equivalent number of days. In ResolverStyle.SMART mode (the default), a logical decision is made to keep the date within the month and going with the last possible day of the month, Feb 29 in a leap year, as there is no 31st day in that month. The ResolverStyle.STRICT mode throws an exception complaining that there is no such date.

All three of these are reasonable depending on your business problem and policies. Sounds like in your case you want the strict mode to reject the invalid date rather than adjust it.


Table of all date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Calling filter returns <filter object at ... >

It's an iterator returned by the filter function.

If you want a list, just do

list(filter(f, range(2, 25)))

Nonetheless, you can just iterate over this object with a for loop.

for e in filter(f, range(2, 25)):
    do_stuff(e)

Calculate difference between 2 date / times in Oracle SQL

select 
    extract( day from diff ) Days, 
    extract( hour from diff ) Hours, 
    extract( minute from diff ) Minutes 
from (
        select (CAST(creationdate as timestamp) - CAST(oldcreationdate as timestamp)) diff   
        from [TableName] 
     );

This will give you three columns as Days, Hours and Minutes.

How to get the start time of a long-running Linux process?

The ps command (at least the procps version used by many Linux distributions) has a number of format fields that relate to the process start time, including lstart which always gives the full date and time the process started:

# ps -p 1 -wo pid,lstart,cmd
  PID                  STARTED CMD
    1 Mon Dec 23 00:31:43 2013 /sbin/init

# ps -p 1 -p $$ -wo user,pid,%cpu,%mem,vsz,rss,tty,stat,lstart,cmd
USER       PID %CPU %MEM    VSZ   RSS TT       STAT                  STARTED CMD
root         1  0.0  0.1   2800  1152 ?        Ss   Mon Dec 23 00:31:44 2013 /sbin/init
root      5151  0.3  0.1   4732  1980 pts/2    S    Sat Mar  8 16:50:47 2014 bash

For a discussion of how the information is published in the /proc filesystem, see https://unix.stackexchange.com/questions/7870/how-to-check-how-long-a-process-has-been-running

(In my experience under Linux, the time stamp on the /proc/ directories seem to be related to a moment when the virtual directory was recently accessed rather than the start time of the processes:

# date; ls -ld /proc/1 /proc/$$ 
Sat Mar  8 17:14:21 EST 2014
dr-xr-xr-x 7 root root 0 2014-03-08 16:50 /proc/1
dr-xr-xr-x 7 root root 0 2014-03-08 16:51 /proc/5151

Note that in this case I ran a "ps -p 1" command at about 16:50, then spawned a new bash shell, then ran the "ps -p 1 -p $$" command within that shell shortly afterward....)

Javascript change date into format of (dd/mm/yyyy)

This will ensure you get a two-digit day and month.

function formattedDate(d = new Date) {
  let month = String(d.getMonth() + 1);
  let day = String(d.getDate());
  const year = String(d.getFullYear());

  if (month.length < 2) month = '0' + month;
  if (day.length < 2) day = '0' + day;

  return `${day}/${month}/${year}`;
}

Or terser:

function formattedDate(d = new Date) {
  return [d.getDate(), d.getMonth()+1, d.getFullYear()]
      .map(n => n < 10 ? `0${n}` : `${n}`).join('/');
}

Creating an empty file in C#

Path.GetTempFileName() will create a uniquly named empty file and return the path to it.

If you want to control the path but get a random file name you can use GetRandomFileName to just return a file name string and use it with Create

For example:

string fileName=Path.GetRandomFileName();
File.Create("custom\\path\\" + fileName);

Data binding to SelectedItem in a WPF Treeview

My requirement was for PRISM-MVVM based solution where a TreeView was needed and the bound object is of type Collection<> and hence needs HierarchicalDataTemplate. The default BindableSelectedItemBehavior wont be able to identify the child TreeViewItem. To make it to work in this scenario.

public class BindableSelectedItemBehavior : Behavior<TreeView>
{
    #region SelectedItem Property

    public object SelectedItem
    {
        get { return (object)GetValue(SelectedItemProperty); }
        set { SetValue(SelectedItemProperty, value); }
    }

    public static readonly DependencyProperty SelectedItemProperty =
        DependencyProperty.Register("SelectedItem", typeof(object), typeof(BindableSelectedItemBehavior), new UIPropertyMetadata(null, OnSelectedItemChanged));

    private static void OnSelectedItemChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var behavior = sender as BindableSelectedItemBehavior;
        if (behavior == null) return;
        var tree = behavior.AssociatedObject;
        if (tree == null) return;
        if (e.NewValue == null)
            foreach (var item in tree.Items.OfType<TreeViewItem>())
                item.SetValue(TreeViewItem.IsSelectedProperty, false);
        var treeViewItem = e.NewValue as TreeViewItem;
        if (treeViewItem != null)
            treeViewItem.SetValue(TreeViewItem.IsSelectedProperty, true);
        else
        {
            var itemsHostProperty = tree.GetType().GetProperty("ItemsHost", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            if (itemsHostProperty == null) return;
            var itemsHost = itemsHostProperty.GetValue(tree, null) as Panel;
            if (itemsHost == null) return;
            foreach (var item in itemsHost.Children.OfType<TreeViewItem>())
            {
                if (WalkTreeViewItem(item, e.NewValue)) 
                    break;
            }
        }
    }

    public static bool WalkTreeViewItem(TreeViewItem treeViewItem, object selectedValue)
    {
        if (treeViewItem.DataContext == selectedValue)
        {
            treeViewItem.SetValue(TreeViewItem.IsSelectedProperty, true);
            treeViewItem.Focus();
            return true;
        }
        var itemsHostProperty = treeViewItem.GetType().GetProperty("ItemsHost", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        if (itemsHostProperty == null) return false;
        var itemsHost = itemsHostProperty.GetValue(treeViewItem, null) as Panel;
        if (itemsHost == null) return false;
        foreach (var item in itemsHost.Children.OfType<TreeViewItem>())
        {
            if (WalkTreeViewItem(item, selectedValue))
                break;
        }
        return false;
    }
    #endregion

    protected override void OnAttached()
    {
        base.OnAttached();
        this.AssociatedObject.SelectedItemChanged += OnTreeViewSelectedItemChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        if (this.AssociatedObject != null)
        {
            this.AssociatedObject.SelectedItemChanged -= OnTreeViewSelectedItemChanged;
        }
    }

    private void OnTreeViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        this.SelectedItem = e.NewValue;
    }
}

This enables to iterate through all the elements irrespective of the level.

Hiding table data using <div style="display:none">

Yes, you can hide only the rows that you want to hide. This can be helpful if you want to show rows only when some condition is satisfied in the rows that are currently being shown. The following worked for me.

<table>
  <tr><th>Sample Table</th></tr>  
  <tr id="row1">
    <td><input id="data1" type="text" name="data1" /></td>
  </tr>
 <tr id="row2" style="display: none;">
    <td><input id="data2" type="text" name="data2" /></td>
 </tr>
 <tr id="row3" style="display: none;">
    <td><input id="data3" type="text" name="data3" /></td>
 </tr>
</table>

In CSS, do the following:

#row2{
    display: none;
}

#row3{
    display: none;
}

In JQuery, you might have something like the following to show the desired rows.

$(document).ready(function(){
    if($("#row1").val() === "sometext"){  //your desired condition
        $("#row2").show();
    }

    if($("#row2").val() !== ""){   //your desired condition
        $("#row3").show();
    }
});

GitHub: invalid username or password

https://[email protected]/eurydyce/MDANSE.git is not an ssh url, it is an https one (which would require your GitHub account name, instead of 'git').

Try to use ssh://[email protected]:eurydyce/MDANSE.git or just [email protected]:eurydyce/MDANSE.git

git remote set-url origin [email protected]:eurydyce/MDANSE.git

The OP Pellegrini Eric adds:

That's what I did in my ~/.gitconfig file that contains currently the following entries [remote "origin"] [email protected]:eurydyce/MDANSE.git

This should not be in your global config (the one in ~/).
You could check git config -l in your repo: that url should be declared in the local config: <yourrepo>/.git/config.

So make sure you are in the repo path when doing the git remote set-url command.


As noted in Oliver's answer, an HTTPS URL would not use username/password if two-factor authentication (2FA) is activated.

In that case, the password should be a PAT (personal access token) as seen in "Using a token on the command line".

That applies only for HTTPS URLS, SSH is not affected by this limitation.

CSS/Javascript to force html table row on a single line

If you hide the overflow and there is a long word, you risk loosing that word, so you could go one step further and use the "word-wrap" css attribute.

http://msdn.microsoft.com/en-us/library/ms531186(VS.85).aspx

How can I change or remove HTML5 form validation default error messages?

you can change them via constraint validation api: http://www.w3.org/TR/html5/constraints.html#dom-cva-setcustomvalidity

if you want an easy solution, you can rock out civem.js, Custom Input Validation Error Messages JavaScript lib download here: https://github.com/javanto/civem.js live demo here: http://jsfiddle.net/hleinone/njSbH/

window.close() doesn't work - Scripts may close only the windows that were opened by it

Error messages don't get any clearer than this:

"Scripts may close only the windows that were opened by it."

If your script did not initiate opening the window (with something like window.open), then the script in that window is not allowed to close it. Its a security to prevent a website taking control of your browser and closing windows.

“tag already exists in the remote" error after recreating the git tag

Some good answers here. Especially the one by @torek. I thought I'd add this work-around with a little explanation for those in a rush.

To summarize, what happens is that when you move a tag locally, it changes the tag from a non-Null commit value to a different value. However, because git (as a default behavior) doesn't allow changing non-Null remote tags, you can't push the change.

The work-around is to delete the tag (and tick remove all remotes). Then create the same tag and push.

Count all values in a matrix greater than a value

The numpy.where function is your friend. Because it's implemented to take full advantage of the array datatype, for large images you should notice a speed improvement over the pure python solution you provide.

Using numpy.where directly will yield a boolean mask indicating whether certain values match your conditions:

>>> data
array([[1, 8],
       [3, 4]])
>>> numpy.where( data > 3 )
(array([0, 1]), array([1, 1]))

And the mask can be used to index the array directly to get the actual values:

>>> data[ numpy.where( data > 3 ) ]
array([8, 4])

Exactly where you take it from there will depend on what form you'd like the results in.

Open Bootstrap Modal from code-behind

By default Bootstrap javascript files are included just before the closing body tag

        <script src="vendors/jquery-1.9.1.min.js"></script>
        <script src="bootstrap/js/bootstrap.min.js"></script>
        <script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
        <script src="assets/scripts.js"></script>
 </body>

I took these javascript files into the head section right before the body tag and I wrote a small function to call the modal popup:

    <script src="vendors/jquery-1.9.1.min.js"></script>
    <script src="bootstrap/js/bootstrap.min.js"></script>
    <script src="vendors/easypiechart/jquery.easy-pie-chart.js"></script>
    <script src="assets/scripts.js"></script>

 <script type="text/javascript">
    function openModal() {
        $('#myModal').modal('show');
    }
</script>
</head>
<body>

then I could call the modal popup from code-behind with the following:

protected void lbEdit_Click(object sender, EventArgs e) {   
      ScriptManager.RegisterStartupScript(this,this.GetType(),"Pop", "openModal();", true);
}

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):

    bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
    bbox = mtransforms.Bbox.union(bboxes)
    bottom = bbox.y0
    x, y = self.label.get_position()
    self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))

You can set the label position independently of the ticks by using:

    ax.xaxis.set_label_coords(x0, y0)

that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.

C# - Making a Process.Start wait until the process has start-up

I used the EventWaitHandle class. On the parent process, create a named EventWaitHandle with initial state of the event set to non-signaled. The parent process blocks until the child process calls the Set method, changing the state of the event to signaled, as shown below.

Parent Process:

using System;
using System.Threading;
using System.Diagnostics;

namespace MyParentProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            EventWaitHandle ewh = null;
            try
            {
                ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "CHILD_PROCESS_READY");

                Process process = Process.Start("MyChildProcess.exe", Process.GetCurrentProcess().Id.ToString());
                if (process != null)
                {
                    if (ewh.WaitOne(10000))
                    {
                        // Child process is ready.
                    }
                }
            }
            catch(Exception exception)
            { }
            finally
            {
                if (ewh != null)
                    ewh.Close();
            }
        }
    }
}

Child Process:

using System;
using System.Threading;
using System.Diagnostics;

namespace MyChildProcess
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Representing some time consuming work.
                Thread.Sleep(5000);

                EventWaitHandle.OpenExisting("CHILD_PROCESS_READY")
                    .Set();

                Process.GetProcessById(Convert.ToInt32(args[0]))
                    .WaitForExit();
            }
            catch (Exception exception)
            { }
        }
    }
}

CFLAGS vs CPPFLAGS

The CPPFLAGS macro is the one to use to specify #include directories.

Both CPPFLAGS and CFLAGS work in your case because the make(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).

You don't need to specify . as an include-directory if you use the form #include "...". You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.

Why do I need to configure the SQL dialect of a data source?

A dialect is a form of the language that is spoken by a particular group of people.

Here, in context of hibernate framework, When hibernate wants to talk(using queries) with the database it uses dialects.

The SQL dialect's are derived from the Structured Query Language which uses human-readable expressions to define query statements.
A hibernate dialect gives information to the framework of how to convert hibernate queries(HQL) into native SQL queries.

The dialect of hibernate can be configured using below property:

hibernate.dialect

Here, is a complete list of hibernate dialects.

Note: The dialect property of hibernate is not mandatory.

htaccess Access-Control-Allow-Origin

Add an .htaccess file with the following directives to your fonts folder, if have problems accessing your fonts. Can easily be modified for use with .css or .js files.

<FilesMatch "\.(eot|ttf|otf|woff)$">
    Header set Access-Control-Allow-Origin "*"
</FilesMatch>

How do I detect IE 8 with jQuery?

Note:

1) $.browser appears to be dropped in jQuery 1.9+ (as noted by Mandeep Jain). It is recommended to use .support instead.

2) $.browser.version can return "7" in IE >7 when the browser is in "compatibility" mode.

3) As of IE 10, conditional comments will no longer work.

4) jQuery 2.0+ will drop support for IE 6/7/8

5) document.documentMode appears to be defined only in Internet Explorer 8+ browsers. The value returned will tell you in what "compatibility" mode Internet Explorer is running. Still not a good solution though.

I tried numerous .support() options, but it appears that when an IE browser (9+) is in compatibility mode, it will simply behave like IE 7 ... :(

So far I only found this to work (kind-a):

(if documentMode is not defined and htmlSerialize and opacity are not supported, then you're very likely looking at IE <8 ...)

if(!document.documentMode && !$.support.htmlSerialize && !$.support.opacity) 
{
    // IE 6/7 code
}

If statement in aspx page

if the purpose is to show or hide a part of the page then you can do the following things

1) wrap it in markup with

<% if(somecondition) { %>
   some html
<% } %>

2) Wrap the parts in a Panel control and in codebehind use the if statement to set the Visible property of the Panel.

jQuery - Dynamically Create Button and Attach Event Handler

Calling .html() serializes the element to a string, so all event handlers and other associated data is lost. Here's how I'd do it:

$("#myButton").click(function ()
{
    var test = $('<button/>',
    {
        text: 'Test',
        click: function () { alert('hi'); }
    });

    var parent = $('<tr><td></td></tr>').children().append(test).end();

    $("#addNodeTable tr:last").before(parent);
});

Or,

$("#myButton").click(function ()
{    
    var test = $('<button/>',
    {
        text: 'Test',
        click: function () { alert('hi'); }
    }).wrap('<tr><td></td></tr>').closest('tr');

    $("#addNodeTable tr:last").before(test);
});

If you don't like passing a map of properties to $(), you can instead use

$('<button/>')
    .text('Test')
    .click(function () { alert('hi'); });

// or

$('<button>Test</button>').click(function () { alert('hi'); });

NSRange to Range<String.Index>

In the accepted answer I find the optionals cumbersome. This works with Swift 3 and seems to have no problem with emojis.

func textField(_ textField: UITextField, 
      shouldChangeCharactersIn range: NSRange, 
      replacementString string: String) -> Bool {

  guard let value = textField.text else {return false} // there may be a reason for returning true in this case but I can't think of it
  // now value is a String, not an optional String

  let valueAfterChange = (value as NSString).replacingCharacters(in: range, with: string)
  // valueAfterChange is a String, not an optional String

  // now do whatever processing is required

  return true  // or false, as required
}

How to resize datagridview control when form resizes

Set the property of your DataGridView:

Anchor: Top,Left
AutoSizeColumn: Fill
Dock: Fill

git diff between two different files

If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"

How to indent a few lines in Markdown markup?

Use a no-break space directly   (not the same as !).

(You could insert HTML or some esoteric markdown code, but I can think of better reasons to break compatibility with standard markdown.)

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Another approach is below. This will take care of pasting also. [it is for alpha-numeric validation]

//Input Validation
var existingLogDescription = "";

$('.logDescription').keydown(function (event) {
    existingLogDescription = this.value;

});


$('.logDescription').keyup(function () {
    if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
        alert("Log Description should contain alpha-numeric values only");
        this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
        this.value = existingLogDescription;
    }
});

isset in jQuery?

You can simply use this:

if ($("#one")){
   alert('yes');
}

if ($("#two")){
   alert('yes');
}

if ($("#three")){
   alert('yes');
}

if ($("#four")){
   alert('no');
}

Sorry, my mistake, it does not work.

Regex to validate date format dd/mm/yyyy

The regex you pasted does not validate leap years correctly, but there is one that does in the same post. I modified it to take dd/mm/yyyy, dd-mm-yyyy or dd.mm.yyyy.

^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

I tested it a bit in the link Arun provided in his answer and also here and it seems to work.

Edit February 14th 2019: I've removed a comma that was in the regex which allowed dates like 29-0,-11

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

How to reproduce this error with as few lines as possible:

>>> class C:
...   def f(self):
...     print "hi"
...
>>> C.f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with C instance as 
first argument (got nothing instead)

It fails because of TypeError because you didn't instantiate the class first, you have two choices: 1: either make the method static so you can run it in a static way, or 2: instantiate your class so you have an instance to grab onto, to run the method.

It looks like you want to run the method in a static way, do this:

>>> class C:
...   @staticmethod
...   def f():
...     print "hi"
...
>>> C.f()
hi

Or, what you probably meant is to use the instantiated instance like this:

>>> class C:
...   def f(self):
...     print "hi"
...
>>> c1 = C()
>>> c1.f()
hi
>>> C().f()
hi

If this confuses you, ask these questions:

  1. What is the difference between the behavior of a static method vs the behavior of a normal method?
  2. What does it mean to instantiate a class?
  3. Differences between how static methods are run vs normal methods.
  4. Differences between class and object.

Best way to handle list.index(might-not-exist) in python?

If you are doing this often then it is better to stove it away in a helper function:

def index_of(val, in_list):
    try:
        return in_list.index(val)
    except ValueError:
        return -1 

Pass element ID to Javascript function

The problem for me was as simple as just not knowing Javascript well. I was trying to pass the name of the id using double quotes, when I should have been using single. And it worked fine.

This worked:

validateSelectizeDropdown('#PartCondition')

This did not:

validateSelectizeDropdown("#PartCondition")

And the function:

    function validateSelectizeDropdown(name) {
    if ($(name).val() === "") {
         //do something
    }
}

Writing data into CSV file in C#

Writing csv files by hand can be difficult because your data might contain commas and newlines. I suggest you use an existing library instead.

This question mentions a few options.

Are there any CSV readers/writer libraries in C#?

Can anonymous class implement interface?

Another option is to create a single, concrete implementing class that takes lambdas in the constructor.

public interface DummyInterface
{
    string A { get; }
    string B { get; }
}

// "Generic" implementing class
public class Dummy : DummyInterface
{
    private readonly Func<string> _getA;
    private readonly Func<string> _getB;

    public Dummy(Func<string> getA, Func<string> getB)
    {
        _getA = getA;
        _getB = getB;
    }

    public string A => _getA();

    public string B => _getB();
}

public class DummySource
{
    public string A { get; set; }
    public string C { get; set; }
    public string D { get; set; }
}

public class Test
{
    public void WillThisWork()
    {
        var source = new DummySource[0];
        var values = from value in source
                     select new Dummy // Syntax changes slightly
                     (
                         getA: () => value.A,
                         getB: () => value.C + "_" + value.D
                     );

        DoSomethingWithDummyInterface(values);

    }

    public void DoSomethingWithDummyInterface(IEnumerable<DummyInterface> values)
    {
        foreach (var value in values)
        {
            Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);
        }
    }
}

If all you are ever going to do is convert DummySource to DummyInterface, then it would be simpler to just have one class that takes a DummySource in the constructor and implements the interface.

But, if you need to convert many types to DummyInterface, this is much less boiler plate.

Disable webkit's spin buttons on input type="number"?

I discovered that there is a second portion of the answer to this.

The first portion helped me, but I still had a space to the right of my type=number input. I had zeroed out the margin on the input, but apparently I had to zero out the margin on the spinner as well.

This fixed it:

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

try/catch blocks with async/await

Alternative Similar To Error Handling In Golang

Because async/await uses promises under the hood, you can write a little utility function like this:

export function catchEm(promise) {
  return promise.then(data => [null, data])
    .catch(err => [err]);
}

Then import it whenever you need to catch some errors, and wrap your async function which returns a promise with it.

import catchEm from 'utility';

async performAsyncWork() {
  const [err, data] = await catchEm(asyncFunction(arg1, arg2));
  if (err) {
    // handle errors
  } else {
    // use data
  }
}

How to run a program without an operating system?

Operating System as the inspiration

The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).

For example, this page can be used as a starting point:

How to write a simple operating system

Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!

Such or similar simple OS can be used to create a simple framework that will allow us:

make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.

There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.

Boot Loader as the inspiration

Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:

How to develop your own Boot Loader

The above article presents also the basic architecture of such a programs:

  1. Correct loading to the memory by 0000:7C00 address.
  2. Calling the BootMain function that is developed in the high-level language.
  3. Show “”Hello, world…”, from low-level” message on the display.

As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.

In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:

to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.

The article shows also how to see the created program in action and how to perform its testing and debug.

UEFI applications as the inspiration

The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:

Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.

A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.

If we would like to start creating such programs, we can, for example, start with these websites:

Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps

Exploring security issues as the inspiration

It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.

A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:

There are at least four known BIOS attack viruses, two of which were for demonstration purposes.

or perhaps another one too.

Attacks before system startup

Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.

Different ways to boot

I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:

What Is Network Booting (PXE) and How Can You Use It?

Transparent background on winforms?

Should it have anything to do with "opacity" of the form / its background ? Did you try opacity = 0

Also see if this CP article helps:

Split Java String by New Line

String lines[] =String.split( System.lineSeparator())

static function in C

pmg is spot on about encapsulation; beyond hiding the function from other translation units (or rather, because of it), making functions static can also confer performance benefits in the presence of compiler optimizations.

Because a static function cannot be called from anywhere outside of the current translation unit (unless the code takes a pointer to its address), the compiler controls all the call points into it.

This means that it is free to use a non-standard ABI, inline it entirely, or perform any number of other optimizations that might not be possible for a function with external linkage.

C# Help reading foreign characters using StreamReader

I had the same problem and my solution was simple: instead of

Encoding.ASCII

use

Encoding.GetEncoding("iso-8859-1")

The answer was found here.

Edit: more solutions. This maybe more accurate one:

Encoding.GetEncoding(1252);

Also, in some cases this will work for you too if your OS default encoding matches file encoding:

Encoding.Default;

JavaScript/jQuery - How to check if a string contain specific words

In javascript the includes() method can be used to determines whether a string contains particular word (or characters at specified position). Its case sensitive.

var str = "Hello there."; 

var check1 = str.includes("there"); //true
var check2 = str.includes("There"); //false, the method is case sensitive
var check3 = str.includes("her");   //true
var check4 = str.includes("o",4);   //true, o is at position 4 (start at 0)
var check5 = str.includes("o",6);   //false o is not at position 6

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

Make sure your files are open from the relevant project, not from another (old) one.

Example:

  • You working on a project, close the VS, but you left files (tabs) open in VS.

  • Copy your project to a new folder and open solution. The files (tabs) will load from the old directory and if you want to debug then you cannot debug until you close them and reload them from the current folder.

I was very close to reinstall my VS because nothing helped for me from another answers, but fortunately I realised this in my project and I can debug now.

IN Clause with NULL or IS NULL

Your query fails due to operator precedence. AND binds before OR!
You need a pair of parentheses, which is not a matter of "clarity", but pure logic necessity.

SELECT *
FROM   tbl_name
WHERE  other_condition = bar
AND    another_condition = foo
AND   (id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL);

The added parentheses prevent AND binding before OR. If there were no other WHERE conditions (no AND) you would not need additional parentheses. The accepted answer is misleading in this respect.

How to Write text file Java

I think your expectations and reality don't match (but when do they ever ;))

Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if statement ;))

public class TestWriteFile {

    public static void main(String[] args) {
        BufferedWriter writer = null;
        try {
            //create a temporary file
            String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
            File logFile = new File(timeLog);

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());

            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write("Hello world!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e) {
            }
        }
    }
}

Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:

writer = new BufferedWriter(new FileWriter(logFile, true));

How to check if a file contains a specific string using Bash

##To check for a particular  string in a file

cd PATH_TO_YOUR_DIRECTORY #Changing directory to your working directory
File=YOUR_FILENAME  
if grep -q STRING_YOU_ARE_CHECKING_FOR "$File"; ##note the space after the string you are searching for
then
echo "Hooray!!It's available"
else
echo "Oops!!Not available"
fi

Readably print out a python dict() sorted by key

The Python pprint module actually already sorts dictionaries by key. In versions prior to Python 2.5, the sorting was only triggered on dictionaries whose pretty-printed representation spanned multiple lines, but in 2.5.X and 2.6.X, all dictionaries are sorted.

Generally, though, if you're writing data structures to a file and want them human-readable and writable, you might want to consider using an alternate format like YAML or JSON. Unless your users are themselves programmers, having them maintain configuration or application state dumped via pprint and loaded via eval can be a frustrating and error-prone task.

How to get CSS to select ID that begins with a string (not in Javascript)?

[id^=product]

^= indicates "starts with". Conversely, $= indicates "ends with".

The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

See the specs for full information.

define() vs. const

Yes, const are defined at compile-time and as nikic states cannot be assigned an expression, as define()'s can. But also const's cannot be conditionally declared (for the same reason). ie. You cannot do this:

if (/* some condition */) {
  const WHIZZ = true;  // CANNOT DO THIS!
}

Whereas you could with a define(). So, it doesn't really come down to personal preference, there is a correct and a wrong way to use both.

As an aside... I would like to see some kind of class const that can be assigned an expression, a sort of define() that can be isolated to classes?

How to select the last column of dataframe

The question is: how to select the last column of a dataframe ? Appart @piRSquared, none answer the question.

the simplest way to get a dataframe with the last column is:

df.iloc[ :, -1:]

Explicitly select items from a list or tuple

list( myBigList[i] for i in [87, 342, 217, 998, 500] )

I compared the answers with python 2.5.2:

  • 19.7 usec: [ myBigList[i] for i in [87, 342, 217, 998, 500] ]

  • 20.6 usec: map(myBigList.__getitem__, (87, 342, 217, 998, 500))

  • 22.7 usec: itemgetter(87, 342, 217, 998, 500)(myBigList)

  • 24.6 usec: list( myBigList[i] for i in [87, 342, 217, 998, 500] )

Note that in Python 3, the 1st was changed to be the same as the 4th.


Another option would be to start out with a numpy.array which allows indexing via a list or a numpy.array:

>>> import numpy
>>> myBigList = numpy.array(range(1000))
>>> myBigList[(87, 342, 217, 998, 500)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> myBigList[[87, 342, 217, 998, 500]]
array([ 87, 342, 217, 998, 500])
>>> myBigList[numpy.array([87, 342, 217, 998, 500])]
array([ 87, 342, 217, 998, 500])

The tuple doesn't work the same way as those are slices.

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

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

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

using namespace std;

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

    tmp_s.reserve(len);

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

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

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

In smarty there is built in modifier you could use that by using | (single pipeline operator). Like this {$varname|@print_r} will print value as print_r($php_variable)

How do you properly use namespaces in C++?

I prefer using a top-level namespace for the application and sub namespaces for the components.

The way you can use classes from other namespaces is surprisingly very similar to the way in java. You can either use "use NAMESPACE" which is similar to an "import PACKAGE" statement, e.g. use std. Or you specify the package as prefix of the class separated with "::", e.g. std::string. This is similar to "java.lang.String" in Java.

Get AVG ignoring Null or Zero values

In Case of not considering '0' or 'NULL' in average function. Simply use

AVG(NULLIF(your_column_name,0))

Euclidean distance of two vectors

As defined on Wikipedia, this should do it.

euc.dist <- function(x1, x2) sqrt(sum((x1 - x2) ^ 2))

There's also the rdist function in the fields package that may be useful. See here.


EDIT: Changed ** operator to ^. Thanks, Gavin.

1052: Column 'id' in field list is ambiguous

The simplest solution is a join with USING instead of ON. That way, the database "knows" that both id columns are actually the same, and won't nitpick on that:

SELECT id, name, section
  FROM tbl_names
  JOIN tbl_section USING (id)

If id is the only common column name in tbl_names and tbl_section, you can even use a NATURAL JOIN:

SELECT id, name, section
  FROM tbl_names
  NATURAL JOIN tbl_section

See also: https://dev.mysql.com/doc/refman/5.7/en/join.html

Understanding passport serialize deserialize

  1. Where does user.id go after passport.serializeUser has been called?

The user id (you provide as the second argument of the done function) is saved in the session and is later used to retrieve the whole object via the deserializeUser function.

serializeUser determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}

  1. We are calling passport.deserializeUser right after it where does it fit in the workflow?

The first argument of deserializeUser corresponds to the key of the user object that was given to the done function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc). In deserializeUser that key is matched with the in memory array / database or any data resource.

The fetched object is attached to the request object as req.user

Visual Flow

passport.serializeUser(function(user, done) {
    done(null, user.id);
});              ¦
                 ¦ 
                 ¦
                 +--------------------? saved to session
                                   ¦    req.session.passport.user = {id: '..'}
                                   ¦
                                   ?           
passport.deserializeUser(function(id, done) {
                   +---------------+
                   ¦
                   ? 
    User.findById(id, function(err, user) {
        done(err, user);
    });            +--------------? user object attaches to the request as req.user   
});

How do I use su to execute the rest of the bash script as that user?

It's not possible to change user within a shell script. Workarounds using sudo described in other answers are probably your best bet.

If you're mad enough to run perl scripts as root, you can do this with the $< $( $> $) variables which hold real/effective uid/gid, e.g.:

#!/usr/bin/perl -w
$user = shift;
if (!$<) {
    $> = getpwnam $user;
    $) = getgrnam $user;
} else {
    die 'must be root to change uid';
}
system('whoami');

What are the differences between a superkey and a candidate key?

Superkey :A set of attributes or combination of attributes which uniquely identify the tuple in a given relation . Superkey have two properties uniqueness and reducible set

Candidate key: Minimal set of superkey which have following two properties: uniqueness and irreducible set or attribute

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.

How to "scan" a website (or page) for info, and bring it into my program?

You could also try jARVEST.

It is based on a JRuby DSL over a pure-Java engine to spider-scrape-transform web sites.

Example:

Find all links inside a web page (wget and xpath are constructs of the jARVEST's language):

wget | xpath('//a/@href')

Inside a Java program:

Jarvest jarvest = new Jarvest();
  String[] results = jarvest.exec(
    "wget | xpath('//a/@href')", //robot! 
    "http://www.google.com" //inputs
  );
  for (String s : results){
    System.out.println(s);
  }

Reading file using relative path in python project

This worked for me.

with open('data/test.csv') as f:

 

How to obtain a QuerySet of all rows, with specific fields for each one of them?

Oskar Persson's answer is the best way to handle it because makes it easier to pass the data to the context and treat it normally from the template as we get the object instances (easily iterable to get props) instead of a plain value list.

After that you can just easily get the wanted prop:

for employee in employees:
    print(employee.eng_name)

Or in the template:

{% for employee in employees %}

    <p>{{ employee.eng_name }}</p>

{% endfor %}

sorting a List of Map<String, String>

@Test
public void testSortedMaps() {
    Map<String, String> map1 = new HashMap<String, String>();
    map1.put("name", "Josh");

    Map<String, String> map2 = new HashMap<String, String>();
    map2.put("name", "Anna");

    Map<String, String> map3 = new HashMap<String, String>();
    map3.put("name", "Bernie");

    List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
    mapList.add(map1);
    mapList.add(map2);
    mapList.add(map3);

    Collections.sort(mapList, new Comparator<Map<String, String>>() {
        public int compare(final Map<String, String> o1, final Map<String, String> o2) {
            return o1.get("name").compareTo(o2.get("name"));
        }
    });

    Assert.assertEquals("Anna", mapList.get(0).get("name"));
    Assert.assertEquals("Bernie", mapList.get(1).get("name"));
    Assert.assertEquals("Josh", mapList.get(2).get("name"));

}

SQL Developer with JDK (64 bit) cannot find JVM

I was trying to use the sqldeveloper that comes with the Oracle installation under:

C:\oracle\product\11.2.0\dbhome_1\sqldeveloper

I tried most of the suggestions in this post to no avail, so I downloaded the one from oracle's download page (you must register) which asks for the location of the jdk folder (rather than the location of java.exe). This worked for me without any problems.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

you need to specify the min and target sdk version in the manifest file.
If not the android.permission.READ_PHONE_STATE will be added automaticly while exporting your apk file.

<uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="19" />

How to give a delay in loop execution using Qt

So this question is nearly 10 years old, but it popped up on one of my searches, and I think that there are better solutions when programming in Qt: Signals & slots, timers, and finite state machines. The delays that are required can be implemented without sleeping the application in a way that interrupts other functions, and without concurrent programming and without spinning the processor - the Qt application will sleep when there are no events to process.

A hack for this is to have a sequence of timers with their timeout() signal connected to the slot for the event, which then kicks off the second timer. This is nice because it is simple. It's not so nice because it quickly becomes difficult to troubleshoot and maintain if there are logical branches, which there generally will be outside of any toy example.

QTimer

A better, more flexible option is the State Machine infrastructure within Qt. There you can configure an framework for an arbitrary sequence of events with multiple states and branches. An FSM is much easier to define, expand and maintain over time.

Qt State Machine

Auto-increment on partial primary key with Entity Framework Core

First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:

make sure you have correclty set the keys

modelBuilder.Entity<Foo>()
            .HasKey(p => new { p.Name, p.Id });
modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

OR you can achieve it using data annotation as well

public class Foo
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key, Column(Order = 0)]
    public int Id { get; set; }

    [Key, Column(Order = 1)]
    public string Name{ get; set; }
}

Is there a REAL performance difference between INT and VARCHAR primary keys?

I faced the same dilemma. I made a DW (Constellation schema) with 3 fact tables, Road Accidents, Vehicles in Accidents and Casualties in Accidents. Data includes all accidents recorded in UK from 1979 to 2012, and 60 dimension tables. All together, about 20 million records.

Fact tables relationships:

+----------+          +---------+
| Accident |>--------<| Vehicle |
+-----v----+ 1      * +----v----+
     1|                    |1
      |    +----------+    |
      +---<| Casualty |>---+
         * +----------+ *

RDMS: MySQL 5.6

Natively the Accident index is a varchar(numbers and letters), with 15 digits. I tried not to have surrogate keys, once the accident indexes would never change. In a i7(8 cores) computer, the DW became too slow to query after 12 million records of load depending of the dimensions. After a lot of re-work and adding bigint surrogate keys I got a average 20% speed performance boost. Yet to low performance gain, but valid try. Im working in MySQL tuning and clustering.

sqlplus statement from command line

I'm able to execute your exact query by just making sure there is a semicolon at the end of my select statement. (Output is actual, connection params removed.)

echo "select 1 from dual;" | sqlplus -s username/password@host:1521/service 

Output:

         1
----------
         1

Note that is should matter but this is running on Mac OS X Snow Leopard and Oracle 11g.

How can I add or update a query string parameter?

I have expanded the solution and combined it with another that I found to replace/update/remove the querystring parameters based on the users input and taking the urls anchor into consideration.

Not supplying a value will remove the parameter, supplying one will add/update the parameter. If no URL is supplied, it will be grabbed from window.location

function UpdateQueryString(key, value, url) {
    if (!url) url = window.location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),
        hash;

    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null) {
            return url.replace(re, '$1' + key + "=" + value + '$2$3');
        } 
        else {
            hash = url.split('#');
            url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                url += '#' + hash[1];
            }
            return url;
        }
    }
    else {
        if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            hash = url.split('#');
            url = hash[0] + separator + key + '=' + value;
            if (typeof hash[1] !== 'undefined' && hash[1] !== null) {
                url += '#' + hash[1];
            }
            return url;
        }
        else {
            return url;
        }
    }
}

Update

There was a bug when removing the first parameter in the querystring, I have reworked the regex and test to include a fix.

Second Update

As suggested by @JarónBarends - Tweak value check to check against undefined and null to allow setting 0 values

Third Update

There was a bug where removing a querystring variable directly before a hashtag would lose the hashtag symbol which has been fixed

Fourth Update

Thanks @rooby for pointing out a regex optimization in the first RegExp object. Set initial regex to ([?&]) due to issue with using (\?|&) found by @YonatanKarni

Fifth Update

Removing declaring hash var in if/else statement

error: package javax.servlet does not exist

I only put this code in my pom.xml and I executed the command maven install.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>

"Parameter not valid" exception loading System.Drawing.Image

Which line is throwing the exception? The new MemoryStream(...)? or the Image.FromStream(...)? And what is the byteArrayIn? Is it a byte[]? I only ask because of the comment "And none of value in it is not greater than 255" - which of course is automatic for a byte[].

As a more obvious question: does the binary actually contain an image in a sensible format?

For example, the following (although not great code) works fine:

    byte[] data = File.ReadAllBytes(@"d:\extn.png"); // not a good idea...
    MemoryStream ms = new MemoryStream(data);
    Image img = Image.FromStream(ms);
    Console.WriteLine(img.Width);
    Console.WriteLine(img.Height);

web-api POST body object always null

Check if JsonProperty attribute is set on the fields that come as null - it could be that they are mapped to different json property-names.

How can I send JSON response in symfony2 controller

Symfony 2.1 has a JsonResponse class.

return new JsonResponse(array('name' => $name));

The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.

There is also a handy setCallback function for JSONP.

Add to python path mac os x

Mathew's answer works for the terminal python shell, but it didn't work for IDLE shell in my case because many versions of python existed before I replaced them all with Python2.7.7. How I solved the problem with IDLE.

  1. In terminal, cd /Applications/Python\ 2.7/IDLE.app/Contents/Resources/
  2. then sudo nano idlemain.py, enter password if required.
  3. after os.chdir(os.path.expanduser('~/Documents')) this line, I added sys.path.append("/Users/admin/Downloads....") NOTE: replace contents of the quotes with the directory where python module to be added
  4. to save the change, ctrl+x and enter Now open idle and try to import the python module, no error for me!!!

docker command not found even though installed with apt-get

SET UP THE REPOSITORY

For Ubuntu 14.04/16.04/16.10/17.04:

sudo add-apt-repository "deb [arch=amd64] \
     https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

For Ubuntu 17.10:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu zesty stable"

Add Docker’s official GPG key:

$ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Then install

$ sudo apt-get update && sudo apt-get -y install docker-ce

How to center a <p> element inside a <div> container?

You only need to add text-align: center to your <div>

In your case also remove both styles that you added to your <p>.

Check out the demo here: http://jsfiddle.net/76uGE/3/

Good Luck

How to reset Django admin password?

  1. python manage.py createsuperuser will create another superuser, you will be able to log into admin and rememder your username.
  2. Yes, why not.

To give a normal user privileges, open a shell with python manage.py shell and try:

from django.contrib.auth.models import User
user = User.objects.get(username='normaluser')
user.is_superuser = True
user.save()

jQuery Remove string from string

To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace function since it is not a mutator function:

myString = myString.replace('username1','');

What's the actual use of 'fail' in JUnit test case?

I, for example, use fail() to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.

This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.

JavaScript style.display="none" or jQuery .hide() is more efficient?

Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.

In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden') which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.

Program "make" not found in PATH

Make sure you have installed 'make' tool through Cygwin's installer.

Who sets response content-type in Spring MVC (@ResponseBody)

Simple declaration of the StringHttpMessageConverter bean is not enough, you need to inject it into AnnotationMethodHandlerAdapter:

<bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean class = "org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
            </bean>
        </array>
    </property>
</bean>

However, using this method you have to redefine all HttpMessageConverters, and also it doesn't work with <mvc:annotation-driven />.

So, perhaps the most convenient but ugly method is to intercept instantiation of the AnnotationMethodHandlerAdapter with BeanPostProcessor:

public class EncodingPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String name)
            throws BeansException {
        if (bean instanceof AnnotationMethodHandlerAdapter) {
            HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
            for (HttpMessageConverter<?> conv: convs) {
                if (conv instanceof StringHttpMessageConverter) {
                    ((StringHttpMessageConverter) conv).setSupportedMediaTypes(
                        Arrays.asList(new MediaType("text", "html", 
                            Charset.forName("UTF-8"))));
                }
            }
        }
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String name)
            throws BeansException {
        return bean;
    }
}

-

<bean class = "EncodingPostProcessor " />

From milliseconds to hour, minutes, seconds and milliseconds

Arduino (c++) version based on Valentinos answer

unsigned long timeNow = 0;
unsigned long mSecInHour = 3600000;
unsigned long TimeNow =0;
int millisecs =0;  
int seconds = 0;
byte minutes = 0;
byte hours = 0;

void setup() {
Serial.begin(9600);
Serial.println (""); // because arduino monitor gets confused with line 1
Serial.println ("hours:minutes:seconds.milliseconds:");
}

void loop() {
TimeNow = millis(); 
hours = TimeNow/mSecInHour;
minutes = (TimeNow-(hours*mSecInHour))/(mSecInHour/60);
seconds = (TimeNow-(hours*mSecInHour)-(minutes*(mSecInHour/60)))/1000;
millisecs = TimeNow-(hours*mSecInHour)-(minutes*(mSecInHour/60))-       (seconds*1000);

Serial.print(hours);  
Serial.print(":");
Serial.print(minutes);
Serial.print(":"); 
Serial.print(seconds); 
Serial.print("."); 
Serial.println(millisecs); 
}

Random number between 0 and 1 in python

random.random() does exactly that

>>> import random
>>> for i in range(10):
...     print(random.random())
... 
0.908047338626
0.0199900075962
0.904058545833
0.321508119045
0.657086320195
0.714084413092
0.315924955063
0.696965958019
0.93824013683
0.484207425759

If you want really random numbers, and to cover the range [0, 1]:

>>> import os
>>> int.from_bytes(os.urandom(8), byteorder="big") / ((1 << 64) - 1)
0.7409674234050893

Which browsers support <script async="async" />?

Just had a look at the DOM (document.scripts[1].attributes) of this page that uses google analytics. I can tell you that google is using async="".

[type="text/javascript", async="", src="http://www.google-analytics.com/ga.js"]

How do I seed a random class to avoid getting duplicate random values

public static Random rand = new Random(); // this happens once, and will be great at preventing duplicates

Note, this is not to be used for cryptographic purposes.

Send XML data to webservice using php curl

Previous anwser works fine. I would just add that you dont need to specify CURLOPT_POSTFIELDS as "xmlRequest=" . $input_xml to read your $_POST. You can use file_get_contents('php://input') to get the raw post data as plain XML.

How to move text up using CSS when nothing is working

footerText {
    line-height: 20px;
}

you don't need to start playing with position or even layout of other elements... use this simple solution

Java: convert seconds to minutes, hours and days

The simpliest way

    Scanner in = new Scanner(System.in);
    System.out.println("Enter seconds");
    int s = in.nextInt();

    int sec = s % 60;
    int min = (s / 60)%60;
    int hours = (s/60)/60;

    System.out.println(hours + ":" + min + ":" + sec);

Solution to "subquery returns more than 1 row" error

You can use in():

select * 
from table
where id in (multiple row query)

or use a join:

select distinct t.* 
from source_of_id_table s
join table t on t.id = s.t_id
where <conditions for source_of_id_table>

The join is never a worse choice for performance, and depending on the exact situation and the database you're using, can give much better performance.

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

Make sure to check your version of npm and whether or not there are issues with it. I was having the same issue at the time of this post and I discovered that my npm version (6.5) was having issues. I had to uninstall and reinstall npm version 6.4.1 and then everything started to work great again.

How do I search an SQL Server database for a string?

If I want to find where anything I want to search is, I use this:

DECLARE @search_string    varchar(200)
    SET @search_string = '%myString%'

    SELECT DISTINCT
           o.name AS Object_Name,
           o.type_desc,
           m.definition
      FROM sys.sql_modules m
           INNER JOIN
           sys.objects o
             ON m.object_id = o.object_id
     WHERE m.definition Like @search_string;

Circle-Rectangle collision detection (intersection)

This is the fastest solution:

public static boolean intersect(Rectangle r, Circle c)
{
    float cx = Math.abs(c.x - r.x - r.halfWidth);
    float xDist = r.halfWidth + c.radius;
    if (cx > xDist)
        return false;
    float cy = Math.abs(c.y - r.y - r.halfHeight);
    float yDist = r.halfHeight + c.radius;
    if (cy > yDist)
        return false;
    if (cx <= r.halfWidth || cy <= r.halfHeight)
        return true;
    float xCornerDist = cx - r.halfWidth;
    float yCornerDist = cy - r.halfHeight;
    float xCornerDistSq = xCornerDist * xCornerDist;
    float yCornerDistSq = yCornerDist * yCornerDist;
    float maxCornerDistSq = c.radius * c.radius;
    return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
}

Note the order of execution, and half the width/height is pre-computed. Also the squaring is done "manually" to save some clock cycles.

How do I encode and decode a base64 string?

I'm sharing my implementation with some neat features:

  • uses Extension Methods for Encoding class. Rationale is that someone may need to support different types of encodings (not only UTF8).
  • Another improvement is failing gracefully with null result for null entry - it's very useful in real life scenarios and supports equivalence for X=decode(encode(X)).

Remark: Remember that to use Extension Method you have to (!) import the namespace with using keyword (in this case using MyApplication.Helpers.Encoding).

Code:

namespace MyApplication.Helpers.Encoding
{
    public static class EncodingForBase64
    {
        public static string EncodeBase64(this System.Text.Encoding encoding, string text)
        {
            if (text == null)
            {
                return null;
            }

            byte[] textAsBytes = encoding.GetBytes(text);
            return System.Convert.ToBase64String(textAsBytes);
        }

        public static string DecodeBase64(this System.Text.Encoding encoding, string encodedText)
        {
            if (encodedText == null)
            {
                return null;
            }

            byte[] textAsBytes = System.Convert.FromBase64String(encodedText);
            return encoding.GetString(textAsBytes);
        }
    }
}

Usage example:

using MyApplication.Helpers.Encoding; // !!!

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1();
            Test2();
        }

        static void Test1()
        {
            string textEncoded = System.Text.Encoding.UTF8.EncodeBase64("test1...");
            System.Diagnostics.Debug.Assert(textEncoded == "dGVzdDEuLi4=");

            string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
            System.Diagnostics.Debug.Assert(textDecoded == "test1...");
        }

        static void Test2()
        {
            string textEncoded = System.Text.Encoding.UTF8.EncodeBase64(null);
            System.Diagnostics.Debug.Assert(textEncoded == null);

            string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
            System.Diagnostics.Debug.Assert(textDecoded == null);
        }
    }
}

How to copy only a single worksheet to another workbook using vba

The much longer example below combines some of the useful snippets above:

  • You can specify any number of sheets you want to copy across
  • You can copy entire sheets, i.e. like dragging the tab across, or you can copy over the contents of cells as values-only but preserving formatting.

It could still do with a lot of work to make it better (better error-handling, general cleaning up), but it hopefully provides a good start.

Note that not all formatting is carried across because the new sheet uses its own theme's fonts and colours. I can't work out how to copy those across when pasting as values only.

 Option Explicit

Sub copyDataToNewFile()
    Application.ScreenUpdating = False

    ' Allow different ways of copying data:
    ' sheet = copy the entire sheet
    ' valuesWithFormatting = create a new sheet with the same name as the
    '                        original, copy values from the cells only, then
    '                        apply original formatting. Formatting is only as
    '                        good as the Paste Special > Formats command - theme
    '                        colours and fonts are not preserved.
    Dim copyMethod As String
    copyMethod = "valuesWithFormatting"

    Dim newFilename As String           ' Name (+optionally path) of new file
    Dim themeTempFilePath As String     ' To temporarily save the source file's theme

    Dim sourceWorkbook As Workbook      ' This file
    Set sourceWorkbook = ThisWorkbook

    Dim newWorkbook As Workbook         ' New file

    Dim sht As Worksheet                ' To iterate through sheets later on.
    Dim sheetFriendlyName As String     ' To store friendly sheet name
    Dim sheetCount As Long              ' To avoid having to count multiple times

    ' Sheets to copy over, using internal code names as more reliable.
    Dim colSheetObjectsToCopy As New Collection
    colSheetObjectsToCopy.Add Sheet1
    colSheetObjectsToCopy.Add Sheet2

    ' Get filename of new file from user.
    Do
        newFilename = InputBox("Please Specify the name of your new workbook." & vbCr & vbCr & "Either enter a full path or just a filename, in which case the file will be saved in the same location (" & sourceWorkbook.Path & "). Don't use the name of a workbook that is already open, otherwise this script will break.", "New Copy")
        If newFilename = "" Then MsgBox "You must enter something.", vbExclamation, "Filename needed"
    Loop Until newFilename > ""

    ' If they didn't supply a path, assume same location as the source workbook.
    ' Not perfect - simply assumes a path has been supplied if a path separator
    ' exists somewhere. Could still be a badly-formed path. And, no check is done
    ' to see if the path actually exists.
    If InStr(1, newFilename, Application.PathSeparator, vbTextCompare) = 0 Then
        newFilename = sourceWorkbook.Path & Application.PathSeparator & newFilename
    End If

    ' Create a new workbook and save as the user requested.
    ' NB This fails if the filename is the same as a workbook that's
    ' already open - it should check for this.
    Set newWorkbook = Application.Workbooks.Add(xlWBATWorksheet)
    newWorkbook.SaveAs Filename:=newFilename, _
        FileFormat:=xlWorkbookDefault

    ' Theme fonts and colours don't get copied over with most paste-special operations.
    ' This saves the theme of the source workbook and then loads it into the new workbook.
    ' BUG: Doesn't work!
    'themeTempFilePath = Environ("temp") & Application.PathSeparator & sourceWorkbook.Name & " - Theme.xml"
    'sourceWorkbook.Theme.ThemeFontScheme.Save themeTempFilePath
    'sourceWorkbook.Theme.ThemeColorScheme.Save themeTempFilePath
    'newWorkbook.Theme.ThemeFontScheme.Load themeTempFilePath
    'newWorkbook.Theme.ThemeColorScheme.Load themeTempFilePath
    'On Error Resume Next
    'Kill themeTempFilePath  ' kill = delete in VBA-speak
    'On Error GoTo 0


    ' getWorksheetNameFromObject returns null if the worksheet object doens't
    ' exist
    For Each sht In colSheetObjectsToCopy
        sheetFriendlyName = getWorksheetNameFromObject(sourceWorkbook, sht)
        Application.StatusBar = "VBL Copying " & sheetFriendlyName
        If Not IsNull(sheetFriendlyName) Then
            Select Case copyMethod
                Case "sheet"
                    sourceWorkbook.Sheets(sheetFriendlyName).Copy _
                        After:=newWorkbook.Sheets(newWorkbook.Sheets.count)
                Case "valuesWithFormatting"
                    newWorkbook.Sheets.Add After:=newWorkbook.Sheets(newWorkbook.Sheets.count), _
                        Type:=sourceWorkbook.Sheets(sheetFriendlyName).Type
                    sheetCount = newWorkbook.Sheets.count
                    newWorkbook.Sheets(sheetCount).Name = sheetFriendlyName
                    ' Copy all cells in current source sheet to the clipboard. Could copy straight
                    ' to the new workbook by specifying the Destination parameter but in this case
                    ' we want to do a paste special as values only and the Copy method doens't allow that.
                    sourceWorkbook.Sheets(sheetFriendlyName).Cells.Copy ' Destination:=newWorkbook.Sheets(newWorkbook.Sheets.Count).[A1]
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlValues
                    newWorkbook.Sheets(sheetCount).[A1].PasteSpecial Paste:=xlFormats
                    newWorkbook.Sheets(sheetCount).Tab.Color = sourceWorkbook.Sheets(sheetFriendlyName).Tab.Color
                    Application.CutCopyMode = False
            End Select
        End If
    Next sht

    Application.StatusBar = False
    Application.ScreenUpdating = True
    ActiveWorkbook.Save

How to resolve git status "Unmerged paths:"?

Another way of dealing with this situation if your files ARE already checked in, and your files have been merged (but not committed, so the merge conflicts are inserted into the file) is to run:

git reset

This will switch to HEAD, and tell git to forget any merge conflicts, and leave the working directory as is. Then you can edit the files in question (search for the "Updated upstream" notices). Once you've dealt with the conflicts, you can run

git add -p

which will allow you to interactively select which changes you want to add to the index. Once the index looks good (git diff --cached), you can commit, and then

git reset --hard

to destroy all the unwanted changes in your working directory.

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)

public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
    disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
    setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}

}

Remove credentials from Git

In my case, Git is using Windows to store credentials.

All you have to do is remove the stored credentials stored in your Windows account:

Windows credentials menu

How to close existing connections to a DB

You can use Cursor like that:

USE master
GO

DECLARE @SQL AS VARCHAR(255)
DECLARE @SPID AS SMALLINT
DECLARE @Database AS VARCHAR(500)
SET @Database = 'AdventureWorks2016CTP3'

DECLARE Murderer CURSOR FOR
SELECT spid FROM sys.sysprocesses WHERE DB_NAME(dbid) = @Database

OPEN Murderer

FETCH NEXT FROM Murderer INTO @SPID
WHILE @@FETCH_STATUS = 0

    BEGIN
    SET @SQL = 'Kill ' + CAST(@SPID AS VARCHAR(10)) + ';'
    EXEC (@SQL)
    PRINT  ' Process ' + CAST(@SPID AS VARCHAR(10)) +' has been killed'
    FETCH NEXT FROM Murderer INTO @SPID
    END 

CLOSE Murderer
DEALLOCATE Murderer

I wrote about that in my blog here: http://www.pigeonsql.com/single-post/2016/12/13/Kill-all-connections-on-DB-by-Cursor

Get properties of a class

Some answers are partially wrong, and some facts in them are partially wrong as well.

Answer your question: Yes! You can.

In Typescript

class A {
    private a1;
    private a2;


}

Generates the following code in Javascript:

var A = /** @class */ (function () {
    function A() {
    }
    return A;
}());

as @Erik_Cupal said, you could just do:

let a = new A();
let array = return Object.getOwnPropertyNames(a);

But this is incomplete. What happens if your class has a custom constructor? You need to do a trick with Typescript because it will not compile. You need to assign as any:

let className:any = A;
let a = new className();// the members will have value undefined

A general solution will be:

class A {
    private a1;
    private a2;
    constructor(a1:number, a2:string){
        this.a1 = a1;
        this.a2 = a2;
    }
}

class Describer{

   describeClass( typeOfClass:any){
       let a = new typeOfClass();
       let array = Object.getOwnPropertyNames(a);
       return array;//you can apply any filter here
   }
}

For better understanding this will reference depending on the context.

When to use IMG vs. CSS background-image?

Using a background image, you need to absolutely specify the dimensions. This can be a significant problem if you don't actually know them in advance or cannot determine them.

A big problem with <img /> is overlays. What if I want an CSS inner shadow on my image (box-shadow:inset 0 0 5px rgb(0,0,0,.5))? In this case, since <img /> can't have child elements, you need to use positioning and add empty elements which equates to useless markup.

In conclusion, it's quite situational.

MySQL vs MySQLi when using PHP

What is better is PDO; it's a less crufty interface and also provides the same features as MySQLi.

Using prepared statements is good because it eliminates SQL injection possibilities; using server-side prepared statements is bad because it increases the number of round-trips.

What are the true benefits of ExpandoObject?

The real benefit for me is the totally effortless data binding from XAML:

public dynamic SomeData { get; set; }

...

SomeData.WhatEver = "Yo Man!";

...

 <TextBlock Text="{Binding SomeData.WhatEver}" />

How to install toolbox for MATLAB

Use ver it will list all the installed toolboxes and versions of the toolbox.

Is there shorthand for returning a default value if None in Python?

You've got the ternary syntax x if x else '' - is that what you're after?

How can I solve the error LNK2019: unresolved external symbol - function?

It turned out I was using .c files with .cpp files. Renaming .c to .cpp solved my problem.

How to validate numeric values which may contain dots or commas?

\d{1,2}[\,\.]{1}\d{1,2}

EDIT: update to meet the new requirements (comments) ;)
EDIT: remove unnecesary qtfier as per Bryan

^[0-9]{1,2}([,.][0-9]{1,2})?$

How do you build a Singleton in Dart?

What about just using a global variable within your library, like so?

single.dart:

library singleton;

var Singleton = new Impl();

class Impl {
  int i;
}

main.dart:

import 'single.dart';

void main() {
  var a = Singleton;
  var b = Singleton;
  a.i = 2;
  print(b.i);
}

Or is this frowned upon?

The singleton pattern is necessary in Java where the concept of globals doesn't exist, but it seems like you shouldn't need to go the long way around in Dart.

Pointers, smart pointers or shared pointers?

Sydius outlined the types fairly well:

  • Normal pointers are just that - they point to some thing in memory somewhere. Who owns it? Only the comments will let you know. Who frees it? Hopefully the owner at some point.
  • Smart pointers are a blanket term that cover many types; I'll assume you meant scoped pointer which uses the RAII pattern. It is a stack-allocated object that wraps a pointer; when it goes out of scope, it calls delete on the pointer it wraps. It "owns" the contained pointer in that it is in charge of deleteing it at some point. They allow you to get a raw reference to the pointer they wrap for passing to other methods, as well as releasing the pointer, allowing someone else to own it. Copying them does not make sense.
  • Shared pointers is a stack-allocated object that wraps a pointer so that you don't have to know who owns it. When the last shared pointer for an object in memory is destructed, the wrapped pointer will also be deleted.

How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure.

There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base.

There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer.

The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.

momentJS date string add 5 days

To get an actual working example going that returns what one would expect:

var startdate = "20.03.2014";
var new_date = moment(startdate, "DD.MM.YYYY");
var thing = new_date.add(5, 'days').format('DD/MM/YYYY');
window.console.log(thing)

null terminating a string

To your first question: I would go with Paul R's comment and terminate with '\0'. But the value 0 itself works also fine. A matter of taste. But don't use the MACRO NULLwhich is meant for pointers.

To your second question: If your string is not terminated with\0, it might still print the expected output because following your string is a non-printable character in your memory. This is a really nasty bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'.

Efficient iteration with index in Scala

I have the following approaches

object HelloV2 {

   def main(args: Array[String]) {

     //Efficient iteration with index in Scala

     //Approach #1
     var msg = "";

     for (i <- args.indices)
     {
       msg+=(args(i));
     }
     var msg1="";

     //Approach #2
     for (i <- 0 until args.length) 
     {
       msg1 += (args(i));
     }

     //Approach #3
     var msg3=""
     args.foreach{
       arg =>
        msg3 += (arg)
     }


      println("msg= " + msg);

      println("msg1= " + msg1);

      println("msg3= " + msg3);

   }
}

How to copy file from HDFS to the local file system

you can accomplish in both these ways.

1.hadoop fs -get <HDFS file path> <Local system directory path>
2.hadoop fs -copyToLocal <HDFS file path> <Local system directory path>

Ex:

My files are located in /sourcedata/mydata.txt I want to copy file to Local file system in this path /user/ravi/mydata

hadoop fs -get /sourcedata/mydata.txt /user/ravi/mydata/

Displaying Windows command prompt output and redirecting it to a file

I install perl on most of my machines so an answer using perl: tee.pl

my $file = shift || "tee.dat";
open $output, ">", $file or die "unable to open $file as output: $!";
while(<STDIN>)
{
    print $_;
    print $output $_;
}
close $output;

dir | perl tee.pl or dir | perl tee.pl dir.bat

crude and untested.

How to calculate the angle between a line and the horizontal axis?

import math
from collections import namedtuple


Point = namedtuple("Point", ["x", "y"])


def get_angle(p1: Point, p2: Point) -> float:
    """Get the angle of this line with the horizontal axis."""
    dx = p2.x - p1.x
    dy = p2.y - p1.y
    theta = math.atan2(dy, dx)
    angle = math.degrees(theta)  # angle is in (-180, 180]
    if angle < 0:
        angle = 360 + angle
    return angle

Testing

For testing I let hypothesis generate test cases.

enter image description here

import hypothesis.strategies as s
from hypothesis import given


@given(s.floats(min_value=0.0, max_value=360.0))
def test_angle(angle: float):
    epsilon = 0.0001
    x = math.cos(math.radians(angle))
    y = math.sin(math.radians(angle))
    p1 = Point(0, 0)
    p2 = Point(x, y)
    assert abs(get_angle(p1, p2) - angle) < epsilon

Node.js Error: connect ECONNREFUSED

Run server.js from a different command line and client.js from a different command line

PSQLException: current transaction is aborted, commands ignored until end of transaction block

You need to rollback. The JDBC Postgres driver is pretty bad. But if you want to keep your transaction, and just rollback that error, you can use savepoints:

try {
_stmt = connection.createStatement();
_savePoint = connection.setSavepoint("sp01");
_result = _stmt.executeUpdate(sentence) > 0;
} catch (Exception e){
 if (_savePoint!=null){
 connection.rollback(_savePoint);
}
}

Read more here:

http://www.postgresql.org/docs/8.1/static/sql-savepoint.html

Submit form using a button outside the <form> tag

You can tell a form that an external component from outside the <form> tag belongs to it by adding the form="yourFormName" to the definition of the component.

In this case,

<form id="login-form">
... blah...
</form>

<button type="submit" form="login-form" name="login_user" class="login-form-btn">
        <B>Autentificate</B>
</button>

... would still submit the form happily because you assigned the form name to it. The form thinks the button is part of it, even if the button is outside the tag, and this requires NO javascript to submit the form (which can be buggy i.e. form may submit but bootstrap errors / validations my fail to show, I tested).

Remove duplicate elements from array in Ruby

array = array.uniq

uniq removes all duplicate elements and retains all unique elements in the array.

This is one of many beauties of the Ruby language.

How to sort a file in-place

sort file | sponge file

This is in the following Fedora package:

moreutils : Additional unix utilities
Repo        : fedora
Matched from:
Filename    : /usr/bin/sponge

asp.net: How can I remove an item from a dropdownlist?

I would add an identifying Id or class to the dropbox and remove using Javascript.

The article here should help.

D

How do I get whole and fractional parts from double in JSP/Java?

A lot of these answers have horrid rounding errors because they're casting numbers from one type to another. How about:

double x=123.456;
double fractionalPart = x-Math.floor(x);
double wholePart = Math.floor(x);

How to convert std::string to LPCWSTR in C++ (Unicode)

If you are in an ATL/MFC environment, You can use the ATL conversion macro:

#include <atlbase.h>
#include <atlconv.h>

. . .

string myStr("My string");
CA2W unicodeStr(myStr);

You can then use unicodeStr as an LPCWSTR. The memory for the unicode string is created on the stack and released then the destructor for unicodeStr executes.

How to use the ConfigurationManager.AppSettings

you should use []

var x = ConfigurationManager.AppSettings["APIKey"];

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Just for completeness, you don't actually have to add it to your HTML (which is unknown http-equiv in HTML5)

Do this and never look back (first example for apache, second for nginx)

Header set X-UA-Compatible "IE=Edge,chrome=1"

add_header X-UA-Compatible "IE=Edge,chrome=1";

SyntaxError: Use of const in strict mode?

One important step after you update your node is to link your node binary to the latest installed node version

sudo ln -sf /usr/local/n/versions/node/6.0.0/bin/node /usr/bin/node  

Where is Java's Array indexOf?

Unlike in C# where you have the Array.IndexOf method, and JavaScript where you have the indexOf method, Java's API (the Array and Arrays classes in particular) have no such method.

This method indexOf (together with its complement lastIndexOf) is defined in the java.util.List interface. Note that indexOf and lastIndexOf are not overloaded and only take an Object as a parameter.

If your array is sorted, you are in luck because the Arrays class defines a series of overloads of the binarySearch method that will find the index of the element you are looking for with best possible performance (O(log n) instead of O(n), the latter being what you can expect from a sequential search done by indexOf). There are four considerations:

  1. The array must be sorted either in natural order or in the order of a Comparator that you provide as an argument, or at the very least all elements that are "less than" the key must come before that element in the array and all elements that are "greater than" the key must come after that element in the array;

  2. The test you normally do with indexOf to determine if a key is in the array (verify if the return value is not -1) does not hold with binarySearch. You need to verify that the return value is not less than zero since the value returned will indicate the key is not present but the index at which it would be expected if it did exist;

  3. If your array contains multiple elements that are equal to the key, what you get from binarySearch is undefined; this is different from indexOf that will return the first occurrence and lastIndexOf that will return the last occurrence.

  4. An array of booleans might appear to be sorted if it first contains all falses and then all trues, but this doesn't count. There is no override of the binarySearch method that accepts an array of booleans and you'll have to do something clever there if you want O(log n) performance when detecting where the first true appears in an array, for instance using an array of Booleans and the constants Boolean.FALSE and Boolean.TRUE.

If your array is not sorted and not primitive type, you can use List's indexOf and lastIndexOf methods by invoking the asList method of java.util.Arrays. This method will return an AbstractList interface wrapper around your array. It involves minimal overhead since it does not create a copy of the array. As mentioned, this method is not overloaded so this will only work on arrays of reference types.

If your array is not sorted and the type of the array is primitive, you are out of luck with the Java API. Write your own for loop, or your own static utility method, which will certainly have performance advantages over the asList approach that involves some overhead of an object instantiation. In case you're concerned that writing a brute force for loop that iterates over all of the elements of the array is not an elegant solution, accept that that is exactly what the Java API is doing when you call indexOf. You can make something like this:

public static int indexOfIntArray(int[] array, int key) {
    int returnvalue = -1;
    for (int i = 0; i < array.length; ++i) {
        if (key == array[i]) {
            returnvalue = i;
            break;
        }
    }
    return returnvalue;
}

If you want to avoid writing your own method here, consider using one from a development framework like Guava. There you can find an implementation of indexOf and lastIndexOf.

Clearing content of text file using C#

Just open the file with the FileMode.Truncate flag, then close it:

using (var fs = new FileStream(@"C:\path\to\file", FileMode.Truncate))
{
}

How to set environment variables in PyCharm?

None of the above methods worked for me. If you are on Windows, try this on PyCharm terminal:

setx YOUR_VAR "VALUE"

You can access it in your scripts using os.environ['YOUR_VAR'].

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

There were too many projects in my solution to go through and individually update so I fixed this by:

  • Right-clicking my solution and selecting 'Manage NuGet Packages for Solution...'
  • Going to the Updates tab
  • Finding the affected package and selecting Update
  • Clicked OK and this brought all instances of the package up to date

close fancy box from function from within open 'fancybox'

yes in Virtuemart its must be button CLOSe-continue shopping, not element, because after click you can redirect.. i found this redirect bug on my ajax website.

How to connect to MySQL Database?

Install Oracle's MySql.Data NuGet package.

using MySql.Data;
using MySql.Data.MySqlClient;

namespace Data
{
    public class DBConnection
    {
        private DBConnection()
        {
        }

        public string Server { get; set; }
        public string DatabaseName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        private MySqlConnection Connection { get; set;}

        private static DBConnection _instance = null;
        public static DBConnection Instance()
        {
            if (_instance == null)
                _instance = new DBConnection();
           return _instance;
        }
    
        public bool IsConnect()
        {
            if (Connection == null)
            {
                if (String.IsNullOrEmpty(databaseName))
                    return false;
                string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
                Connection = new MySqlConnection(connstring);
                Connection.Open();
            }
    
            return true;
        }
    
        public void Close()
        {
            Connection.Close();
        }        
    }
}

Example:

var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
    //suppose col0 and col1 are defined as VARCHAR in the DB
    string query = "SELECT col0,col1 FROM YourTable";
    var cmd = new MySqlCommand(query, dbCon.Connection);
    var reader = cmd.ExecuteReader();
    while(reader.Read())
    {
        string someStringFromColumnZero = reader.GetString(0);
        string someStringFromColumnOne = reader.GetString(1);
        Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
    }
    dbCon.Close();
}

How to easily resize/optimize an image size with iOS?

- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize {
    CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
    CGImageRef imageRef = image.CGImage;

    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);

    CGContextConcatCTM(context, flipVertical);
    CGContextDrawImage(context, newRect, imageRef);

    CGImageRef newImageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];

    CGImageRelease(newImageRef);
    UIGraphicsEndImageContext();

    return newImage;
}

Bloomberg BDH function with ISIN

The problem is that an isin does not identify the exchange, only an issuer.

Let's say your isin is US4592001014 (IBM), one way to do it would be:

  • get the ticker (in A1):

    =BDP("US4592001014 ISIN", "TICKER") => IBM
    
  • get a proper symbol (in A2)

    =BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
    

    where XX depends on your terminal settings, which you can check on CNDF <Go>.

  • get the main exchange composite ticker, or whatever suits your need (in A3):

    =BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
    
  • and finally:

    =BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
    

How to count instances of character in SQL Column

If you need to count the char in a string with more then 2 kinds of chars, you can use instead of 'n' - some operator or regex of the chars accept the char you need.

SELECT LEN(REPLACE(col, 'N', ''))

How to resolve a Java Rounding Double issue

double rounded = Math.rint(toround * 100) / 100;

How To change the column order of An Existing Table in SQL Server 2008

SQL query to change the id column into first:

ALTER TABLE `student` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT FIRST;

or by using:

ALTER TABLE `student` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT AFTER 'column_name' 

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

C++ Calling a function from another class

Forward declare class B and swap order of A and B definitions: 1st B and 2nd A. You can not call methods of forward declared B class.

Precision String Format Specifier In Swift

a simple way is:

import Foundation // required for String(format: _, _)

print(String(format: "hex string: %X", 123456))
print(String(format: "a float number: %.5f", 1.0321))

Calling a function on bootstrap modal open

Bootstrap modal exposes events. Listen for the the shown event like this

$('#my-modal').on('shown', function(){
  // code here
});

Twitter Bootstrap alert message close and open again

Here is a solution based on the answer by Henrik Karlsson but with proper event triggering (based on Bootstrap sources):

$(function(){
    $('[data-hide]').on('click', function ___alert_hide(e) {
        var $this = $(this)
        var selector = $this.attr('data-target')
        if (!selector) {
            selector = $this.attr('href')
            selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
        }

        var $parent = $(selector === '#' ? [] : selector)

        if (!$parent.length) {
            $parent = $this.closest('.alert')
        }

        $parent.trigger(e = $.Event('close.bs.alert'))

        if (e.isDefaultPrevented()) return

        $parent.hide()

        $parent.trigger($.Event('closed.bs.alert'))
    })
});

The answer mostly for me, as a note.

Uploading/Displaying Images in MVC 4

Here is a short tutorial:

Model:

namespace ImageUploadApp.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Image
    {
        public int ID { get; set; }
        public string ImagePath { get; set; }
    }
}

View:

  1. Create:

    @model ImageUploadApp.Models.Image
    @{
        ViewBag.Title = "Create";
    }
    <h2>Create</h2>
    @using (Html.BeginForm("Create", "Image", null, FormMethod.Post, 
                                  new { enctype = "multipart/form-data" })) {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>Image</legend>
            <div class="editor-label">
                @Html.LabelFor(model => model.ImagePath)
            </div>
            <div class="editor-field">
                <input id="ImagePath" title="Upload a product image" 
                                      type="file" name="file" />
            </div>
            <p><input type="submit" value="Create" /></p>
        </fieldset>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
    
  2. Index (for display):

    @model IEnumerable<ImageUploadApp.Models.Image>
    
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.ImagePath)
            </th>
        </tr>
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ImagePath)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
                @Html.ActionLink("Details", "Details", new { id=item.ID }) |
                @Ajax.ActionLink("Delete", "Delete", new {id = item.ID} })
            </td>
        </tr>
    }
    
    </table>
    
  3. Controller (Create)

    public ActionResult Create(Image img, HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            if (file != null)
            {
                file.SaveAs(HttpContext.Server.MapPath("~/Images/") 
                                                      + file.FileName);
                img.ImagePath = file.FileName;
            }  
            db.Image.Add(img);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(img);
    }
    

Hope this will help :)

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

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

tar -cvjf my.tar.bz2 dir/

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

Repeat table headers in print mode

Some browsers repeat the thead element on each page, as they are supposed to. Others need some help: Add this to your CSS:

thead {display: table-header-group;}
tfoot {display: table-header-group;}

Opera 7.5 and IE 5 won't repeat headers no matter what you try.

(source)

How to programmatically add controls to a form in VB.NET

To add controls dynamically to the form, do the following code. Here we are creating textbox controls to add dynamically.

Public Class Form1
    Private m_TextBoxes() As TextBox = {}

    Private Sub Button1_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles Button1.Click

        ' Get the index for the new control.
        Dim i As Integer = m_TextBoxes.Length

        ' Make room.
        ReDim Preserve m_TextBoxes(i)

        ' Create and initialize the control.
        m_TextBoxes(i) = New TextBox
        With m_TextBoxes(i)
            .Name = "TextBox" & i.ToString()
            If m_TextBoxes.Length < 2 Then
                ' Position the first one.
                .SetBounds(8, 8, 100, 20)
            Else
                ' Position subsequent controls.
                .Left = m_TextBoxes(i - 1).Left
                .Top = m_TextBoxes(i - 1).Top + m_TextBoxes(i - _
                    1).Height + 4
                .Size = m_TextBoxes(i - 1).Size
            End If

            ' Save the control's index in the Tag property.
            ' (Or you can get this from the Name.)
            .Tag = i
        End With

        ' Give the control an event handler.
        AddHandler m_TextBoxes(i).TextChanged, AddressOf TextBox_TextChanged

        ' Add the control to the form.
        Me.Controls.Add(m_TextBoxes(i))
    End Sub

    'When you enter text in one of the TextBoxes, the TextBox_TextChanged event
    'handler displays the control's name and its current text.
    Private Sub TextBox_TextChanged(ByVal sender As  _
    System.Object, ByVal e As System.EventArgs)
        ' Display the current text.
        Dim txt As TextBox = DirectCast(sender, TextBox)
        Debug.WriteLine(txt.Name & ": [" & txt.Text & "]")
    End Sub
End Class

how to use Spring Boot profiles

I'm not sure I fully understand the question but I'll attempt to answer by providing a few details about profiles in Spring Boot.

For your #1 example, according to the docs you can select the profile using the Spring Boot Maven plugin using -Drun.profiles.

Edit: For Spring Boot 2.0+ run has been renamed to spring-boot.run and run.profiles has been renamed to spring-boot.run.profiles

mvn spring-boot:run -Dspring-boot.run.profiles=dev

https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/maven-plugin/examples/run-profiles.html

From your #2 example, you are defining the active profile after the name of the jar. You need to provide the JVM argument before the name of the jar you are running.

java -jar -Dspring.profiles.active=dev XXX.jar

General info:

You mention that you have both an application.yml and a application-dev.yml. Running with the dev profile will actually load both config files. Values from application-dev.yml will override the same values provided by application.yml but values from both yml files will be loaded.

There are also multiple ways to define the active profile.

You can define them as you did, using -Dspring.profiles.active when running your jar. You can also set the profile using a SPRING_PROFILES_ACTIVE environment variable or a spring.profiles.active system property.

More info can be found here: https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-set-active-spring-profiles