Programs & Examples On #C

C is a general-purpose computer programming language used for operating systems, libraries, games and other high performance work. This tag should be used with general questions concerning the C language, as defined in the ISO 9899 standard (the latest version, 9899:2018, unless otherwise specified—also tag version-specific requests with c99, c89, etc). C is distinct from C++ and it should not be combined with the C++ tag absent a rational reason.

Finding the length of an integer in C

I think I got the most efficient way to find the length of an integer its a very simple and elegant way here it is:

int PEMath::LengthOfNum(int Num)
{
int count = 1;  //count starts at one because its the minumum amount of digits posible
if (Num < 0)
{
    Num *= (-1);
}

for(int i = 10; i <= Num; i*=10)
{
     count++;
}      
return count;
                // this loop will loop until the number "i" is bigger then "Num"
                // if "i" is less then "Num" multiply "i" by 10 and increase count
                // when the loop ends the number of count is the length of "Num".
}

How to compile makefile using MinGW?

You have to actively choose to install MSYS to get the make.exe. So you should always have at least (the native) mingw32-make.exe if MinGW was installed properly. And if you installed MSYS you will have make.exe (in the MSYS subfolder probably).

Note that many projects require first creating a makefile (e.g. using a configure script or automake .am file) and it is this step that requires MSYS or cygwin. Makes you wonder why they bothered to distribute the native make at all.

Once you have the makefile, it is unclear if the native executable requires a different path separator than the MSYS make (forward slashes vs backward slashes). Any autogenerated makefile is likely to have unix-style paths, assuming the native make can handle those, the compiled output should be the same.

min and max value of data type in C

Look at the these pages on limits.h and float.h, which are included as part of the standard c library.

How to run C program on Mac OS X using Terminal?

First save your program as program.c.

Now you need the compiler, so you need to go to App Store and install Xcode which is Apple's compiler and development tools. How to find App Store? Do a "Spotlight Search" by typing Space and start typing App Store and hit Enter when it guesses correctly.

App Store looks like this:

enter image description here

Xcode looks like this on App Store:

enter image description here

Then you need to install the command-line tools in Terminal. How to start Terminal? You need to do another "Spotlight Search", which means you type Space and start typing Terminal and hit Enter when it guesses Terminal.

Now install the command-line tools like this:

xcode-select --install

Then you can compile your code with by simply running gcc as in the next line without having to fire up the big, ugly software development GUI called Xcode:

gcc -Wall -o program program.c

Note: On newer versions of OS X, you would use clang instead of gcc, like this:

clang program.c -o program

Then you can run it with:

./program
Hello, world!

If your program is C++, you'll probably want to use one of these commands:

clang++ -o program program.cpp
g++ -std=c++11 -o program program.cpp
g++-7 -std=c++11 -o program program.cpp

warning: implicit declaration of function

I think the question is not 100% answered. I was searching for issue with missing typeof(), which is compile time directive.

Following links will shine light on the situation:

https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Typeof.html

https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Alternate-Keywords.html#Alternate-Keywords

as of conculsion try to use __typeof__() instead. Also gcc ... -Dtypeof=__typeof__ ... can help.

How to initialize a struct in accordance with C programming language standards

If MS has not updated to C99, MY_TYPE a = { true,15,0.123 };

Get IP address of an interface on Linux

If you're looking for an address (IPv4) of the specific interface say wlan0 then try this code which uses getifaddrs():

#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1) 
    {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }


    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) 
    {
        if (ifa->ifa_addr == NULL)
            continue;  

        s=getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);

        if((strcmp(ifa->ifa_name,"wlan0")==0)&&(ifa->ifa_addr->sa_family==AF_INET))
        {
            if (s != 0)
            {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                exit(EXIT_FAILURE);
            }
            printf("\tInterface : <%s>\n",ifa->ifa_name );
            printf("\t  Address : <%s>\n", host); 
        }
    }

    freeifaddrs(ifaddr);
    exit(EXIT_SUCCESS);
}

You can replace wlan0 with eth0 for ethernet and lo for local loopback.

The structure and detailed explanations of the data structures used could be found here.

To know more about linked list in C this page will be a good starting point.

How to convert integer to string in C?

Use sprintf():

int someInt = 368;
char str[12];
sprintf(str, "%d", someInt);

All numbers that are representable by int will fit in a 12-char-array without overflow, unless your compiler is somehow using more than 32-bits for int. When using numbers with greater bitsize, e.g. long with most 64-bit compilers, you need to increase the array size—at least 21 characters for 64-bit types.

error: unknown type name ‘bool’

C99 does, if you have

#include <stdbool.h> 

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

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

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

#endif

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

Is there an alternative sleep function in C to milliseconds?

#include <unistd.h>

int usleep(useconds_t useconds); //pass in microseconds

what is the use of fflush(stdin) in c programming

it clears stdin buffer before reading. From the man page:

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.

Note: This is Linux-specific, using fflush() on input streams is undefined by the standard, however, most implementations behave the same as in Linux.

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

If you want the structure to have a certain size with GCC for example use __attribute__((packed)).

On Windows you can set the alignment to one byte when using the cl.exe compier with the /Zp option.

Usually it is easier for the CPU to access data that is a multiple of 4 (or 8), depending platform and also on the compiler.

So it is a matter of alignment basically.

You need to have good reasons to change it.

How do I change a TCP socket to be non-blocking?

You're misinformed about fcntl() not always being reliable. It's untrue.

To mark a socket as non-blocking the code is as simple as:

// where socketfd is the socket you want to make non-blocking
int status = fcntl(socketfd, F_SETFL, fcntl(socketfd, F_GETFL, 0) | O_NONBLOCK);

if (status == -1){
  perror("calling fcntl");
  // handle the error.  By the way, I've never seen fcntl fail in this way
}

Under Linux, on kernels > 2.6.27 you can also create sockets non-blocking from the outset using socket() and accept4().

e.g.

   // client side
   int socketfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);

   // server side - see man page for accept4 under linux 
   int socketfd = accept4( ... , SOCK_NONBLOCK);

It saves a little bit of work, but is less portable so I tend to set it with fcntl().

Printing leading 0's in C

There are 2 ways to output your number with leading zeroes:

Using the 0 flag and the width specifier:

int zipcode = 123;
printf("%05d\n", zipcode);  // outputs 00123

Using the precision specifier:

int zipcode = 123;
printf("%.5d\n", zipcode);  // outputs 00123

The difference between these is the handling of negative numbers:

printf("%05d\n", -123);  // outputs -0123 (pad to 5 characters)
printf("%.5d\n", -123);  // outputs -00123 (pad to 5 digits)

Zip codes are unlikely to be negative, so it should not matter.

Note however that zip codes may actually contain letters and dashes, so they should be stored as strings. Including the leading zeroes in the string is straightforward so it solves your problem in a much simpler way.

Note that in both examples above, the 5 width or precision values can be specified as an int argument:

int width = 5;
printf("%0*d\n", width, 123);  // outputs 00123
printf("%.*d\n", width, 123);  // outputs 00123

There is one more trick to know: a precision of 0 causes no output for the value 0:

printf("|%0d|%0d|\n", 0, 1);  // outputs |0|1|
printf("|%.0d|%.0d|\n", 0, 1);  // outputs ||1|

Reading in double values with scanf in c

Format specifier in printf should be %f for doubl datatypes since float datatyles eventually convert to double datatypes inside printf.

There is no provision to print float data. Please find the discussion here : Correct format specifier for double in printf

Use of exit() function

The exit() function is a type of function with a return type without an argument. It's defined by the stdlib header file.

You need to use ( exit(0) or exit(EXIT_SUCCESS)) or (exit(non-zero) or exit(EXIT_FAILURE) ).

What's the Use of '\r' escape sequence?

The program is printing "Hey this is my first hello world ", then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.

How to generate a random integer number from within a range

While Ryan is correct, the solution can be much simpler based on what is known about the source of the randomness. To re-state the problem:

  • There is a source of randomness, outputting integer numbers in range [0, MAX) with uniform distribution.
  • The goal is to produce uniformly distributed random integer numbers in range [rmin, rmax] where 0 <= rmin < rmax < MAX.

In my experience, if the number of bins (or "boxes") is significantly smaller than the range of the original numbers, and the original source is cryptographically strong - there is no need to go through all that rigamarole, and simple modulo division would suffice (like output = rnd.next() % (rmax+1), if rmin == 0), and produce random numbers that are distributed uniformly "enough", and without any loss of speed. The key factor is the randomness source (i.e., kids, don't try this at home with rand()).

Here's an example/proof of how it works in practice. I wanted to generate random numbers from 1 to 22, having a cryptographically strong source that produced random bytes (based on Intel RDRAND). The results are:

Rnd distribution test (22 boxes, numbers of entries in each box):     
 1: 409443    4.55%
 2: 408736    4.54%
 3: 408557    4.54%
 4: 409125    4.55%
 5: 408812    4.54%
 6: 409418    4.55%
 7: 408365    4.54%
 8: 407992    4.53%
 9: 409262    4.55%
10: 408112    4.53%
11: 409995    4.56%
12: 409810    4.55%
13: 409638    4.55%
14: 408905    4.54%
15: 408484    4.54%
16: 408211    4.54%
17: 409773    4.55%
18: 409597    4.55%
19: 409727    4.55%
20: 409062    4.55%
21: 409634    4.55%
22: 409342    4.55%   
total: 100.00%

This is as close to uniform as I need for my purpose (fair dice throw, generating cryptographically strong codebooks for WWII cipher machines such as http://users.telenet.be/d.rijmenants/en/kl-7sim.htm, etc). The output does not show any appreciable bias.

Here's the source of cryptographically strong (true) random number generator: Intel Digital Random Number Generator and a sample code that produces 64-bit (unsigned) random numbers.

int rdrand64_step(unsigned long long int *therand)
{
  unsigned long long int foo;
  int cf_error_status;

  asm("rdrand %%rax; \
        mov $1,%%edx; \
        cmovae %%rax,%%rdx; \
        mov %%edx,%1; \
        mov %%rax, %0;":"=r"(foo),"=r"(cf_error_status)::"%rax","%rdx");
        *therand = foo;
  return cf_error_status;
}

I compiled it on Mac OS X with clang-6.0.1 (straight), and with gcc-4.8.3 using "-Wa,q" flag (because GAS does not support these new instructions).

C non-blocking keyboard input

You probably want kbhit();

//Example will loop until a key is pressed
#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    while(1)
    {
        if(kbhit())
        {
            break;
        }
    }
}

this may not work on all environments. A portable way would be to create a monitoring thread and set some flag on getch();

strdup() - what does it do in C?

It makes a duplicate copy of the string passed in by running a malloc and strcpy of the string passed in. The malloc'ed buffer is returned to the caller, hence the need to run free on the return value.

C - gettimeofday for computing time?

To subtract timevals:

gettimeofday(&t0, 0);
/* ... */
gettimeofday(&t1, 0);
long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;

This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:

long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec;

Where are static variables stored in C and C++?

I don't believe there will be a collision. Using static at the file level (outside functions) marks the variable as local to the current compilation unit (file). It's never visible outside the current file so never has to have a name that can be used externally.

Using static inside a function is different - the variable is only visible to the function (whether static or not), it's just its value is preserved across calls to that function.

In effect, static does two different things depending on where it is. In both cases however, the variable visibility is limited in such a way that you can easily prevent namespace clashes when linking.

Having said that, I believe it would be stored in the DATA section, which tends to have variables that are initialized to values other than zero. This is, of course, an implementation detail, not something mandated by the standard - it only cares about behaviour, not how things are done under the covers.

The "backspace" escape character '\b': unexpected behavior?

Your result will vary depending on what kind of terminal or console program you're on, but yes, on most \b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there.

So for the hello worl part, the code outputs

hello worl
          ^

...(where ^ shows where the cursor is) Then it outputs two \b characters which moves the cursor backward two places without erasing (on your terminal):

hello worl
        ^

Note the cursor is now on the r. Then it outputs d, which overwrites the r and gives us:

hello wodl
         ^

Finally, it outputs \n, which is a non-destructive newline (again, on most terminals, including apparently yours), so the l is left unchanged and the cursor is moved to the beginning of the next line.

How to specify 64 bit integers in c

Try an LL suffix on the number, the compiler may be casting it to an intermediate type as part of the parse. See http://gcc.gnu.org/onlinedocs/gcc/Long-Long.html

long long int i2 = 0x0000444400004444LL;

Additionally, the the compiler is discarding the leading zeros, so 0x000044440000 is becoming 0x44440000, which is a perfectly acceptable 32-bit integer (which is why you aren't seeing any warnings prior to f2).

How to use function srand() with time.h?

#include"stdio.h"//rmv coding for randam number access

#include"conio.h"

#include"time.h"

void main()
{
    time_t t;
    int rmvivek;

    srand(time(&t));
    rmvivek=1;

    while(rmvivek<=5)
    {
        printf("%c\t",rand()%10);
        rmvivek++;
    }
    getch();
}

Do I need to compile the header files in a C program?

Firstly, in general:

If these .h files are indeed typical C-style header files (as opposed to being something completely different that just happens to be named with .h extension), then no, there's no reason to "compile" these header files independently. Header files are intended to be included into implementation files, not fed to the compiler as independent translation units.

Since a typical header file usually contains only declarations that can be safely repeated in each translation unit, it is perfectly expected that "compiling" a header file will have no harmful consequences. But at the same time it will not achieve anything useful.

Basically, compiling hello.h as a standalone translation unit equivalent to creating a degenerate dummy.c file consisting only of #include "hello.h" directive, and feeding that dummy.c file to the compiler. It will compile, but it will serve no meaningful purpose.


Secondly, specifically for GCC:

Many compilers will treat files differently depending on the file name extension. GCC has special treatment for files with .h extension when they are supplied to the compiler as command-line arguments. Instead of treating it as a regular translation unit, GCC creates a precompiled header file for that .h file.

You can read about it here: http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html

So, this is the reason you might see .h files being fed directly to GCC.

Convert ASCII number to ASCII Character in C

You can assign int to char directly.

int a = 65;
char c = a;
printf("%c", c);

In fact this will also work.

printf("%c", a);  // assuming a is in valid range

Removing Spaces from a String in C?

if you are still interested, this function removes spaces from the beginning of the string, and I just had it working in my code:

void removeSpaces(char *str1)  
{
    char *str2; 
    str2=str1;  
    while (*str2==' ') str2++;  
    if (str2!=str1) memmove(str1,str2,strlen(str2)+1);  
}

How to compile C programming in Windows 7?

Microsoft Visual Studio Express

It's a full IDE, with powerful debugging tools, syntax highlighting, etc.

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

What primitive data type is time_t?

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

How to convert integer to char in C?

 void main ()
 {
    int temp,integer,count=0,i,cnd=0;
    char ascii[10]={0};
    printf("enter a number");
    scanf("%d",&integer);


     if(integer>>31)
     {
     /*CONVERTING 2's complement value to normal value*/    
     integer=~integer+1;    
     for(temp=integer;temp!=0;temp/=10,count++);    
     ascii[0]=0x2D;
     count++;
     cnd=1;
     }
     else
     for(temp=integer;temp!=0;temp/=10,count++);    
     for(i=count-1,temp=integer;i>=cnd;i--)
     {

        ascii[i]=(temp%10)+0x30;
        temp/=10;
     }
    printf("\n count =%d ascii=%s ",count,ascii);

 }

segmentation fault : 11

Run your program with valgrind of linked to efence. That will tell you where the pointer is being dereferenced and most likely fix your problem if you fix all the errors they tell you about.

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

Actually, you have it down pat, there's nothing more you need to know :-)

I would just add the following bits:

  • the two operations are opposite ends of the spectrum. & takes a variable and gives you the address, * takes an address and gives you the variable (or contents).
  • arrays "degrade" to pointers when you pass them to functions.
  • you can actually have multiple levels on indirection (char **p means that p is a pointer to a pointer to a char.

As to things working differently, not really:

  • arrays, as already mentioned, degrade to pointers (to the first element in the array) when passed to functions; they don't preserve size information.
  • there are no strings in C, just character arrays that, by convention, represent a string of characters terminated by a zero (\0) character.
  • When you pass the address of a variable to a function, you can de-reference the pointer to change the variable itself (normally variables are passed by value (except for arrays)).

How to get address of a pointer in c/c++?

int a = 10;

To get the address of a, you do: &a (address of a) which returns an int* (pointer to int)

int *p = &a;

Then you store the address of a in p which is of type int*.

Finally, if you do &p you get the address of p which is of type int**, i.e. pointer to pointer to int:

int** p_ptr = &p;

just seen your edit:

to print out the pointer's address, you either need to convert it:

printf("address of pointer is: 0x%0X\n", (unsigned)&p);
printf("address of pointer to pointer is: 0x%0X\n", (unsigned)&p_ptr);

or if your printf supports it, use the %p:

printf("address of pointer is: %p\n", p);
printf("address of pointer to pointer is: %p\n", p_ptr);

How can I get the list of files in a directory using C or C++?

C++17 now has a std::filesystem::directory_iterator, which can be used as

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main() {
    std::string path = "/path/to/directory";
    for (const auto & entry : fs::directory_iterator(path))
        std::cout << entry.path() << std::endl;
}

Also, std::filesystem::recursive_directory_iterator can iterate the subdirectories as well.

How to check if C string is empty

strlen(url)

Returns the length of the string. It counts all characters until a null-byte is found. In your case, check it against 0.

Or just check it manually with:

*url == '\0'

Using Cygwin to Compile a C program; Execution error

when you start in cygwin, you are in your $HOME, like in unix generally, which maps to c:/cygwin/home/$YOURNAME by default. So you could put everything there.

You can also access the c: drive from cygwin through /cygdrive/c/ (e.g. /cygdrive/c/Documents anb Settings/yourname/Desktop).

How to dynamically allocate memory space for a string and get that string from user?

char* load_string()
 {

char* string = (char*) malloc(sizeof(char));
*string = '\0';

int key;
int sizer = 2;

char sup[2] = {'\0'};

while( (key = getc(stdin)) != '\n')
{
    string = realloc(string,sizer * sizeof(char));
    sup[0] = (char) key;
    strcat(string,sup);
    sizer++

}
return string;

}

int main()
  {
char* str;
str = load_string();

return 0;
  }

Print text instead of value from C enum

The question is you want write the name just one times.
I have an ider like this:

#define __ENUM(situation,num) \
    int situation = num;        const char * __##situation##_name = #situation;

    const struct {
        __ENUM(get_other_string, -203);//using a __ENUM Mirco make it ease to write, 
        __ENUM(get_negative_to_unsigned, -204);
        __ENUM(overflow,-205);
//The following two line showing the expanding for __ENUM
        int get_no_num = -201;      const char * __get_no_num_name = "get_no_num";
        int get_float_to_int = -202;        const char * get_float_to_int_name = "float_to_int_name";

    }eRevJson;
#undef __ENUM
    struct sIntCharPtr { int value; const char * p_name; };
//This function transform it to string.
    inline const char * enumRevJsonGetString(int num) {
        sIntCharPtr * ptr = (sIntCharPtr *)(&eRevJson);
        for (int i = 0;i < sizeof(eRevJson) / sizeof(sIntCharPtr);i++) {
            if (ptr[i].value == num) {
                return ptr[i].p_name;
            }
        }
        return "bad_enum_value";
    }

it uses a struct to insert enum, so that a printer to string could follows each enum value define.

int main(int argc, char *argv[]) {  
    int enum_test = eRevJson.get_other_string;
    printf("error is %s, number is %d\n", enumRevJsonGetString(enum_test), enum_test);

>error is get_other_string, number is -203

The difference to enum is builder can not report error if the numbers are repeated. if you don't like write number, __LINE__ could replace it:

#define ____LINE__ __LINE__
#define __ENUM(situation) \
    int situation = (____LINE__ - __BASELINE -2);       const char * __##situation##_name = #situation;
constexpr int __BASELINE = __LINE__;
constexpr struct {
    __ENUM(Sunday);
    __ENUM(Monday);
    __ENUM(Tuesday);
    __ENUM(Wednesday);
    __ENUM(Thursday);
    __ENUM(Friday);
    __ENUM(Saturday);
}eDays;
#undef __ENUM
inline const char * enumDaysGetString(int num) {
    sIntCharPtr * ptr = (sIntCharPtr *)(&eDays);
    for (int i = 0;i < sizeof(eDays) / sizeof(sIntCharPtr);i++) {
        if (ptr[i].value == num) {
            return ptr[i].p_name;
        }
    }
    return "bad_enum_value";
}
int main(int argc, char *argv[]) {  
    int d = eDays.Wednesday;
    printf("day %s, number is %d\n", enumDaysGetString(d), d);
    d = 1;
    printf("day %s, number is %d\n", enumDaysGetString(d), d);
}

>day Wednesday, number is 3 >day Monday, number is 1

Segmentation Fault - C

Your scanf("%s", s); is commented out. That means s is uninitialized, so when this line ln = strlen(s); executes, you get a seg fault.

It always helps to initialize a pointer to NULL, and then test for null before using the pointer.

Why use pointers?

Let me try and answer this too.

Pointers are similar to references. In other words, they're not copies, but rather a way to refer to the original value.

Before anything else, one place where you will typically have to use pointers a lot is when you're dealing with embedded hardware. Maybe you need to toggle the state of a digital IO pin. Maybe you're processing an interrupt and need to store a value at a specific location. You get the picture. However, if you're not dealing with hardware directly and are just wondering about which types to use, read on.

Why use pointers as opposed to normal variables? The answer becomes clearer when you're dealing with complex types, like classes, structures and arrays. If you were to use a normal variable, you might end up making a copy (compilers are smart enough to prevent this in some situations and C++11 helps too, but we'll stay away from that discussion for now).

Now what happens if you want to modify the original value? You could use something like this:

MyType a; //let's ignore what MyType actually is right now.
a = modify(a); 

That will work just fine and if you don't know exactly why you're using pointers, you shouldn't use them. Beware of the "they're probably faster" reason. Run your own tests and if they actually are faster, then use them.

However, let's say you're solving a problem where you need to allocate memory. When you allocate memory, you need to deallocate it. The memory allocation may or may not be successful. This is where pointers come in useful - they allow you to test for the existence of the object you've allocated and they allow you to access the object the memory was allocated for by de-referencing the pointer.

MyType *p = NULL; //empty pointer
if(p)
{
    //we never reach here, because the pointer points to nothing
}
//now, let's allocate some memory
p = new MyType[50000];
if(p) //if the memory was allocated, this test will pass
{
    //we can do something with our allocated array
    for(size_t i=0; i!=50000; i++)
    {
        MyType &v = *(p+i); //get a reference to the ith object
        //do something with it
        //...
    }
    delete[] p; //we're done. de-allocate the memory
}

This is the key to why you would use pointers - references assume the element you're referencing exists already. A pointer does not.

The other reason why you would use pointers (or at least end up having to deal with them) is because they're a data type that existed before references. Therefore, if you end up using libraries to do the things that you know they're better at, you will find that a lot of these libraries use pointers all over the place, simply because of how long they've been around (a lot of them were written before C++).

If you didn't use any libraries, you could design your code in such a way that you could stay away from pointers, but given that pointers are one of the basic types of the language, the faster you get comfortable using them, the more portable your C++ skills would be.

From a maintainability point of view, I should also mention that when you do use pointers, you either have to test for their validity and handle the case when they're not valid, or, just assume they are valid and accept the fact that your program will crash or worse WHEN that assumption is broken. Put another way, your choice with pointers is to either introduce code complexity or more maintenance effort when something breaks and you're trying to track down a bug that belongs to a whole class of errors that pointers introduce, like memory corruption.

So if you control all of your code, stay away from pointers and instead use references, keeping them const when you can. This will force you to think about the life times of your objects and will end up keeping your code easier to understand.

Just remember this difference: A reference is essentially a valid pointer. A pointer is not always valid.

So am I saying that its impossible to create an invalid reference? No. Its totally possible, because C++ lets you do almost anything. It's just harder to do unintentionally and you will be amazed at how many bugs are unintentional :)

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

Instead of overriding the library search path at runtime with LD_LIBRARY_PATH, you could instead bake it into the binary itself with rpath. If you link with GCC adding -Wl,-rpath,<libdir> should do the trick, if you link with ld it's just -rpath <libdir>.

malloc for struct and pointer in C

When you malloc(sizeof(struct_name)) it automatically allocates memory for the full size of the struct, you don't need to malloc each element inside.

Use -fsanitize=address flag to check how you used your program memory.

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

How do I find the current machine's full hostname in C (hostname and domain information)?

To get a fully qualified name for a machine, we must first get the local hostname, and then lookup the canonical name.

The easiest way to do this is by first getting the local hostname using uname() or gethostname() and then performing a lookup with gethostbyname() and looking at the h_name member of the struct it returns. If you are using ANSI c, you must use uname() instead of gethostname().

Example:

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
printf("Hostname: %s\n", hostname);
struct hostent* h;
h = gethostbyname(hostname);
printf("h_name: %s\n", h->h_name);

Unfortunately, gethostbyname() is deprecated in the current POSIX specification, as it doesn't play well with IPv6. A more modern version of this code would use getaddrinfo().

Example:

struct addrinfo hints, *info, *p;
int gai_result;

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;

if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
    exit(1);
}

for(p = info; p != NULL; p = p->ai_next) {
    printf("hostname: %s\n", p->ai_canonname);
}

freeaddrinfo(info);

Of course, this will only work if the machine has a FQDN to give - if not, the result of the getaddrinfo() ends up being the same as the unqualified hostname.

Reading string from input with space character?

The correct answer is this:

#include <stdio.h>

int main(void)
{
    char name[100];

    printf("Enter your name: ");
    // pay attention to the space in front of the %
    //that do all the trick
    scanf(" %[^\n]s", name);
    printf("Your Name is: %s", name);

    return 0;
}

That space in front of % is very important, because if you have in your program another few scanf let's say you have 1 scanf of an integer value and another scanf with a double value... when you reach the scanf for your char (string name) that command will be skipped and you can't enter value for it... but if you put that space in front of % will be ok everything and not skip nothing.

Endless loop in C/C++

The problem with asking this question is that you'll get so many subjective answers that simply state "I prefer this...". Instead of making such pointless statements, I'll try to answer this question with facts and references, rather than personal opinions.

Through experience, we can probably start by excluding the do-while alternatives (and the goto), as they are not commonly used. I can't recall ever seeing them in live production code, written by professionals.

The while(1), while(true) and for(;;) are the 3 different versions commonly existing in real code. They are of course completely equivalent and results in the same machine code.


for(;;)

  • This is the original, canonical example of an eternal loop. In the ancient C bible The C Programming Language by Kernighan and Ritchie, we can read that:

    K&R 2nd ed 3.5:

    for (;;) {
    ...
    }
    

    is an "infinite" loop, presumably to be broken by other means, such as a break or return. Whether to use while or for is largely a matter of personal preference.

    For a long while (but not forever), this book was regarded as canon and the very definition of the C language. Since K&R decided to show an example of for(;;), this would have been regarded as the most correct form at least up until the C standardization in 1990.

    However, K&R themselves already stated that it was a matter of preference.

    And today, K&R is a very questionable source to use as a canonical C reference. Not only is it outdated several times over (not addressing C99 nor C11), it also preaches programming practices that are often regarded as bad or blatantly dangerous in modern C programming.

    But despite K&R being a questionable source, this historical aspect seems to be the strongest argument in favour of the for(;;).

  • The argument against the for(;;) loop is that it is somewhat obscure and unreadable. To understand what the code does, you must know the following rule from the standard:

    ISO 9899:2011 6.8.5.3:

    for ( clause-1 ; expression-2 ; expression-3 ) statement
    

    /--/

    Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

    Based on this text from the standard, I think most will agree that it is not only obscure, it is subtle as well, since the 1st and 3rd part of the for loop are treated differently than the 2nd, when omitted.


while(1)

  • This is supposedly a more readable form than for(;;). However, it relies on another obscure, although well-known rule, namely that C treats all non-zero expressions as boolean logical true. Every C programmer is aware of that, so it is not likely a big issue.

  • There is one big, practical problem with this form, namely that compilers tend to give a warning for it: "condition is always true" or similar. That is a good warning, of a kind which you really don't want to disable, because it is useful for finding various bugs. For example a bug such as while(i = 1), when the programmer intended to write while(i == 1).

    Also, external static code analysers are likely to whine about "condition is always true".


while(true)

  • To make while(1) even more readable, some use while(true) instead. The consensus among programmers seem to be that this is the most readable form.

  • However, this form has the same problem as while(1), as described above: "condition is always true" warnings.

  • When it comes to C, this form has another disadvantage, namely that it uses the macro true from stdbool.h. So in order to make this compile, we need to include a header file, which may or may not be inconvenient. In C++ this isn't an issue, since bool exists as a primitive data type and true is a language keyword.

  • Yet another disadvantage of this form is that it uses the C99 bool type, which is only available on modern compilers and not backwards compatible. Again, this is only an issue in C and not in C++.


So which form to use? Neither seems perfect. It is, as K&R already said back in the dark ages, a matter of personal preference.

Personally, I always use for(;;) just to avoid the compiler/analyser warnings frequently generated by the other forms. But perhaps more importantly because of this:

If even a C beginner knows that for(;;) means an eternal loop, then who are you trying to make the code more readable for?

I guess that's what it all really boils down to. If you find yourself trying to make your source code readable for non-programmers, who don't even know the fundamental parts of the programming language, then you are only wasting time. They should not be reading your code.

And since everyone who should be reading your code already knows what for(;;) means, there is no point in making it further readable - it is already as readable as it gets.

How to free memory from char array in C

The memory associated with arr is freed automatically when arr goes out of scope. It is either a local variable, or allocated statically, but it is not dynamically allocated.

A simple rule for you to follow is that you must only every call free() on a pointer that was returned by a call to malloc, calloc or realloc.

static and extern global variables in C and C++

Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

const int varGlobal = 7;

And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

Header included by multiple files:

extern int varGlobal;

In one of your source files:

int varGlobal = 7;

Reading file using fscanf() in C

scanf() and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:

#include <stdio.h>
#include <errno.h>
#include <stdbool.h>

int main(void)
{
    char item[9], status;

    FILE *fp;

    if((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
        printf("No such file\n");
        exit(1);
    }

    while (true) {
        int ret = fscanf(fp, "%s %c", item, &status);
        if(ret == 2)
            printf("\n%s \t %c", item, status);
        else if(errno != 0) {
            perror("scanf:");
            break;
        } else if(ret == EOF) {
            break;
        } else {
            printf("No match.\n");
        }
    }
    printf("\n");
    if(feof(fp)) {
        puts("EOF");
    }
    return 0;
}

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

Converting from signed char to unsigned char and back again?

Yes this is safe.

The c language uses a feature called integer promotion to increase the number of bits in a value before performing calculations. Therefore your CLAMP255 macro will operate at integer (probably 32 bit) precision. The result is assigned to a jbyte, which reduces the integer precision back to 8 bits fit in to the jbyte.

Parsing JSON using C

I used JSON-C for a work project and would recommend it. Lightweight and is released with open licensing.

Documentation is included in the distribution. You basically have *_add functions to create JSON objects, equivalent *_put functions to release their memory, and utility functions that convert types and output objects in string representation.

The licensing allows inclusion with your project. We used it in this way, compiling JSON-C as a static library that is linked in with the main build. That way, we don't have to worry about dependencies (other than installing Xcode).

JSON-C also built for us under OS X (x86 Intel) and Linux (x86 Intel) without incident. If your project needs to be portable, this is a good start.

C compile : collect2: error: ld returned 1 exit status

This issue appears when you have a running console at the time you try to run other (or the same) program.

I had this problem during executing a program on Sublime Text while I had another one running on DevC++ already.

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

I was able to sort this out using Gorgando's fix, but instead of moving imports away, I commented each out individually, built the app, then edited accordingly until I got rid of them.

Why does ENOENT mean "No such file or directory"?

It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE would have been too narrow in its meaning.

What's the difference between "static" and "static inline" function?

From my experience with GCC I know that static and static inline differs in a way how compiler issue warnings about unused functions. More precisely when you declare static function and it isn't used in current translation unit then compiler produce warning about unused function, but you can inhibit that warning with changing it to static inline.

Thus I tend to think that static should be used in translation units and benefit from extra check compiler does to find unused functions. And static inline should be used in header files to provide functions that can be in-lined (due to absence of external linkage) without issuing warnings.

Unfortunately I cannot find any evidence for that logic. Even from GCC documentation I wasn't able to conclude that inline inhibits unused function warnings. I'd appreciate if someone will share links to description of that.

semaphore implementation

Vary the consumer-rate and the producer-rate (using sleep), to better understand the operation of code. The code below is the consumer-producer simulation (over a max-limit on container).

Code for your reference:

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

sem_t semP, semC;
int stock_count = 0;
const int stock_max_limit=5;

void *producer(void *arg) {
    int i, sum=0;
    for (i = 0; i < 10; i++) {

        while(stock_max_limit == stock_count){
            printf("stock overflow, production on wait..\n");
            sem_wait(&semC);
            printf("production operation continues..\n");
        }

        sleep(1);   //production decided here
        stock_count++;
        printf("P::stock-count : %d\n",stock_count);
        sem_post(&semP);
        printf("P::post signal..\n");
    }
 }

void *consumer(void *arg) {
    int i, sum=0;
    for (i = 0; i < 10; i++) {

        while(0 == stock_count){
            printf("stock empty, consumer on wait..\n");
            sem_wait(&semP);
            printf("consumer operation continues..\n");
        }

        sleep(2);   //consumer rate decided here
        stock_count--;
        printf("C::stock-count : %d\n", stock_count);
        sem_post(&semC);
        printf("C::post signal..\n");
        }
}

int main(void) {

    pthread_t tid0,tid1;
    sem_init(&semP, 0, 0);
    sem_init(&semC, 0, 0);

        pthread_create(&tid0, NULL, consumer, NULL);
        pthread_create(&tid1, NULL, producer, NULL);
        pthread_join(tid0, NULL);
        pthread_join(tid1, NULL);

    sem_destroy(&semC);
    sem_destroy(&semP);

    return 0;
}

C: scanf to array

if (array[0]=1) should be if (array[0]==1).

The same with else if (array[0]=2).

Note that the expression of the assignment returns the assigned value, in this case if (array[0]=1) will be always true, that's why the code below the if-statement will be always executed if you don't change the = to ==.

= is the assignment operator, you want to compare, not to assign. So you need ==.

Another thing, if you want only one integer, why are you using array? You might want also to scanf("%d", &array[0]);

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

For anyone wondering about the difference between -1.#IND00 and -1.#IND (which the question specifically asked, and none of the answers address):

-1.#IND00

This specifically means a non-zero number divided by zero, e.g. 3.14 / 0 (source)

-1.#IND (a synonym for NaN)

This means one of four things (see wiki from source):

1) sqrt or log of a negative number

2) operations where both variables are 0 or infinity, e.g. 0 / 0

3) operations where at least one variable is already NaN, e.g. NaN * 5

4) out of range trig, e.g. arcsin(2)

What is the format specifier for unsigned short int?

Here is a good table for printf specifiers. So it should be %hu for unsigned short int.

And link to Wikipedia "C data types" too.

close vs shutdown socket?

None of the existing answers tell people how shutdown and close works at the TCP protocol level, so it is worth to add this.

A standard TCP connection gets terminated by 4-way finalization:

  1. Once a participant has no more data to send, it sends a FIN packet to the other
  2. The other party returns an ACK for the FIN.
  3. When the other party also finished data transfer, it sends another FIN packet
  4. The initial participant returns an ACK and finalizes transfer.

However, there is another "emergent" way to close a TCP connection:

  1. A participant sends an RST packet and abandons the connection
  2. The other side receives an RST and then abandon the connection as well

In my test with Wireshark, with default socket options, shutdown sends a FIN packet to the other end but it is all it does. Until the other party send you the FIN packet you are still able to receive data. Once this happened, your Receive will get an 0 size result. So if you are the first one to shut down "send", you should close the socket once you finished receiving data.

On the other hand, if you call close whilst the connection is still active (the other side is still active and you may have unsent data in the system buffer as well), an RST packet will be sent to the other side. This is good for errors. For example, if you think the other party provided wrong data or it refused to provide data (DOS attack?), you can close the socket straight away.

My opinion of rules would be:

  1. Consider shutdown before close when possible
  2. If you finished receiving (0 size data received) before you decided to shutdown, close the connection after the last send (if any) finished.
  3. If you want to close the connection normally, shutdown the connection (with SHUT_WR, and if you don't care about receiving data after this point, with SHUT_RD as well), and wait until you receive a 0 size data, and then close the socket.
  4. In any case, if any other error occurred (timeout for example), simply close the socket.

Ideal implementations for SHUT_RD and SHUT_WR

The following haven't been tested, trust at your own risk. However, I believe this is a reasonable and practical way of doing things.

If the TCP stack receives a shutdown with SHUT_RD only, it shall mark this connection as no more data expected. Any pending and subsequent read requests (regardless whichever thread they are in) will then returned with zero sized result. However, the connection is still active and usable -- you can still receive OOB data, for example. Also, the OS will drop any data it receives for this connection. But that is all, no packages will be sent to the other side.

If the TCP stack receives a shutdown with SHUT_WR only, it shall mark this connection as no more data can be sent. All pending write requests will be finished, but subsequent write requests will fail. Furthermore, a FIN packet will be sent to another side to inform them we don't have more data to send.

Difference between malloc and calloc?

Both malloc and calloc allocate memory, but calloc initialises all the bits to zero whereas malloc doesn't.

Calloc could be said to be equivalent to malloc + memset with 0 (where memset sets the specified bits of memory to zero).

So if initialization to zero is not necessary, then using malloc could be faster.

Is there a printf converter to print in binary format?

void
print_binary(unsigned int n)
{
    unsigned int mask = 0;
    /* this grotesque hack creates a bit pattern 1000... */
    /* regardless of the size of an unsigned int */
    mask = ~mask ^ (~mask >> 1);

    for(; mask != 0; mask >>= 1) {
        putchar((n & mask) ? '1' : '0');
    }

}

How to print variable addresses in C?

You want to use %p to print a pointer. From the spec:

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

And don't forget the cast, e.g.

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

How exactly does __attribute__((constructor)) work?

Here is a "concrete" (and possibly useful) example of how, why, and when to use these handy, yet unsightly constructs...

Xcode uses a "global" "user default" to decide which XCTestObserver class spews it's heart out to the beleaguered console.

In this example... when I implicitly load this psuedo-library, let's call it... libdemure.a, via a flag in my test target á la..

OTHER_LDFLAGS = -ldemure

I want to..

  1. At load (ie. when XCTest loads my test bundle), override the "default" XCTest "observer" class... (via the constructor function) PS: As far as I can tell.. anything done here could be done with equivalent effect inside my class' + (void) load { ... } method.

  2. run my tests.... in this case, with less inane verbosity in the logs (implementation upon request)

  3. Return the "global" XCTestObserver class to it's pristine state.. so as not to foul up other XCTest runs which haven't gotten on the bandwagon (aka. linked to libdemure.a). I guess this historically was done in dealloc.. but I'm not about to start messing with that old hag.

So...

#define USER_DEFS NSUserDefaults.standardUserDefaults

@interface      DemureTestObserver : XCTestObserver @end
@implementation DemureTestObserver

__attribute__((constructor)) static void hijack_observer() {

/*! here I totally hijack the default logging, but you CAN
    use multiple observers, just CSV them, 
    i.e. "@"DemureTestObserverm,XCTestLog"
*/
  [USER_DEFS setObject:@"DemureTestObserver" 
                forKey:@"XCTestObserverClass"];
  [USER_DEFS synchronize];
}

__attribute__((destructor)) static void reset_observer()  {

  // Clean up, and it's as if we had never been here.
  [USER_DEFS setObject:@"XCTestLog" 
                forKey:@"XCTestObserverClass"];
  [USER_DEFS synchronize];
}

...
@end

Without the linker flag... (Fashion-police swarm Cupertino demanding retribution, yet Apple's default prevails, as is desired, here)

enter image description here

WITH the -ldemure.a linker flag... (Comprehensible results, gasp... "thanks constructor/destructor"... Crowd cheers) enter image description here

What does it mean to write to stdout in C?

That means that you are printing output on the main output device for the session... whatever that may be. The user's console, a tty session, a file or who knows what. What that device may be varies depending on how the program is being run and from where.

The following command will write to the standard output device (stdout)...

printf( "hello world\n" );

Which is just another way, in essence, of doing this...

fprintf( stdout, "hello world\n" );

In which case stdout is a pointer to a FILE stream that represents the default output device for the application. You could also use

fprintf( stderr, "that didn't go well\n" );

in which case you would be sending the output to the standard error output device for the application which may, or may not, be the same as stdout -- as with stdout, stderr is a pointer to a FILE stream representing the default output device for error messages.

What is more efficient? Using pow to square or just multiply it with itself?

If the exponent is constant and small, expand it out, minimizing the number of multiplications. (For example, x^4 is not optimally x*x*x*x, but y*y where y=x*x. And x^5 is y*y*x where y=x*x. And so on.) For constant integer exponents, just write out the optimized form already; with small exponents, this is a standard optimization that should be performed whether the code has been profiled or not. The optimized form will be quicker in so large a percentage of cases that it's basically always worth doing.

(If you use Visual C++, std::pow(float,int) performs the optimization I allude to, whereby the sequence of operations is related to the bit pattern of the exponent. I make no guarantee that the compiler will unroll the loop for you, though, so it's still worth doing it by hand.)

[edit] BTW pow has a (un)surprising tendency to crop up on the profiler results. If you don't absolutely need it (i.e., the exponent is large or not a constant), and you're at all concerned about performance, then best to write out the optimal code and wait for the profiler to tell you it's (surprisingly) wasting time before thinking further. (The alternative is to call pow and have the profiler tell you it's (unsurprisingly) wasting time -- you're cutting out this step by doing it intelligently.)

Source file not compiled Dev C++

This error occurred because your settings are not correct.

For example I receive

cannot open output file Project1.exe: Permission denied
collect2.exe: error: ld returned 1 exit status

mingw32-make.exe: *** [Project1.exe] Error 1

Because I have no permission to write on my exe file.

Where does gcc look for C and C++ header files?

`gcc -print-prog-name=cc1plus` -v

This command asks gcc which C++ preprocessor it is using, and then asks that preprocessor where it looks for includes.

You will get a reliable answer for your specific setup.

Likewise, for the C preprocessor:

`gcc -print-prog-name=cpp` -v

C compiling - "undefined reference to"?

As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.

Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,

int main()
{
  int a = func();
}

int func()
{
   return 1;
}

However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.

int func();

int main()
{
   int a = func();
}

int func()
{
  return 1;
}

How to append strings using sprintf?

Use strcat http://www.cplusplus.com/reference/cstring/strcat/

int main ()
    {
      char str[80];
      strcpy (str,"these ");
      strcat (str,"strings ");
      strcat (str,"are ");
      strcat (str,"concatenated.");
      puts (str);
      return 0;
    }




    Output:


    these strings are concatenated. 

What does the question mark and the colon (?: ternary operator) mean in objective-c?

Fun fact, in objective-c if you want to check null / nil For example:

-(NSString*) getSomeStringSafeCheck
{
    NSString *string = [self getSomeString];
    if(string != nil){
        return String;
    }
    return @"";
}

The quick way to do it is:

-(NSString*) getSomeStringSafeCheck
{
    return [self getSomeString] != nil ? [self getSomeString] : @"";
}

Then you can update it to a simplest way:

-(NSString*) getSomeStringSafeCheck
{
    return [self getSomeString]?: @"";
}

Because in Objective-C:

  1. if an object is nil, it will return false as boolean;
  2. Ternary Operator's second parameter can be empty, as it will return the result on the left of '?'

So let say you write:

[self getSomeString] != nil?: @"";

the second parameter is returning a boolean value, thus a exception is thrown.

How to get substring in C

char originalString[] = "THESTRINGHASNOSPACES";

    char aux[5];
    int j=0;
    for(int i=0;i<strlen(originalString);i++){
        aux[j] = originalString[i];
        if(j==3){
            aux[j+1]='\0'; 
            printf("%s\n",aux);
            j=0;
        }else{
            j++;
        }
    }

How do I pass a command line argument while starting up GDB in Linux?

Once gdb starts, you can run the program using "r args".

So if you are running your code by:

$ executablefile arg1 arg2 arg3 

Debug it on gdb by:

$ gdb executablefile  
(gdb) r arg1 arg2 arg3

C - The %x format specifier

Break-down:

  • 8 says that you want to show 8 digits
  • 0 that you want to prefix with 0's instead of just blank spaces
  • x that you want to print in lower-case hexadecimal.

Quick example (thanks to Grijesh Chauhan):

#include <stdio.h>
int main() {
    int data = 29;
    printf("%x\n", data);    // just print data
    printf("%0x\n", data);   // just print data ('0' on its own has no effect)
    printf("%8x\n", data);   // print in 8 width and pad with blank spaces
    printf("%08x\n", data);  // print in 8 width and pad with 0's

    return 0;
}

Output:

1d
1d
      1d
0000001d

Also see http://www.cplusplus.com/reference/cstdio/printf/ for reference.

How to prevent gcc optimizing some statements in C?

Instead of using the new pragmas, you can also use __attribute__((optimize("O0"))) for your needs. This has the advantage of just applying to a single function and not all functions defined in the same file.

Usage example:

void __attribute__((optimize("O0"))) foo(unsigned char data) {
    // unmodifiable compiler code
}

uint8_t vs unsigned char

On almost every system I've met uint8_t == unsigned char, but this is not guaranteed by the C standard. If you are trying to write portable code and it matters exactly what size the memory is, use uint8_t. Otherwise use unsigned char.

"Press Any Key to Continue" function in C

Use getch():

printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();

Windows alternative should be _getch().

If you're using Windows, this should be the full example:

#include <conio.h>
#include <ctype.h>

int main( void )
{
    printf("Let the Battle Begin!\n");
    printf("Press Any Key to Continue\n");
    _getch();
}

P.S. as @Rörd noted, if you're on POSIX system, you need to make sure that curses library is setup right.

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

How to reverse a singly linked list using only two pointers?

Using two pointers while maintaining time complexity of O(n), the fastest achievable, might only be possible through number casting of pointers and swapping their values. Here is an implementation:

#include <stdio.h>

typedef struct node
{
    int num;
    struct node* next;
}node;

void reverse(node* head)
{
   node* ptr;
   if(!head || !head->next || !head->next->next) return;
   ptr = head->next->next;
   head->next->next = NULL;
   while(ptr)
   {
     /* Swap head->next and ptr. */
     head->next = (unsigned)(ptr =\
     (unsigned)ptr ^ (unsigned)(head->next =\
     (unsigned)head->next ^ (unsigned)ptr)) ^ (unsigned)head->next;

     /* Swap head->next->next and ptr. */
     head->next->next = (unsigned)(ptr =\
     (unsigned)ptr ^ (unsigned)(head->next->next =\
     (unsigned)head->next->next ^ (unsigned)ptr)) ^ (unsigned)head->next->next;
   }
}

void add_end(node* ptr, int n)
{
    while(ptr->next) ptr = ptr->next;
    ptr->next = malloc(sizeof(node));
    ptr->next->num = n;
    ptr->next->next = NULL;
}

void print(node* ptr)
{
    while(ptr = ptr->next) printf("%d ", ptr->num);
    putchar('\n');
}

void erase(node* ptr)
{
    node *end;
    while(ptr->next)
    {
        if(ptr->next->next) ptr = ptr->next;
        else
        {
            end = ptr->next;
            ptr->next = NULL;
            free(end);
        }
    }
}

void main()
{
    int i, n = 5;
    node* dummy_head;
    dummy_head->next = NULL;
    for(i = 1; i <= n ; ++i) add_end(dummy_head, i);
    print(dummy_head);
    reverse(dummy_head);
    print(dummy_head);
    erase(dummy_head);
}

What integer hash function are good that accepts an integer hash key?

I have been using splitmix64 (pointed in Thomas Mueller's answer) ever since I found this thread. However, I recently stumbled upon Pelle Evensen's rrxmrrxmsx_0, which yielded tremendously better statistical distribution than the original MurmurHash3 finalizer and its successors (splitmix64 and other mixes). Here is the code snippet in C:

#include <stdint.h>

static inline uint64_t ror64(uint64_t v, int r) {
    return (v >> r) | (v << (64 - r));
}

uint64_t rrxmrrxmsx_0(uint64_t v) {
    v ^= ror64(v, 25) ^ ror64(v, 50);
    v *= 0xA24BAED4963EE407UL;
    v ^= ror64(v, 24) ^ ror64(v, 49);
    v *= 0x9FB21C651E98DF25UL;
    return v ^ v >> 28;
}

Pelle also provides an in-depth analysis of the 64-bit mixer used in the final step of MurmurHash3 and the more recent variants.

How do you implement a class in C?

Also see this answer and this one

It is possible. It always seems like a good idea at the time but afterwards it becomes a maintenance nightmare. Your code become littered with pieces of code tying everything together. A new programmer will have lots of problems reading and understanding the code if you use function pointers since it will not be obvious what functions is called.

Data hiding with get/set functions is easy to implement in C but stop there. I have seen multiple attempts at this in the embedded environment and in the end it is always a maintenance problem.

Since you all ready have maintenance issues I would steer clear.

What is size_t in C?

The manpage for types.h says:

size_t shall be an unsigned integer type

Read int values from a text file in C

How about this?

fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2); 

In this case spaces in fscanf match multiple occurrences of any whitespace until the next token in found.

error: function returns address of local variable

a is defined locally in the function, and can't be used outside the function. If you want to return a char array from the function, you'll need to allocate it dynamically:

char *a = malloc(1000);

And at some point call free on the returned pointer.

You should also see a warning at this line: char b = "blah";: you're trying to assign a string literal to a char.

C: Run a System Command and Get Output?

You need some sort of Inter Process Communication. Use a pipe or a shared buffer.

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

There is no difference between the %i and %d format specifiers for printf. We can see this by going to the draft C99 standard section 7.19.6.1 The fprintf function which also covers printf with respect to format specifiers and it says in paragraph 8:

The conversion specifiers and their meanings are:

and includes the following bullet:

d,i     The int argument is converted to signed decimal in the style
        [-]dddd. The precision specifies the minimum number of digits to
        appear; if the value being converted can be represented in fewer
        digits, it is expanded with leading zeros. The default precision is
        1. The result of converting a zero value with a precision of zero is
        no characters.

On the other hand for scanf there is a difference, %d assume base 10 while %i auto detects the base. We can see this by going to section 7.19.6.2 The fscanf function which covers scanf with respect to format specifier, in paragraph 12 it says:

The conversion specifiers and their meanings are:

and includes the following:

d     Matches an optionally signed decimal integer, whose format is the
      same as expected for the subject sequence of the strtol function with
      the value 10 for the base argument. The corresponding argument shall
      be a pointer to signed integer.

i     Matches an optionally signed integer, whose format is the same as
      expected for the subject sequence of the strtol function with the
      value 0 for the base argument. The corresponding argument shall be a
      pointer to signed integer.

Why dividing two integers doesn't get a float?

Use casting of types:

int main() {
    int a;
    float b, c, d;
    a = 750;
    b = a / (float)350;
    c = 750;
    d = c / (float)350;
    printf("%.2f %.2f", b, d);
    // output: 2.14 2.14
}

This is another way to solve that:

 int main() {
        int a;
        float b, c, d;
        a = 750;
        b = a / 350.0; //if you use 'a / 350' here, 
                       //then it is a division of integers, 
                       //so the result will be an integer
        c = 750;
        d = c / 350;
        printf("%.2f %.2f", b, d);
        // output: 2.14 2.14
    }

However, in both cases you are telling the compiler that 350 is a float, and not an integer. Consequently, the result of the division will be a float, and not an integer.

How to Convert double to int in C?

int b;
double a;
a=3669.0;
b=a;
printf("b=%d",b);

this code gives the output as b=3669 only you check it clearly.

Difference between int32, int, int32_t, int8 and int8_t

Always keep in mind that 'size' is variable if not explicitly specified so if you declare

 int i = 10;

On some systems it may result in 16-bit integer by compiler and on some others it may result in 32-bit integer (or 64-bit integer on newer systems).

In embedded environments this may end up in weird results (especially while handling memory mapped I/O or may be consider a simple array situation), so it is highly recommended to specify fixed size variables. In legacy systems you may come across

 typedef short INT16;
 typedef int INT32;
 typedef long INT64; 

Starting from C99, the designers added stdint.h header file that essentially leverages similar typedefs.

On a windows based system, you may see entries in stdin.h header file as

 typedef signed char       int8_t;
 typedef signed short      int16_t;
 typedef signed int        int32_t;
 typedef unsigned char     uint8_t;

There is quite more to that like minimum width integer or exact width integer types, I think it is not a bad thing to explore stdint.h for a better understanding.

how to return a char array from a function in C

Lazy notes in comments.

#include <stdio.h>
// for malloc
#include <stdlib.h>

// you need the prototype
char *substring(int i,int j,char *ch);


int main(void /* std compliance */)
{
  int i=0,j=2;
  char s[]="String";
  char *test;
  // s points to the first char, S
  // *s "is" the first char, S
  test=substring(i,j,s); // so s only is ok
  // if test == NULL, failed, give up
  printf("%s",test);
  free(test); // you should free it
  return 0;
}


char *substring(int i,int j,char *ch)
{
  int k=0;
  // avoid calc same things several time
  int n = j-i+1; 
  char *ch1;
  // you can omit casting - and sizeof(char) := 1
  ch1=malloc(n*sizeof(char));
  // if (!ch1) error...; return NULL;

  // any kind of check missing:
  // are i, j ok? 
  // is n > 0... ch[i] is "inside" the string?...
  while(k<n)
    {   
      ch1[k]=ch[i];
      i++;k++;
    }   

  return ch1;
}

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

Do aman 2 sendfile. You only need to open the source file on the client and destination file on the server, then call sendfile and the kernel will chop and move the data.

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.

How to Initialize char array from a string

This compiles fine on gcc version 4.3.3 (Ubuntu 4.3.3-5ubuntu4).

const char s[] = "cheese";

int main()
{
    return 0;
}

What does OpenCV's cvWaitKey( ) function do?

/* Assuming this is a while loop -> e.g. video stream where img is obtained from say web camera.*/    
cvShowImage("Window",img);

/* A small interval of 10 milliseconds. This may be necessary to display the image correctly */
cvWaitKey(10);  

/* to wait until user feeds keyboard input replace with cvWaitKey(0); */

A free tool to check C/C++ source code against a set of coding standards?

I have used a tool in my work its LDRA tool suite

It is used for testing the c/c++ code but it also can check against coding standards such as MISRA etc.

Compiler warning - suggest parentheses around assignment used as truth value

Be explicit - then the compiler won't warn that you perhaps made a mistake.

while ( (list = list->next) != NULL )

or

while ( (list = list->next) )

Some day you'll be glad the compiler told you, people do make that mistake ;)

How can I multiply and divide using only bit shifting and adding?

To multiply in terms of adding and shifting you want to decompose one of the numbers by powers of two, like so:

21 * 5 = 10101_2 * 101_2             (Initial step)
       = 10101_2 * (1 * 2^2  +  0 * 2^1  +  1 * 2^0)
       = 10101_2 * 2^2 + 10101_2 * 2^0 
       = 10101_2 << 2 + 10101_2 << 0 (Decomposed)
       = 10101_2 * 4 + 10101_2 * 1
       = 10101_2 * 5
       = 21 * 5                      (Same as initial expression)

(_2 means base 2)

As you can see, multiplication can be decomposed into adding and shifting and back again. This is also why multiplication takes longer than bit shifts or adding - it's O(n^2) rather than O(n) in the number of bits. Real computer systems (as opposed to theoretical computer systems) have a finite number of bits, so multiplication takes a constant multiple of time compared to addition and shifting. If I recall correctly, modern processors, if pipelined properly, can do multiplication just about as fast as addition, by messing with the utilization of the ALUs (arithmetic units) in the processor.

CSS transition effect makes image blurry / moves image 1px, in Chrome?

None of this worked, what worked for me is scaling image down.

So depending on what size you want the image or what resoultion your image is, you can do something like this:

_x000D_
_x000D_
.ok {
      transform: perspective(100px) rotateY(0deg) scale(0.5);
      transition: transform 1s;
      object-fit:contain;
}
.ok:hover{
      transform: perspective(100px) rotateY(-10deg) scale(0.5);
}

/* Demo Preview Stuff */
.bad {
   max-width: 320px;
   object-fit:contain;
   transform: perspective(100px) rotateY(0deg);
   transition: transform 1s;
}
.bad:hover{
      transform: perspective(100px) rotateY(-10deg);
}

div {
     text-align: center;
     position: relative;
     display: flex;
}
h3{
    position: absolute;
    bottom: 30px;
    left: 0;
    right: 0;
}
     
.b {
    display: flex;
}
_x000D_
<center>
<h2>Hover on images</h2>
<div class="b">
<div>
  <img class="ok" src='https://www.howtogeek.com/wp-content/uploads/2018/10/preview-11.png'>
  <h3>Sharp</h3>
</div>

<div>
  <img class="bad" src='https://www.howtogeek.com/wp-content/uploads/2018/10/preview-11.png'>
  <h3>Blurry</h3>
</div>

</div>

</center>
_x000D_
_x000D_
_x000D_

The image should be scaled down, make sure you have a big image resoultion

Asp.net 4.0 has not been registered

The aspnet_regiis approach described above doesn't appear to work on Windows 8.1:

C:\Windows\system32>aspnet_regiis -i

Microsoft (R) ASP.NET RegIIS version 4.0.30319.33440
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation. All rights reserved.
Start installing ASP.NET (4.0.30319.33440).
This option is not supported on this version of the operating system. Administrators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Windows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlink/?LinkID=216771.
Finished installing ASP.NET (4.0.30319.33440).

As indicated in the message, I went to:

  1. Start
  2. Turn Windows features on or off
  3. .NET Framework 4.5 Advanced Services

and checked ASP.NET 4.5.

This seems to have resolved the problem.

What is the difference between the float and integer data type when the size is the same?

Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point

Import data.sql MySQL Docker Container

Mount your sql-dump under/docker-entrypoint-initdb.d/yourdump.sql utilizing a volume mount

mysql:
  image: mysql:latest
  container_name: mysql-container
  ports:
    - 3306:3306
  volumes:
    - ./dump.sql:/docker-entrypoint-initdb.d/dump.sql
  environment:
    MYSQL_ROOT_PASSWORD: secret
    MYSQL_DATABASE: name_db
    MYSQL_USER: user
    MYSQL_PASSWORD: password

This will trigger an import of the sql-dump during the start of the container, see https://hub.docker.com/_/mysql/ under "Initializing a fresh instance"

Generating random numbers with Swift

look, i had the same problem but i insert the function as a global variable

as

var RNumber = Int(arc4random_uniform(9)+1)

func GetCase(){

your code
}

obviously this is not efficent, so then i just copy and paste the code into the function so it could be reusable, then xcode suggest me to set the var as constant so my code were

func GetCase() {

let RNumber = Int(arc4random_uniform(9)+1)

   if categoria == 1 {
    }
}

well thats a part of my code so xcode tell me something of inmutable and initialization but, it build the app anyway and that advice simply dissapear

hope it helps

Cross-reference (named anchor) in markdown

For anyone who is looking for a solution to this problem in GitBook. This is how I made it work (in GitBook). You need to tag your header explicitly, like this:

# My Anchored Heading {#my-anchor}

Then link to this anchor like this

[link to my anchored heading](#my-anchor)

Solution, and additional examples, may be found here: https://seadude.gitbooks.io/learn-gitbook/

Conda activate not working?

Here's what worked for me using the Git Bash terminal in VS Code on windows in succinct steps:

  1. source activate env-name - You should see your line appended by the (base) tag now.

  2. After calling on source activate, I've found following conda activate commands to work: i.e. conda activate env2-name

What didn't work for Git Bash (as a VS Code terminal) for me: activate env-name and conda activate env-name.

Not exactly sure why this specific behaviour occurs on the Git Bash terminal on VS Code, but the accepted answer + this stackoverflow question I've found might provide clues.

Java 8 stream's .min() and .max(): why does this compile?

I had an error with an array getting the max and the min so my solution was:

int max = Arrays.stream(arrayWithInts).max().getAsInt();
int min = Arrays.stream(arrayWithInts).min().getAsInt();

In angular $http service, How can I catch the "status" of error?

Response status comes as second parameter in callback, (from docs):

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

c# Best Method to create a log file

You can use http://logging.apache.org/ library and use a database appender to collect all your log info together.

Remove the last character from a string

You can use substr:

echo substr('a,b,c,d,e,', 0, -1);
# => 'a,b,c,d,e'

Getting the parent div of element

I had to do recently something similar, I used this snippet:

const getNode = () =>
  for (let el = this.$el; el && el.parentNode; el = el.parentNode){
    if (/* insert your condition here */) return el;
  }
  return null
})

The function will returns the element that fulfills your condition. It was a CSS class on the element that I was looking for. If there isn't such element then it will return null

In case somebody would look for multiple elements it only returns closest parent to the element that you provided.

My example was:

if (el.classList?.contains('o-modal')) return el;

I used it in a vue component (this.$el) change that to your document.getElementById function and you're good to go. Hope it will be useful for some people ??

Error # 1045 - Cannot Log in to MySQL server -> phpmyadmin

In mysql 5.7 the auth mechanism changed, documentation can be found in the official manual here.

Using the system root user (or sudo) you can connect to the mysql database with the mysql 'root' user via CLI. All other users will work, too.

In phpmyadmin however, all mysql users will work, but not the mysql 'root' user.

This comes from here:

$ mysql -Ne "select Host,User,plugin from mysql.user where user='root';"
+-----------+------+-----------------------+
| localhost | root | auth_socket |
|  hostname | root | mysql_native_password |
+-----------+------+-----------------------+

To 'fix' this security feature, do:

mysql -Ne "update mysql.user set plugin='mysql_native_password' where User='root' and Host='localhost'; flush privileges;"

More on this can also be found here in the manual.

Simple insecure two-way data "obfuscation"?

The namespace System.Security.Cryptography contains the TripleDESCryptoServiceProvider and RijndaelManaged classes

Don't forget to add a reference to the System.Security assembly.

XmlWriter to Write to a String Instead of to a File

Use StringBuilder:

var sb = new StringBuilder();
    using (XmlWriter xmlWriter = XmlWriter.Create(sb))
    {
        ...
    }
return sb.ToString();

JavaScript ternary operator example with functions

The ternary style is generally used to save space. Semantically, they are identical. I prefer to go with the full if/then/else syntax because I don't like to sacrifice readability - I'm old-school and I prefer my braces.

The full if/then/else format is used for pretty much everything. It's especially popular if you get into larger blocks of code in each branch, you have a muti-branched if/else tree, or multiple else/ifs in a long string.

The ternary operator is common when you're assigning a value to a variable based on a simple condition or you are making multiple decisions with very brief outcomes. The example you cite actually doesn't make sense, because the expression will evaluate to one of the two values without any extra logic.

Good ideas:

this > that ? alert(this) : alert(that);  //nice and short, little loss of meaning

if(expression)  //longer blocks but organized and can be grasped by humans
{
    //35 lines of code here
}
else if (something_else)
{
    //40 more lines here
}
else if (another_one)  /etc, etc
{
    ...

Less good:

this > that ? testFucntion() ? thirdFunction() ? imlost() : whathappuh() : lostinsyntax() : thisisprobablybrokennow() ? //I'm lost in my own (awful) example by now.
//Not complete... or for average humans to read.

if(this != that)  //Ternary would be done by now
{
    x = this;
}
else
}
    x = this + 2;
}

A really basic rule of thumb - can you understand the whole thing as well or better on one line? Ternary is OK. Otherwise expand it.

How to add files/folders to .gitignore in IntelliJ IDEA?

You can create file .gitignore and then Idea will suggest you install plugin

C# Reflection: How to get class reference from string?

A simple use:

Type typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName");

Sample:

Type dogClass = Type.GetType("Animals.Dog, Animals");

Deleting Row in SQLite in Android

Try like that may you get your solution

String table = "beaconTable";
String whereClause = "_id=?";
String[] whereArgs = new String[] { String.valueOf(row) };
db.delete(table, whereClause, whereArgs);

Switching users inside Docker image to a non-root user

You should not use su in a dockerfile, however you should use the USER instruction in the Dockerfile.

At each stage of the Dockerfile build, a new container is created so any change you make to the user will not persist on the next build stage.

For example:

RUN whoami
RUN su test
RUN whoami

This would never say the user would be test as a new container is spawned on the 2nd whoami. The output would be root on both (unless of course you run USER beforehand).

If however you do:

RUN whoami
USER test
RUN whoami

You should see root then test.

Alternatively you can run a command as a different user with sudo with something like

sudo -u test whoami

But it seems better to use the official supported instruction.

Indentation shortcuts in Visual Studio

You can just use Tab and Shift+Tab

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

wsHttpBinding is a problem because silverlight doesn't support it!

Expand a div to fill the remaining width

Im not sure if this is the answer you are expecting but, why don't you set the width of Tree to 'auto' and width of 'View' to 100% ?

CSS values using HTML5 data attribute

You can create with javascript some css-rules, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/

var addRule = (function (sheet) {
    if(!sheet) return;
    return function (selector, styles) {
        if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
        if (sheet.addRule) return sheet.addRule(selector, styles);
    }
}(document.styleSheets[document.styleSheets.length - 1]));

var i = 101;
while (i--) {
    addRule("[data-width='" + i + "%']", "width:" + i + "%");
}

This creates 100 pseudo-selectors like this:

[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }

Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.

Multidimensional Array [][] vs [,]

double[,] is a 2d array (matrix) while double[][] is an array of arrays (jagged arrays) and the syntax is:

double[][] ServicePoint = new double[10][];

Get the previous month's first and last day dates in c#

using Fluent DateTime https://github.com/FluentDateTime/FluentDateTime

        var lastMonth = 1.Months().Ago().Date;
        var firstDayOfMonth = lastMonth.FirstDayOfMonth();
        var lastDayOfMonth = lastMonth.LastDayOfMonth();

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

raw_input returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3 is "ABABAB"; how much is "L" * 3.14 ? Please do not reply "LLL|"). You need to parse the string to a numerical value.

You might want to try:

salesAmount = float(raw_input("Insert sale amount here\n"))

Check if list contains element that contains a string and get that element

You could use Linq's FirstOrDefault extension method:

string element = myList.FirstOrDefault(s => s.Contains(myString));

This will return the fist element that contains the substring myString, or null if no such element is found.

If all you need is the index, use the List<T> class's FindIndex method:

int index = myList.FindIndex(s => s.Contains(myString));

This will return the the index of fist element that contains the substring myString, or -1 if no such element is found.

jQuery AJAX Call to PHP Script with JSON Return

Make it dataType instead of datatype.

And add below code in php as your ajax request is expecting json and will not accept anything, but json.

header('Content-Type: application/json');

Correct Content type for JSON and JSONP

The response visible in firebug is text data. Check Content-Type of the response header to verify, if the response is json. It should be application/json for dataType:'json' and text/html for dataType:'html'.

Detect when an HTML5 video finishes

You can add listener all video events nicluding ended, loadedmetadata, timeupdate where ended function gets called when video ends

_x000D_
_x000D_
$("#myVideo").on("ended", function() {_x000D_
   //TO DO: Your code goes here..._x000D_
      alert("Video Finished");_x000D_
});_x000D_
_x000D_
$("#myVideo").on("loadedmetadata", function() {_x000D_
      alert("Video loaded");_x000D_
  this.currentTime = 50;//50 seconds_x000D_
   //TO DO: Your code goes here..._x000D_
});_x000D_
_x000D_
_x000D_
$("#myVideo").on("timeupdate", function() {_x000D_
  var cTime=this.currentTime;_x000D_
  if(cTime>0 && cTime % 2 == 0)//Alerts every 2 minutes once_x000D_
      alert("Video played "+cTime+" minutes");_x000D_
   //TO DO: Your code goes here..._x000D_
  var perc=cTime * 100 / this.duration;_x000D_
  if(perc % 10 == 0)//Alerts when every 10% watched_x000D_
      alert("Video played "+ perc +"%");_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <video id="myVideo" controls="controls">_x000D_
    <source src="your_video_file.mp4" type="video/mp4">_x000D_
      <source src="your_video_file.mp4" type="video/ogg">_x000D_
        Your browser does not support HTML5 video._x000D_
  </video>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I restart my C# WinForm Application?

Unfortunately you can't use Process.Start() to start an instance of the currently running process. According to the Process.Start() docs: "If the process is already running, no additional process resource is started..."

This technique will work fine under the VS debugger (because VS does some kind of magic that causes Process.Start to think the process is not already running), but will fail when not run under the debugger. (Note that this may be OS-specific - I seem to remember that in some of my testing, it worked on either XP or Vista, but I may just be remembering running it under the debugger.)

This technique is exactly the one used by the last programmer on the project on which I'm currently working, and I've been trying to find a workaround for this for quite some time. So far, I've only found one solution, and it just feels dirty and kludgy to me: start a 2nd application, that waits in the background for the first application to terminate, then re-launches the 1st application. I'm sure it would work, but, yuck.

Edit: Using a 2nd application works. All I did in the second app was:

    static void RestartApp(int pid, string applicationName )
    {
        // Wait for the process to terminate
        Process process = null;
        try
        {
            process = Process.GetProcessById(pid);
            process.WaitForExit(1000);
        }
        catch (ArgumentException ex)
        {
            // ArgumentException to indicate that the 
            // process doesn't exist?   LAME!!
        }
        Process.Start(applicationName, "");
    }

(This is a very simplified example. The real code has lots of sanity checking, error handling, etc)

Limiting Powershell Get-ChildItem by File Creation Date Range

Fixed it...

Get-ChildItem C:\Windows\ -recurse -include @("*.txt*","*.pdf") |
Where-Object {$_.CreationTime -gt "01/01/2013" -and $_.CreationTime -lt "12/02/2014"} | 
Select-Object FullName, CreationTime, @{Name="Mbytes";Expression={$_.Length/1Kb}}, @{Name="Age";Expression={(((Get-Date) - $_.CreationTime).Days)}} | 
Export-Csv C:\search_TXT-and-PDF_files_01012013-to-12022014_sort.txt

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

this worked for me.

    $('#thedate').datepicker({
    dateFormat: 'dd-mm-yy',
    altField: '#thealtdate',
    altFormat: 'yy-mm-dd'
});

Getting DOM elements by classname

Update: Xpath version of *[@class~='my-class'] css selector

So after my comment below in response to hakre's comment, I got curious and looked into the code behind Zend_Dom_Query. It looks like the above selector is compiled to the following xpath (untested):

[contains(concat(' ', normalize-space(@class), ' '), ' my-class ')]

So the PHP would be:

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

Basically, all we do here is normalize the class attribute so that even a single class is bounded by spaces, and the complete class list is bounded in spaces. Then append the class we are searching for with a space. This way we are effectively looking for and find only instances of my-class .


Use an xpath selector?

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(@class, '$classname')]");

If it is only ever one type of element you can replace the * with the particular tagname.

If you need to do a lot of this with very complex selector I would recommend Zend_Dom_Query which supports CSS selector syntax (a la jQuery):

$finder = new Zend_Dom_Query($html);
$classname = 'my-class';
$nodes = $finder->query("*[class~=\"$classname\"]");

SQL Server - How to lock a table until a stored procedure finishes

Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.

Getting value of select (dropdown) before change

How about using a custom jQuery event with an angular watch type interface;

// adds a custom jQuery event which gives the previous and current values of an input on change
(function ($) {
    // new event type tl_change
    jQuery.event.special.tl_change = {
        add: function (handleObj) {
            // use mousedown and touchstart so that if you stay focused on the
            // element and keep changing it, it continues to update the prev val
            $(this)
                .on('mousedown.tl_change touchstart.tl_change', handleObj.selector, focusHandler)
                .on('change.tl_change', handleObj.selector, function (e) {
                // use an anonymous funciton here so we have access to the
                // original handle object to call the handler with our args
                var $el = $(this);
                // call our handle function, passing in the event, the previous and current vals
                // override the change event name to our name
                e.type = "tl_change";
                handleObj.handler.apply($el, [e, $el.data('tl-previous-val'), $el.val()]);
            });
        },
        remove: function (handleObj) {
            $(this)
                .off('mousedown.tl_change touchstart.tl_change', handleObj.selector, focusHandler)
                .off('change.tl_change', handleObj.selector)
                .removeData('tl-previous-val');
        }
    };

    // on focus lets set the previous value of the element to a data attr
    function focusHandler(e) {
        var $el = $(this);
        $el.data('tl-previous-val', $el.val());
    }
})(jQuery);

// usage
$('.some-element').on('tl_change', '.delegate-maybe', function (e, prev, current) {
    console.log(e);         // regular event object
    console.log(prev);      // previous value of input (before change)
    console.log(current);   // current value of input (after change)
    console.log(this);      // element
});

django admin - add custom form fields that are not part of the model

Either in your admin.py or in a separate forms.py you can add a ModelForm class and then declare your extra fields inside that as you normally would. I've also given an example of how you might use these values in form.save():

from django import forms
from yourapp.models import YourModel


class YourModelForm(forms.ModelForm):

    extra_field = forms.CharField()

    def save(self, commit=True):
        extra_field = self.cleaned_data.get('extra_field', None)
        # ...do something with extra_field here...
        return super(YourModelForm, self).save(commit=commit)

    class Meta:
        model = YourModel

To have the extra fields appearing in the admin just:

  1. edit your admin.py and set the form property to refer to the form you created above
  2. include your new fields in your fields or fieldsets declaration

Like this:

class YourModelAdmin(admin.ModelAdmin):

    form = YourModelForm

    fieldsets = (
        (None, {
            'fields': ('name', 'description', 'extra_field',),
        }),
    )

UPDATE: In django 1.8 you need to add fields = '__all__' to the metaclass of YourModelForm.

Get column index from label in a data frame

Use t function:

t(colnames(df))

     [,1]   [,2]   [,3]   [,4]   [,5]   [,6]  
[1,] "var1" "var2" "var3" "var4" "var5" "var6"

JavaScript Promises - reject vs. throw

TLDR: A function is hard to use when it sometimes returns a promise and sometimes throws an exception. When writing an async function, prefer to signal failure by returning a rejected promise

Your particular example obfuscates some important distinctions between them:

Because you are error handling inside a promise chain, thrown exceptions get automatically converted to rejected promises. This may explain why they seem to be interchangeable - they are not.

Consider the situation below:

checkCredentials = () => {
    let idToken = localStorage.getItem('some token');
    if ( idToken ) {
      return fetch(`https://someValidateEndpoint`, {
        headers: {
          Authorization: `Bearer ${idToken}`
        }
      })
    } else {
      throw new Error('No Token Found In Local Storage')
    }
  }

This would be an anti-pattern because you would then need to support both async and sync error cases. It might look something like:

try {
  function onFulfilled() { ... do the rest of your logic }
  function onRejected() { // handle async failure - like network timeout }
  checkCredentials(x).then(onFulfilled, onRejected);
} catch (e) {
  // Error('No Token Found In Local Storage')
  // handle synchronous failure
} 

Not good and here is exactly where Promise.reject ( available in the global scope ) comes to the rescue and effectively differentiates itself from throw. The refactor now becomes:

checkCredentials = () => {
  let idToken = localStorage.getItem('some_token');
  if (!idToken) {
    return Promise.reject('No Token Found In Local Storage')
  }
  return fetch(`https://someValidateEndpoint`, {
    headers: {
      Authorization: `Bearer ${idToken}`
    }
  })
}

This now lets you use just one catch() for network failures and the synchronous error check for lack of tokens:

checkCredentials()
      .catch((error) => if ( error == 'No Token' ) {
      // do no token modal
      } else if ( error === 400 ) {
      // do not authorized modal. etc.
      }

Difference between InvariantCulture and Ordinal string comparison

InvariantCulture

Uses a "standard" set of character orderings (a,b,c, ... etc.). This is in contrast to some specific locales, which may sort characters in different orders ('a-with-acute' may be before or after 'a', depending on the locale, and so on).

Ordinal

On the other hand, looks purely at the values of the raw byte(s) that represent the character.


There's a great sample at http://msdn.microsoft.com/en-us/library/e6883c06.aspx that shows the results of the various StringComparison values. All the way at the end, it shows (excerpted):

StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)

You can see that where InvariantCulture yields (U+0069, U+0049, U+00131), Ordinal yields (U+0049, U+0069, U+00131).

How can I check for existence of element in std::vector, in one line?

Try std::find

vector<int>::iterator it = std::find(v.begin(), v.end(), 123);

if(it==v.end()){

    std::cout<<"Element not found";
}

Format Date output in JSF

Use <f:convertDateTime>. You can nest this in any input and output component. Pattern rules are same as java.text.SimpleDateFormat.

<h:outputText value="#{someBean.dateField}" >
    <f:convertDateTime pattern="dd.MM.yyyy HH:mm" />
</h:outputText>

How to read XML using XPath in Java

Expanding on the excellent answer by @bluish and @Yishai, here is how you make the NodeLists and node attributes support iterators, i.e. the for(Node n: nodelist) interface.

Use it like:

NodeList nl = ...
for(Node n : XmlUtil.asList(nl))
{...}

and

Node n = ...
for(Node attr : XmlUtil.asList(n.getAttributes())
{...}

The code:

/**
 * Converts NodeList to an iterable construct.
 * From: https://stackoverflow.com/a/19591302/779521
 */
public final class XmlUtil {
    private XmlUtil() {}

    public static List<Node> asList(NodeList n) {
        return n.getLength() == 0 ? Collections.<Node>emptyList() : new NodeListWrapper(n);
    }

    static final class NodeListWrapper extends AbstractList<Node> implements RandomAccess {
        private final NodeList list;

        NodeListWrapper(NodeList l) {
            this.list = l;
        }

        public Node get(int index) {
            return this.list.item(index);
        }

        public int size() {
            return this.list.getLength();
        }
    }

    public static List<Node> asList(NamedNodeMap n) {
        return n.getLength() == 0 ? Collections.<Node>emptyList() : new NodeMapWrapper(n);
    }

    static final class NodeMapWrapper extends AbstractList<Node> implements RandomAccess {
        private final NamedNodeMap list;

        NodeMapWrapper(NamedNodeMap l) {
            this.list = l;
        }

        public Node get(int index) {
            return this.list.item(index);
        }

        public int size() {
            return this.list.getLength();
        }
    }
}

Using jQuery, Restricting File Size Before Uploading

I don't think it's possible unless you use a flash, activex or java uploader.

For security reasons ajax / javascript isn't allowed to access the file stream or file properties before or during upload.

Type.GetType("namespace.a.b.ClassName") returns null

If it's a nested Type, you might be forgetting to transform a . to a +

Regardless, typeof( T).FullName will tell you what you should be saying

EDIT: BTW the usings (as I'm sure you know) are only directives to the compiler at compile time and cannot thus have any impact on the API call's success. (If you had project or assembly references, that could potentially have had influence - hence the information isnt useless, it just takes some filtering...)

Is there a <meta> tag to turn off caching in all browsers?

This is a link to a great Case Study on the industry wide misunderstanding of controlling caches.

http://securityevaluators.com/knowledge/case_studies/caching/

In summary, according to this article, only Cache-Control: no-store is recognized by Chrome, Firefox, and IE. IE recognizes other controls, but Chrome and Firefox do not.

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

How to create empty folder in java?

You can create folder using the following Java code:

File dir = new File("nameoffolder");
dir.mkdir();

By executing above you will have folder 'nameoffolder' in current folder.

Select multiple value in DropDownList using ASP.NET and C#

Dropdown list wont allows multiple item select in dropdown.

If you need , you can use listbox control..

ASP.NET List Box

Chrome javascript debugger breakpoints don't do anything?

as I experienced with chrome we need to open browser console to make debugger run when loading page.

put this somewhere in javascript file you want to run

debugger

open browser console and reload page.

debugger will run like example image below

enter image description here

jQuery: Return data after ajax call success

you can add async option to false and return outside the ajax call.

function testAjax() {
    var result="";
    $.ajax({
      url:"getvalue.php",
      async: false,  
      success:function(data) {
         result = data; 
      }
   });
   return result;
}

Is there a way to add a gif to a Markdown file?

you can use ![ ](any link of image)

Also I would suggest to use https://stackedit.io/ for markdown formating and wring it is much easy than remembering all the markdown syntax

javascript code to check special characters

You could also do it this way.

specialRegex = /[^A-Z a-z0-9]/ specialRegex.test('test!') // evaluates to true Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character

MATLAB - multiple return values from a function?

Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed

What does @@variable mean in Ruby?

The answers are partially correct because @@ is actually a class variable which is per class hierarchy meaning it is shared by a class, its instances and its descendant classes and their instances.

class Person
  @@people = []

  def initialize
    @@people << self
  end

  def self.people
    @@people
  end
end

class Student < Person
end

class Graduate < Student
end

Person.new
Student.new

puts Graduate.people

This will output

#<Person:0x007fa70fa24870>
#<Student:0x007fa70fa24848>

So there is only one same @@variable for Person, Student and Graduate classes and all class and instance methods of these classes refer to the same variable.

There is another way of defining a class variable which is defined on a class object (Remember that each class is actually an instance of something which is actually the Class class but it is another story). You use @ notation instead of @@ but you can't access these variables from instance methods. You need to have class method wrappers.

class Person

  def initialize
    self.class.add_person self
  end

  def self.people
    @people
  end

  def self.add_person instance
    @people ||= []
    @people << instance
  end
end

class Student < Person
end

class Graduate < Student
end

Person.new
Person.new
Student.new
Student.new
Graduate.new
Graduate.new

puts Student.people.join(",")
puts Person.people.join(",")
puts Graduate.people.join(",")

Here, @people is single per class instead of class hierarchy because it is actually a variable stored on each class instance. This is the output:

#<Student:0x007f8e9d2267e8>,#<Student:0x007f8e9d21ff38>
#<Person:0x007f8e9d226158>,#<Person:0x007f8e9d226608>
#<Graduate:0x007f8e9d21fec0>,#<Graduate:0x007f8e9d21fdf8> 

One important difference is that, you cannot access these class variables (or class instance variables you can say) directly from instance methods because @people in an instance method would refer to an instance variable of that specific instance of the Person or Student or Graduate classes.

So while other answers correctly state that @myvariable (with single @ notation) is always an instance variable, it doesn't necessarily mean that it is not a single shared variable for all instances of that class.

How to Refresh a Component in Angular

Use the this.ngOnInit(); to reload the same component instead reloading the entire page!!

DeleteEmployee(id:number)
  {
    this.employeeService.deleteEmployee(id)
    .subscribe( 
      (data) =>{
        console.log(data);

        this.ngOnInit();

      }),
      err => {
        console.log("Error");
      }   
  }

How to fix the error "Windows SDK version 8.1" was not found?

Grep the folder tree's *.vcxproj files. Replace <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion> with <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion> or whatever SDK version you get when you update one of the projects.

How do I find all files containing specific text on Linux?

Find any files whose name is ".kube/config", and content include eks_use1d:

locate ".kube/config" | xargs -i sh -c 'echo \\n{};cat {} | grep eks_use1d'

g++ undefined reference to typeinfo

I just spent a few hours on this error, and while the other answers here helped me understand what was going on, they did not fix my particular problem.

I am working on a project that compiles using both clang++ and g++. I was having no linking issues using clang++, but was getting the undefined reference to 'typeinfo for error with g++.

The important point: Linking order MATTERS with g++. If you list the libraries you want to link in an order which is incorrect you can get the typeinfo error.

See this SO question for more details on linking order with gcc/g++.

Press any key to continue

Check out the ReadKey() method on the System.Console .NET class. I think that will do what you're looking for.

http://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx

Example:

Write-Host -Object ('The key that was pressed was: {0}' -f [System.Console]::ReadKey().Key.ToString());

function to return a string in java

In Java, a String is a reference to heap-allocated storage. Returning "ans" only returns the reference so there is no need for stack-allocated storage. In fact, there is no way in Java to allocate objects in stack storage.

I would change to this, though. You don't need "ans" at all.

return String.format("%d:%d", mins, secs);

Why do python lists have pop() but not push()

Push and Pop make sense in terms of the metaphor of a stack of plates or trays in a cafeteria or buffet, specifically the ones in type of holder that has a spring underneath so the top plate is (more or less... in theory) in the same place no matter how many plates are under it.

If you remove a tray, the weight on the spring is a little less and the stack "pops" up a little, if you put the plate back, it "push"es the stack down. So if you think about the list as a stack and the last element as being on top, then you shouldn't have much confusion.

CSS3 Transition not working

HTML:

<div class="foo">
    /* whatever is required */
</div>

CSS:

.foo {
    top: 0;
    transition: top ease 0.5s;
}

.foo:hover{
    top: -10px;
}

This is just a basic transition to ease the div tag up by 10px when it is hovered on. The transition property's values can be edited along with the class.hover properties to determine how the transition works.

Read only file system on Android

mount -o rw,remount /dev/stl12 /system

works for me

Copy output of a JavaScript variable to the clipboard

At the time of writing, setting display:none on the element didn't work for me. Setting the element's width and height to 0 did not work either. So the element has to be at least 1px in width for this to work.

The following example worked in Chrome and Firefox:

    const str = 'Copy me';
    const el = document.createElement("input");
    // Does not work:
    // dummy.style.display = "none";
    el.style.height = '0px';
    // Does not work:
    // el.style.width = '0px';
    el.style.width = '1px';
    document.body.appendChild(el);
    el.value = str;
    el.select();
    document.execCommand("copy");
    document.body.removeChild(el);

I'd like to add that I can see why the browsers are trying to prevent this hackish approach. It's better to openly show the content you are going copy into the user's browser. But sometimes there are design requirements, we can't change.

SVN Commit specific files

You basically put the files you want to commit on the command line

svn ci file1 file2 dir1/file3

SwiftUI - How do I change the background color of a View?

Would this solution work?:

add following line to SceneDelegate: window.rootViewController?.view.backgroundColor = .black

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        if let windowScene = scene as? UIWindowScene {

                window.rootViewController?.view.backgroundColor = .black
}

Tree implementation in Java (root, parents and children)

Accepted answer throws a java.lang.StackOverflowError when calling the setParent or addChild methods.

Here's a slightly simpler implementation without those bugs:

public class MyTreeNode<T>{
    private T data = null;
    private List<MyTreeNode> children = new ArrayList<>();
    private MyTreeNode parent = null;

    public MyTreeNode(T data) {
        this.data = data;
    }

    public void addChild(MyTreeNode child) {
        child.setParent(this);
        this.children.add(child);
    }

    public void addChild(T data) {
        MyTreeNode<T> newChild = new MyTreeNode<>(data);
        this.addChild(newChild);
    }

    public void addChildren(List<MyTreeNode> children) {
        for(MyTreeNode t : children) {
            t.setParent(this);
        }
        this.children.addAll(children);
    }

    public List<MyTreeNode> getChildren() {
        return children;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    private void setParent(MyTreeNode parent) {
        this.parent = parent;
    }

    public MyTreeNode getParent() {
        return parent;
    }
}

Some examples:

MyTreeNode<String> root = new MyTreeNode<>("Root");

MyTreeNode<String> child1 = new MyTreeNode<>("Child1");
child1.addChild("Grandchild1");
child1.addChild("Grandchild2");

MyTreeNode<String> child2 = new MyTreeNode<>("Child2");
child2.addChild("Grandchild3");

root.addChild(child1);
root.addChild(child2);
root.addChild("Child3");

root.addChildren(Arrays.asList(
        new MyTreeNode<>("Child4"),
        new MyTreeNode<>("Child5"),
        new MyTreeNode<>("Child6")
));

for(MyTreeNode node : root.getChildren()) {
    System.out.println(node.getData());
}

Remove white space below image

.youtube-thumb img {display:block;} or .youtube-thumb img {float:left;}

Should I use "camel case" or underscores in python?

Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style

Check out its already been answered, click here

How to Find App Pool Recycles in Event Log

As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:

Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}

From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.

This along with @BlackHawkDesign comment should help you find what you need.

I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00

Creating an XmlNode/XmlElement in C# without an XmlDocument?

From W3C Document Object Model (Core) Level 1 specification (bold is mine):

Most of the APIs defined by this specification are interfaces rather than classes. That means that an actual implementation need only expose methods with the defined names and specified operation, not actually implement classes that correspond directly to the interfaces. This allows the DOM APIs to be implemented as a thin veneer on top of legacy applications with their own data structures, or on top of newer applications with different class hierarchies. This also means that ordinary constructors (in the Java or C++ sense) cannot be used to create DOM objects, since the underlying objects to be constructed may have little relationship to the DOM interfaces. The conventional solution to this in object-oriented design is to define factory methods that create instances of objects that implement the various interfaces. In the DOM Level 1, objects implementing some interface "X" are created by a "createX()" method on the Document interface; this is because all DOM objects live in the context of a specific Document.

AFAIK, you can not create any XmlNode (XmlElement, XmlAttribute, XmlCDataSection, etc) except XmlDocument from a constructor.

Moreover, note that you can not use XmlDocument.AppendChild() for nodes that are not created via the factory methods of the same document. In case you have a node from another document, you must use XmlDocument.ImportNode().

What does href expression <a href="javascript:;"></a> do?

<a href="javascript:void(0);"></a>

javascript: tells the browser going to write javascript code

How to stop a goroutine

You can't kill a goroutine from outside. You can signal a goroutine to stop using a channel, but there's no handle on goroutines to do any sort of meta management. Goroutines are intended to cooperatively solve problems, so killing one that is misbehaving would almost never be an adequate response. If you want isolation for robustness, you probably want a process.

How to convert An NSInteger to an int?

Commonly used in UIsegmentedControl, "error" appear when compiling in 64bits instead of 32bits, easy way for not pass it to a new variable is to use this tips, add (int):

[_monChiffre setUnite:(int)[_valUnites selectedSegmentIndex]];

instead of :

[_monChiffre setUnite:[_valUnites selectedSegmentIndex]];

What does the "More Columns than Column Names" error mean?

It uses commas as separators. So you can either set sep="," or just use read.csv:

x <- read.csv(file="http://www.irs.gov/file_source/pub/irs-soi/countyinflow1011.csv")
dim(x)
## [1] 113593      9

The error is caused by spaces in some of the values, and unmatched quotes. There are no spaces in the header, so read.table thinks that there is one column. Then it thinks it sees multiple columns in some of the rows. For example, the first two lines (header and first row):

State_Code_Dest,County_Code_Dest,State_Code_Origin,County_Code_Origin,State_Abbrv,County_Name,Return_Num,Exmpt_Num,Aggr_AGI
00,000,96,000,US,Total Mig - US & For,6973489,12948316,303495582

And unmatched quotes, for example on line 1336 (row 1335) which will confuse read.table with the default quote argument (but not read.csv):

01,089,24,033,MD,Prince George's County,13,30,1040

How to restore PostgreSQL dump file into Postgres databases?

You didn't mention how your backup was made, so the generic answer is: Usually with the psql tool.

Depending on what pg_dump was instructed to dump, the SQL file can have different sets of SQL commands. For example, if you instruct pg_dump to dump a database using --clean and --schema-only, you can't expect to be able to restore the database from that dump as there will be no SQL commands for COPYing (or INSERTing if --inserts is used ) the actual data in the tables. A dump like that will contain only DDL SQL commands, and will be able to recreate the schema but not the actual data.

A typical SQL dump is restored with psql:

psql (connection options here) database  < yourbackup.sql

or alternatively from a psql session,

psql (connection options here) database
database=# \i /path/to/yourbackup.sql

In the case of backups made with pg_dump -Fc ("custom format"), which is not a plain SQL file but a compressed file, you need to use the pg_restore tool.

If you're working on a unix-like, try this:

man psql
man pg_dump
man pg_restore

otherwise, take a look at the html docs. Good luck!

Day Name from Date in JS

I'm not a fan of over-complicated solutions if anyone else comes up with something better, please let us know :)

any-name.js

var today = new Date().toLocaleDateString(undefined, {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
    weekday: 'long'
});
any-name.html
<script>
    document.write(today);
</script>

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

How to convert a list into data table

Just add this function and call it, it will convert List to DataTable.

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}

How to run an application as "run as administrator" from the command prompt?

It looks like psexec -h is the way to do this:

 -h         If the target system is Windows Vista or higher, has the process
            run with the account's elevated token, if available.

Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.

But it works on my machine.

Scala Doubles, and Precision

You may use implicit classes:

import scala.math._

object ExtNumber extends App {
  implicit class ExtendedDouble(n: Double) {
    def rounded(x: Int) = {
      val w = pow(10, x)
      (n * w).toLong.toDouble / w
    }
  }

  // usage
  val a = 1.23456789
  println(a.rounded(2))
}

Move UIView up when the keyboard appears in iOS

For all the issue related to KeyBoard just use IQKeyBoardManager it's helpful. https://github.com/hackiftekhar/IQKeyboardManager.

SQL sum with condition

Try this instead:

SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)

Explanation

Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:

The CASE expression has two formats:

  • The simple CASE expression compares an expression to a set of simple expressions to determine the result.
  • The searched CASE expression evaluates a set of Boolean expressions to determine the result.

You want the searched CASE expression syntax:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.

How to bind inverse boolean properties in WPF?

This one also works for nullable bools.

 [ValueConversion(typeof(bool?), typeof(bool))]
public class InverseBooleanConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (targetType != typeof(bool?))
        {
            throw new InvalidOperationException("The target must be a nullable boolean");
        }
        bool? b = (bool?)value;
        return b.HasValue && !b.Value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return !(value as bool?);
    }

    #endregion
}

How to center align the ActionBar title in Android?

This code will not hide back button, Same time will align the title in centre.

call this method in oncreate

centerActionBarTitle();



getSupportActionBar().setDisplayHomeAsUpEnabled(true);
myActionBar.setIcon(new ColorDrawable(Color.TRANSPARENT));

private void centerActionBarTitle() {
    int titleId = 0;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        titleId = getResources().getIdentifier("action_bar_title", "id", "android");
    } else {
        // This is the id is from your app's generated R class when 
        // ActionBarActivity is used for SupportActionBar
        titleId = R.id.action_bar_title;
    }

    // Final check for non-zero invalid id
    if (titleId > 0) {
        TextView titleTextView = (TextView) findViewById(titleId);
        DisplayMetrics metrics = getResources().getDisplayMetrics();

        // Fetch layout parameters of titleTextView 
        // (LinearLayout.LayoutParams : Info from HierarchyViewer)
        LinearLayout.LayoutParams txvPars = (LayoutParams) titleTextView.getLayoutParams();
        txvPars.gravity = Gravity.CENTER_HORIZONTAL;
        txvPars.width = metrics.widthPixels;
        titleTextView.setLayoutParams(txvPars);
        titleTextView.setGravity(Gravity.CENTER);
    }
}

How to avoid soft keyboard pushing up my layout?

Solved it by setting the naughty EditText:

etSearch = (EditText) view.findViewById(R.id.etSearch);

etSearch.setInputType(InputType.TYPE_NULL);

etSearch.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        etSearch.setInputType(InputType.TYPE_CLASS_TEXT);
        return false;
    }
});

How to change RGB color to HSV?

There's a C implementation here:

http://www.cs.rit.edu/~ncs/color/t_convert.html

Should be very straightforward to convert to C#, as almost no functions are called - just calculations.

found via Google

Laravel orderBy on a relationship

Try this solution.

$mainModelData = mainModel::where('column', $value)
    ->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
    ->orderBy('relation_table.title', 'ASC')
    ->with(['relationModal' => function ($q) {
        $q->where('column', 'value');
    }])->get();

Example:

$user = User::where('city', 'kullu')
    ->join('salaries', 'users.id', '=', 'salaries.user_id')
    ->orderBy('salaries.amount', 'ASC')
    ->with(['salaries' => function ($q) {
        $q->where('amount', '>', '500000');
    }])->get();

You can change the column name in join() as per your database structure.

Can you Run Xcode in Linux?

Nobody suggested Vagrant yet, so here it is, Vagrant box for OSX

vagrant init https://vagrant-osx.nyc3.digitaloceanspaces.com/osx-sierra-0.3.1.box
vagrant up

and you have a MACOS virtual machine. But according to Apple's EULA, you still need to run it on MacOS hardware :D But anywhere, here's one to all of you geeks who wiped MacOS and installed Ubuntu :D

Unfortunately, you can't run the editors from inside using SSH X-forwarding option.

How to pass parameter to click event in Jquery

 $('elements-to-match').click(function(){
        alert("The id is "+ this.id );
    });

no need to wrap it in a jquery object

How to click or tap on a TextView text

You can use TextWatcher for TextView, is more flexible than ClickLinstener (not best or worse, only more one way).

holder.bt_foo_ex.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // code during!

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // code before!

        }

        @Override
        public void afterTextChanged(Editable s) {
            // code after!

        }
    });

github: server certificate verification failed

Try to connect to repositroy with url: http://github.com/<user>/<project>.git (http except https)

In your case you should clone like this:

git clone http://github.com/<user>/<project>.git

Disable clipboard prompt in Excel VBA on workbook close

proposed solution edit works if you replace the row

Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)

with

Set rDst = ThisWorkbook.Sheets("SomeSheet").Range("YourRange").Resize(rSrc.Rows.Count, rSrc.Columns.Count)

Docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

I have Jenkins running in Docker and connected Jenkins is using Docker socket from host machine Ubuntu 16.04 via volume to /var/run/docker.sock.

For me solution was:

1) Inside Docker container of Jenkins (docker exec -it jenkins bash on host machine)

usermod -a -G docker jenkins
chmod 664 /var/run/docker.sock
service jenkins restart (or systemctl restart jenkins.service)
su jenkins

2) On host machine:

sudo service docker restart

664 means - read and write(but not execute) for owner and users from group.

Remove values from select list based on condition

Give an id for the select object like this:

<select id="mySelect" name="val" size="1" >
    <option value="A">Apple</option>
    <option value="C">Cars</option>
    <option value="H">Honda</option>
    <option value="F">Fiat</option>
    <option value="I">Indigo</option>                    
</select> 

You can do it in pure JavaScript:

var selectobject = document.getElementById("mySelect");
for (var i=0; i<selectobject.length; i++) {
    if (selectobject.options[i].value == 'A')
        selectobject.remove(i);
}

But - as the other answers suggest - it's a lot easier to use jQuery or some other JS library.

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

You must specify which type the response is

  this.productService.getProducts().subscribe(res => {
          this.productsArray = res;
        });

Try this

  this.productService.getProducts().subscribe((res: Product[]) => {
          this.productsArray = res;
        });

Check if something is (not) in a list in Python

How do I check if something is (not) in a list in Python?

The cheapest and most readable solution is using the in operator (or in your specific case, not in). As mentioned in the documentation,

The operators in and not in test for membership. x in s evaluates to True if x is a member of s, and False otherwise. x not in s returns the negation of x in s.

Additionally,

The operator not in is defined to have the inverse true value of in.

y not in x is logically the same as not y in x.

Here are a few examples:

'a' in [1, 2, 3]
# False

'c' in ['a', 'b', 'c']
# True

'a' not in [1, 2, 3]
# True

'c' not in ['a', 'b', 'c']
# False

This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):

(1, 2) in [(3, 4), (1, 2)]
#  True

If the object on the RHS defines a __contains__() method, in will internally call it, as noted in the last paragraph of the Comparisons section of the docs.

... in and not in, are supported by types that are iterable or implement the __contains__() method. For example, you could (but shouldn't) do this:

[3, 2, 1].__contains__(1)
# True

in short-circuits, so if your element is at the start of the list, in evaluates faster:

lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst  # Expected to take longer time.

68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

If you want to do more than just check whether an item is in a list, there are options:

  • list.index can be used to retrieve the index of an item. If that element does not exist, a ValueError is raised.
  • list.count can be used if you want to count the occurrences.

The XY Problem: Have you considered sets?

Ask yourself these questions:

  • do you need to check whether an item is in a list more than once?
  • Is this check done inside a loop, or a function called repeatedly?
  • Are the items you're storing on your list hashable? IOW, can you call hash on them?

If you answered "yes" to these questions, you should be using a set instead. An in membership test on lists is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.

set objects, on the other hand, hash their values for constant time membership check. The check is also done using in:

1 in {1, 2, 3} 
# True

'a' not in {'a', 'b', 'c'}
# False

(1, 2) in {('a', 'c'), (1, 2)}
# True

If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:

l = list(range(100001))
s = set(l)

%timeit 100000 in l
%timeit 100000 in s

2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__.

jQuery SVG vs. Raphael

I've recently used both Raphael and jQuery SVG - and here are my thoughts:

Raphael

Pros: a good starter library, easy to do a LOT of things with SVG quickly. Well written and documented. Lots of examples and Demos. Very extensible architecture. Great with animation.

Cons: is a layer over the actual SVG markup, makes it difficult to do more complex things with SVG - such as grouping (it supports Sets, but not groups). Doesn't do great w/ editing of already existing elements.

jQuery SVG

Pros: a jquery plugin, if you're already using jQuery. Well written and documented. Lots of examples and demos. Supports most SVG elements, allows native access to elements easily

Cons: architecture not as extensible as Raphael. Some things could be better documented (like configure of SVG element). Doesn't do great w/ editing of already existing elements. Relies on SVG semantics for animation - which is not that great.

SnapSVG as a pure SVG version of Raphael

SnapSVG is the successor of Raphael. It is supported only in the SVG enabled browsers and supports almost all the features of SVG.

Conclusion

If you're doing something quick and easy, Raphael is an easy choice. If you're going to do something more complex, I chose to use jQuery SVG because I can manipulate the actual markup significantly easier than with Raphael. And if you want a non-jQuery solution then SnapSVG is a good option.

Set the selected index of a Dropdown using jQuery

Just found this, it works for me and I personally find it easier to read.

This will set the actual index just like gnarf's answer number 3 option.

// sets selected index of a select box the actual index of 0 
$("select#elem").attr('selectedIndex', 0);

This didn't used to work but does now... see bug: http://dev.jquery.com/ticket/1474

Addendum

As recommended in the comments use :

$("select#elem").prop('selectedIndex', 0);

how to install gcc on windows 7 machine?

Following up on Mat's answer (use Cygwin), here are some detailed instructions for : installing gcc on Windows The packages you want are gcc, gdb and make. Cygwin installer lets you install additional packages if you need them.

Swapping two variable value without using third variable

Stupid questions deserve appropriate answers:

void sw2ap(int& a, int& b) {
  register int temp = a; // !
  a = b;
  b = temp;
}

The only good use of the register keyword.

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

I had the same issue and I found this nice poweshell script to update all of your app pools at the same time: https://gallery.technet.microsoft.com/scriptcenter/How-to-set-the-IIS-9c295a20

Make sure to set you $IISAppPoolDotNetVersion = "v4.0" variable at the top.

Is there a limit on an Excel worksheet's name length?

Renaming a worksheet manually in Excel, you hit a limit of 31 chars, so I'd suggest that that's a hard limit.

Get the element triggering an onclick event in jquery?

Try this

<input onclick="confirmSubmit(event);" type="button" value="Send" />

Along with this

function confirmSubmit(event){
            var domElement =$(event.target);
            console.log(domElement.attr('type'));
        }

I tried it in firefox, it prints the 'type' attribute of dom Element clicked. I guess you can then get the form via the parents() methods using this object.

PHP - Getting the index of a element from a array

PHP arrays are both integer-indexed and string-indexed. You can even mix them:

array('red', 'green', 'white', 'color3'=>'blue', 3=>'yellow');

What do you want the index to be for the value 'blue'? Is it 3? But that's actually the index of the value 'yellow', so that would be an ambiguity.

Another solution for you is to coerce the array to an integer-indexed list of values.

foreach (array_values($array) as $i => $value) {
  echo "$i: $value\n";
}

Output:

0: red
1: green
2: white
3: blue
4: yellow

SQL Query for Selecting Multiple Records

Try the following code:

SELECT *
FROM users
WHERE firstname IN ('joe','jane');

How to hide Bootstrap previous modal when you opening new one?

You hide Bootstrap modals with:

$('#modal').modal('hide');

Saying $().hide() makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.

Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

Example:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

Before

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

After

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also https://github.com/Microsoft/TypeScript/issues/3755

Find duplicate lines in a file and count how many time each line was duplicated?

This will print duplicate lines only, with counts:

sort FILE | uniq -cd

or, with GNU long options (on Linux):

sort FILE | uniq --count --repeated

on BSD and OSX you have to use grep to filter out unique lines:

sort FILE | uniq -c | grep -v '^ *1 '

For the given example, the result would be:

  3 123
  2 234

If you want to print counts for all lines including those that appear only once:

sort FILE | uniq -c

or, with GNU long options (on Linux):

sort FILE | uniq --count

For the given input, the output is:

  3 123
  2 234
  1 345

In order to sort the output with the most frequent lines on top, you can do the following (to get all results):

sort FILE | uniq -c | sort -nr

or, to get only duplicate lines, most frequent first:

sort FILE | uniq -cd | sort -nr

on OSX and BSD the final one becomes:

sort FILE | uniq -c | grep -v '^ *1 ' | sort -nr

What is the maximum size of a web browser's cookie's key?

The 4K limit you read about is for the entire cookie, including name, value, expiry date etc. If you want to support most browsers, I suggest keeping the name under 4000 bytes, and the overall cookie size under 4093 bytes.

One thing to be careful of: if the name is too big you cannot delete the cookie (at least in JavaScript). A cookie is deleted by updating it and setting it to expire. If the name is too big, say 4090 bytes, I found that I could not set an expiry date. I only looked into this out of interest, not that I plan to have a name that big.

To read more about it, here are the "Browser Cookie Limits" for common browsers.


While on the subject, if you want to support most browsers, then do not exceed 50 cookies per domain, and 4093 bytes per domain. That is, the size of all cookies should not exceed 4093 bytes.

This means you can have 1 cookie of 4093 bytes, or 2 cookies of 2045 bytes, etc.


I used to say 4095 bytes due to IE7, however now Mobile Safari comes in with 4096 bytes with a 3 byte overhead per cookie, so 4093 bytes max.

Primary key or Unique index?

There is no such thing as a primary key in relational data theory, so your question has to be answered on the practical level.

Unique indexes are not part of the SQL standard. The particular implementation of a DBMS will determine what are the consequences of declaring a unique index.

In Oracle, declaring a primary key will result in a unique index being created on your behalf, so the question is almost moot. I can't tell you about other DBMS products.

I favor declaring a primary key. This has the effect of forbidding NULLs in the key column(s) as well as forbidding duplicates. I also favor declaring REFERENCES constraints to enforce entity integrity. In many cases, declaring an index on the coulmn(s) of a foreign key will speed up joins. This kind of index should in general not be unique.

How do I specify different Layouts in the ASP.NET MVC 3 razor ViewStart file?

One more method is to Define the Layout inside the View:

   @{
    Layout = "~/Views/Shared/_MyAdminLayout.cshtml";
    }

More Ways to do, can be found here, hope this helps someone.

What tool to use to draw file tree diagram

The advice to use Graphviz is good: you can generate the dot file and it will do the hard work of measuring strings, doing the layout, etc. Plus it can output the graphs in lot of formats, including vector ones.

I found a Perl program doing precisely that, in a mailing list, but I just can't find it back! I copied the sample dot file and studied it, since I don't know much of this declarative syntax and I wanted to learn a bit more.

Problem: with latest Graphviz, I have errors (or rather, warnings, as the final diagram is generated), both in the original graph and the one I wrote (by hand). Some searches shown this error was found in old versions and disappeared in more recent versions. Looks like it is back.

I still give the file, maybe it can be a starting point for somebody, or maybe it is enough for your needs (of course, you still have to generate it).

digraph tree
{
  rankdir=LR;

  DirTree [label="Directory Tree" shape=box]

  a_Foo_txt [shape=point]
  f_Foo_txt [label="Foo.txt", shape=none]
  a_Foo_txt -> f_Foo_txt

  a_Foo_Bar_html [shape=point]
  f_Foo_Bar_html [label="Foo Bar.html", shape=none]
  a_Foo_Bar_html -> f_Foo_Bar_html

  a_Bar_png [shape=point]
  f_Bar_png [label="Bar.png", shape=none]
  a_Bar_png -> f_Bar_png

  a_Some_Dir [shape=point]
  d_Some_Dir [label="Some Dir", shape=ellipse]
  a_Some_Dir -> d_Some_Dir

  a_VBE_C_reg [shape=point]
  f_VBE_C_reg [label="VBE_C.reg", shape=none]
  a_VBE_C_reg -> f_VBE_C_reg

  a_P_Folder [shape=point]
  d_P_Folder [label="P Folder", shape=ellipse]
  a_P_Folder -> d_P_Folder

  a_Processing_20081117_7z [shape=point]
  f_Processing_20081117_7z [label="Processing-20081117.7z", shape=none]
  a_Processing_20081117_7z -> f_Processing_20081117_7z

  a_UsefulBits_lua [shape=point]
  f_UsefulBits_lua [label="UsefulBits.lua", shape=none]
  a_UsefulBits_lua -> f_UsefulBits_lua

  a_Graphviz [shape=point]
  d_Graphviz [label="Graphviz", shape=ellipse]
  a_Graphviz -> d_Graphviz

  a_Tree_dot [shape=point]
  f_Tree_dot [label="Tree.dot", shape=none]
  a_Tree_dot -> f_Tree_dot

  {
    rank=same;
    DirTree -> a_Foo_txt -> a_Foo_Bar_html -> a_Bar_png -> a_Some_Dir -> a_Graphviz [arrowhead=none]
  }
  {
    rank=same;
    d_Some_Dir -> a_VBE_C_reg -> a_P_Folder -> a_UsefulBits_lua [arrowhead=none]
  }
  {
    rank=same;
    d_P_Folder -> a_Processing_20081117_7z [arrowhead=none]
  }
  {
    rank=same;
    d_Graphviz -> a_Tree_dot [arrowhead=none]
  }
}

> dot -Tpng Tree.dot -o Tree.png
Error: lost DirTree a_Foo_txt edge
Error: lost a_Foo_txt a_Foo_Bar_html edge
Error: lost a_Foo_Bar_html a_Bar_png edge
Error: lost a_Bar_png a_Some_Dir edge
Error: lost a_Some_Dir a_Graphviz edge
Error: lost d_Some_Dir a_VBE_C_reg edge
Error: lost a_VBE_C_reg a_P_Folder edge
Error: lost a_P_Folder a_UsefulBits_lua edge
Error: lost d_P_Folder a_Processing_20081117_7z edge
Error: lost d_Graphviz a_Tree_dot edge

I will try another direction, using Cairo, which is also able to export a number of formats. It is more work (computing positions/offsets) but the structure is simple, shouldn't be too hard.

Can I position an element fixed relative to parent?

The CSS specification requires that position:fixed be anchored to the viewport, not the containing positioned element.

If you must specify your coordinates relative to a parent, you will have to use JavaScript to find the parent's position relative to the viewport first, then set the child (fixed) element's position accordingly.

ALTERNATIVE: Some browsers have sticky CSS support which limits an element to be positioned within both its container and the viewport. Per the commit message:

sticky ... constrains an element to be positioned inside the intersection of its container box, and the viewport.

A stickily positioned element behaves like position:relative (space is reserved for it in-flow), but with an offset that is determined by the sticky position. Changed isInFlowPositioned() to cover relative and sticky.

Depending on your design goals, this behavior may be helpful in some cases. It is currently a working draft, and has decent support, aside from table elements. position: sticky still needs a -webkit prefix in Safari.

See caniuse for up-to-date stats on browser support.

Having trouble setting working directory

Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!

ServletException, HttpServletResponse and HttpServletRequest cannot be resolved to a type

You can do the folllwoing: import the jar file inside you class:

import javax.servlet.http.HttpServletResponse

add the Apache Tomcat library as follow:

Project > Properties > Java Build Path > Libraries > Add library from library tab > Choose server runtime > Next > choose Apache Tomcat v 6.0 > Finish > Ok

Also First of all, make sure that Servlet jar is included in your class path in eclipse as PermGenError said.

I think this will solve your error

How to copy a collection from one database to another in MongoDB

In my case, I had to use a subset of attributes from the old collection in my new collection. So I ended up choosing those attributes while calling insert on the new collection.

db.<sourceColl>.find().forEach(function(doc) { 
    db.<newColl>.insert({
        "new_field1":doc.field1,
        "new_field2":doc.field2,
        ....
    })
});`

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

I always put the code below in the first two lines of the python files:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

How to write JUnit test with Spring Autowire?

A JUnit4 test with Autowired and bean mocking (Mockito):

// JUnit starts spring context
@RunWith(SpringRunner.class)
// spring load context configuration from AppConfig class
@ContextConfiguration(classes = AppConfig.class)
// overriding some properties with test values if you need
@TestPropertySource(properties = {
        "spring.someConfigValue=your-test-value",
})
public class PersonServiceTest {

    @MockBean
    private PersonRepository repository;

    @Autowired
    private PersonService personService; // uses PersonRepository    

    @Test
    public void testSomething() {
        // using Mockito
        when(repository.findByName(any())).thenReturn(Collection.emptyList());
        Person person = new Person();
        person.setName(null);

        // when
        boolean found = personService.checkSomething(person);

        // then
        assertTrue(found, "Something is wrong");
    }
}

In Javascript, how to conditionally add a member to an object?

Define a var by let and just assign new property

let msg = {
    to: "[email protected]",
    from: "[email protected]",
    subject: "Contact form",    
};

if (file_uploaded_in_form) { // the condition goes here
    msg.attachments = [ // here 'attachments' is the new property added to msg Javascript object
      {
        content: "attachment",
        filename: "filename",
        type: "mime_type",
        disposition: "attachment",
      },
    ];
}

Now the msg become

{
    to: "[email protected]",
    from: "[email protected]",
    subject: "Contact form",
    attachments: [
      {
        content: "attachment",
        filename: "filename",
        type: "mime_type",
        disposition: "attachment",
      },
    ]
}

In my opinion this is very simple and easy solution.

CMD what does /im (taskkill)?

If you type the executable name and a /? switch at the command line, there is typically help information available. Doing so with taskkill /? provides the following, for instance:

TASKKILL [/S system [/U username [/P [password]]]]
         { [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]

Description:
    This tool is used to terminate tasks by process id (PID) or image name.

Parameter List:
    /S    system           Specifies the remote system to connect to.

    /U    [domain\]user    Specifies the user context under which the
                           command should execute.

    /P    [password]       Specifies the password for the given user
                           context. Prompts for input if omitted.

    /FI   filter           Applies a filter to select a set of tasks.
                           Allows "*" to be used. ex. imagename eq acme*

    /PID  processid        Specifies the PID of the process to be terminated.
                           Use TaskList to get the PID.

    /IM   imagename        Specifies the image name of the process
                           to be terminated. Wildcard '*' can be used
                           to specify all tasks or image names.

    /T                     Terminates the specified process and any
                           child processes which were started by it.

    /F                     Specifies to forcefully terminate the process(es).

    /?                     Displays this help message.

Filters:
    Filter Name   Valid Operators           Valid Value(s)
    -----------   ---------------           -------------------------
    STATUS        eq, ne                    RUNNING |
                                            NOT RESPONDING | UNKNOWN
    IMAGENAME     eq, ne                    Image name
    PID           eq, ne, gt, lt, ge, le    PID value
    SESSION       eq, ne, gt, lt, ge, le    Session number.
    CPUTIME       eq, ne, gt, lt, ge, le    CPU time in the format
                                            of hh:mm:ss.
                                            hh - hours,
                                            mm - minutes, ss - seconds
    MEMUSAGE      eq, ne, gt, lt, ge, le    Memory usage in KB
    USERNAME      eq, ne                    User name in [domain\]user
                                            format
    MODULES       eq, ne                    DLL name
    SERVICES      eq, ne                    Service name
    WINDOWTITLE   eq, ne                    Window title

    NOTE
    ----
    1) Wildcard '*' for /IM switch is accepted only when a filter is applied.
    2) Termination of remote processes will always be done forcefully (/F).
    3) "WINDOWTITLE" and "STATUS" filters are not considered when a remote
       machine is specified.

Examples:
    TASKKILL /IM notepad.exe
    TASKKILL /PID 1230 /PID 1241 /PID 1253 /T
    TASKKILL /F /IM cmd.exe /T 
    TASKKILL /F /FI "PID ge 1000" /FI "WINDOWTITLE ne untitle*"
    TASKKILL /F /FI "USERNAME eq NT AUTHORITY\SYSTEM" /IM notepad.exe
    TASKKILL /S system /U domain\username /FI "USERNAME ne NT*" /IM *
    TASKKILL /S system /U username /P password /FI "IMAGENAME eq note*"

You can also find this information, as well as documentation for most of the other command-line utilities, in the Microsoft TechNet Command-Line Reference

How to use an environment variable inside a quoted string in Bash

Just a quick note/summary for any who came here via Google looking for the answer to the general question asked in the title (as I was). Any of the following should work for getting access to shell variables inside quotes:

echo "$VARIABLE"
echo "${VARIABLE}"

Use of single quotes is the main issue. According to the Bash Reference Manual:

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. [...] Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed. The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

In the specific case asked in the question, $COLUMNS is a special variable which has nonstandard properties (see lhunath's answer above).

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

Use TextAreaFor

@Html.TextAreaFor(model => model.Description, new { @class = "whatever-class", @cols = 80, @rows = 10 })

or use style for multi-line class.

You could also write EditorTemplate for this.

How to pass objects to functions in C++?

There are several cases to consider.

Parameter modified ("out" and "in/out" parameters)

void modifies(T &param);
// vs
void modifies(T *param);

This case is mostly about style: do you want the code to look like call(obj) or call(&obj)? However, there are two points where the difference matters: the optional case, below, and you want to use a reference when overloading operators.

...and optional

void modifies(T *param=0);  // default value optional, too
// vs
void modifies();
void modifies(T &param);

Parameter not modified

void uses(T const &param);
// vs
void uses(T param);

This is the interesting case. The rule of thumb is "cheap to copy" types are passed by value — these are generally small types (but not always) — while others are passed by const ref. However, if you need to make a copy within your function regardless, you should pass by value. (Yes, this exposes a bit of implementation detail. C'est le C++.)

...and optional

void uses(T const *param=0);  // default value optional, too
// vs
void uses();
void uses(T const &param);  // or optional(T param)

There's the least difference here between all situations, so choose whichever makes your life easiest.

Const by value is an implementation detail

void f(T);
void f(T const);

These declarations are actually the exact same function! When passing by value, const is purely an implementation detail. Try it out:

void f(int);
void f(int const) { /* implements above function, not an overload */ }

typedef void NC(int);       // typedefing function types
typedef void C(int const);

NC *nc = &f;  // nc is a function pointer
C *c = nc;    // C and NC are identical types

How to delete a cookie?

Here a good link on Quirksmode.

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}

ToggleButton in C# WinForms

You can just use a CheckBox and set its appearance to Button:

CheckBox checkBox = new System.Windows.Forms.CheckBox(); 
checkBox.Appearance = System.Windows.Forms.Appearance.Button; 

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

This problem can be caused by requests for certain files that don't exist. For example, requests for files in wp-content/uploads/ where the file does not exist.

If this is the situation you're seeing, you can solve the problem by going to .htaccess and changing this line:

RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

to:

RewriteRule ^(wp-(content|admin|includes).*) - [L]

The underlying issue is that the rule above triggers a rewrite to the exact same url with a slash in front and because there was a rewrite, the newly rewritten request goes back through the rules again and the same rule is triggered. By changing that line's "$1" to "-", no rewrite happens and so the rewriting process does not start over again with the same URL.

It's possible that there's a difference in how apache 2.2 and 2.4 handle this situation of only-difference-is-a-slash-in-front and that's why the default rules provided by WordPress aren't working perfectly.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

"Open in Browser context menu for HTML files" has been added in the latest build (2207). Its release date was 25 June 2012.

What is the most compatible way to install python modules on a Mac?

There's nothing wrong with using a MacPorts Python installation. If you are installing python modules from MacPorts but then not seeing them, that likely means you are not invoking the MacPorts python you installed to. In a terminal shell, you can use absolute paths to invoke the various Pythons that may be installed. For example:

$ /usr/bin/python2.5         # Apple-supplied 2.5 (Leopard)
$ /opt/local/bin/python2.5   # MacPorts 2.5
$ /opt/local/bin/python2.6   # MacPorts 2.6
$ /usr/local/bin/python2.6   # python.org (MacPython) 2.6
$ /usr/local/bin/python3.1   # python.org (MacPython) 3.1

To get the right python by default requires ensuring your shell $PATH is set properly to ensure that the right executable is found first. Another solution is to define shell aliases to the various pythons.

A python.org (MacPython) installation is fine, too, as others have suggested. easy_install can help but, again, because each Python instance may have its own easy_install command, make sure you are invoking the right easy_install.

Logical Operators, || or OR?

The difference between respectively || and OR and && and AND is operator precedence :

$bool = FALSE || TRUE;

  • interpreted as ($bool = (FALSE || TRUE))
  • value of $bool is TRUE

$bool = FALSE OR TRUE;

  • interpreted as (($bool = FALSE) OR TRUE)
  • value of $bool is FALSE

$bool = TRUE && FALSE;

  • interpreted as ($bool = (TRUE && FALSE))
  • value of $bool is FALSE

$bool = TRUE AND FALSE;

  • interpreted as (($bool = TRUE) AND FALSE)
  • value of $bool is TRUE

Kendo grid date column not formatting

The option I use is as follows:

columns.Bound(p => p.OrderDate).Format("{0:d}").ClientTemplate("#=formatDate(OrderDate)#");

function formatDate(OrderDate) {
    var formatedOrderDate = kendo.format("{0:d}", OrderDate);

    return formatedOrderDate;
}

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

If you got this error when working with your flutter project, you can add the following code in the module build.gradle and within Android block and then in the defaultConfig block. This error happened when I was trying to make a flutter apk build.

android{
    ...
    defaultConfig{
        ...
        //Add this ndk block of code to your build.gradle
        ndk {
            abiFilters 'armeabi-v7a', 'x86', 'armeabi'
        }
    }
}

Convert XML String to Object

You can generate class as described above, or write them manually:

[XmlRoot("msg")]
public class Message
{
    [XmlElement("id")]
    public string Id { get; set; }
    [XmlElement("action")]
    public string Action { get; set; }
}

Then you can use ExtendedXmlSerializer to serialize and deserialize.

Instalation You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer

Serialization:

var serializer = new ConfigurationContainer().Create();
var obj = new Message();
var xml = serializer.Serialize(obj);

Deserialization

var obj2 = serializer.Deserialize<Message>(xml);

This serializer support:

  • Deserialization xml from standard XMLSerializer
  • Serialization class, struct, generic class, primitive type, generic list and dictionary, array, enum
  • Serialization class with property interface
  • Serialization circular reference and reference Id
  • Deserialization of old version of xml
  • Property encryption
  • Custom serializer
  • Support XmlElementAttribute and XmlRootAttribute
  • POCO - all configurations (migrations, custom serializer...) are outside the class

ExtendedXmlSerializer support .NET 4.5 or higher and .NET Core. You can integrate it with WebApi and AspCore.

How to change line-ending settings

The normal way to control this is with git config

For example

git config --global core.autocrlf true

For details, scroll down in this link to Pro Git to the section named "core.autocrlf"


If you want to know what file this is saved in, you can run the command:

git config --global --edit

and the git global config file should open in a text editor, and you can see where that file was loaded from.

What's the difference between align-content and align-items?

I had the same confusion. After some tinkering based on many of the answers above, I can finally see the differences. In my humble opinion, the distinction is best demonstrated with a flex container that satisfies the following two conditions:

  1. The flex container itself has a height constraint (e.g., min-height: 60rem) and thus can become too tall for its content
  2. The child items enclosed in the container have uneven heights

Condition 1 helps me understand what content means relative to its parent container. When the content is flush with the container, we will not be able to see any positioning effects coming from align-content. It is only when we have extra space along the cross axis, we start to see its effect: It aligns the content relative to the boundaries of the parent container.

Condition 2 helps me visualize the effects of align-items: it aligns items relative to each other.


Here is a code example. Raw materials come from Wes Bos' CSS Grid tutorial (21. Flexbox vs. CSS Grid)

  • Example HTML:
  <div class="flex-container">
    <div class="item">Short</div>
    <div class="item">Longerrrrrrrrrrrrrr</div>
    <div class="item"></div>
    <div class="item" id="tall">This is Many Words</div>
    <div class="item">Lorem, ipsum.</div>
    <div class="item">10</div>
    <div class="item">Snickers</div>
    <div class="item">Wes Is Cool</div>
    <div class="item">Short</div>
  </div>
  • Example CSS:
.flex-container {
  display: flex;
  /*dictates a min-height*/
  min-height: 60rem;
  flex-flow: row wrap;
  border: 5px solid white;
  justify-content: center;
  align-items: center;
  align-content: flex-start;
 }

#tall {
  /*intentionally made tall*/
  min-height: 30rem;
}

.item {
  margin: 10px;
  max-height: 10rem;
}

Example 1: Let's narrow the viewport so that the content is flush with the container. This is when align-content: flex-start; has no effects since the entire content block is tightly fit inside the container (no extra room for repositioning!)

Also, note the 2nd row--see how the items are center aligned among themselves.

enter image description here

Example 2: As we widen the viewport, we no longer have enough content to fill the entire container. Now we start to see the effects of align-content: flex-start;--it aligns the content relative to the top edge of the container. enter image description here


These examples are based on flexbox, but the same principles are applicable to CSS grid. Hope this helps :)

How to compare two JSON have the same properties without order?

Lodash _.isEqual allows you to do that:

_x000D_
_x000D_
var_x000D_
remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": "CAN_REQUEST_TO_JOIN"},_x000D_
    localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", "allowExternalMembers": "false"};_x000D_
    _x000D_
console.log( _.isEqual(remoteJSON, localJSON) );
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Laravel - Route::resource vs Route::controller

For route controller method we have to define only one route. In get or post method we have to define the route separately.

And the resources method is used to creates multiple routes to handle a variety of Restful actions.

Here the Laravel documentation about this.

How to select data from 30 days?

Short version for easy use:

SELECT * 
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.

How to check if an object implements an interface?

Use

if (gor instanceof Monster) {
    //...
}

javax.persistence.PersistenceException: No Persistence provider for EntityManager named customerManager

my experience tells me that missing persistence.xml,will generate the same exception too.

i caught the same error msg today when i tried to run a jar package packed by ant.

when i used jar tvf to check the content of the jar file, i realized that "ant" forgot to pack the persistnece.xml for me.

after I manually repacked the jar file ,the error msg disappered.

so i believe maybe you should try simplely putting META-INF under src directory and placing your persistence.xml there.

What is Haskell used for in the real world?

From the Haskell Wiki:

Haskell has a diverse range of use commercially, from aerospace and defense, to finance, to web startups, hardware design firms and lawnmower manufacturers. This page collects resources on the industrial use of Haskell.

According to Wikipedia, the Haskell language was created out of the need to consolidate existing functional languages into a common one which could be used for future research in functional-language design.

It is apparent based on the information available that it has outgrown it's original purpose and is used for much more than research. It is now considered a general purpose functional programming language.

If you're still asking yourself, "Why should I use it?", then read the Why use it? section of the Haskell Wiki Introduction.

SQL - Update multiple records in one query

Camille's solution worked. Turned it into a basic PHP function, which writes up the SQL statement. Hope this helps someone else.

    function _bulk_sql_update_query($table, $array)
    {
        /*
         * Example:
        INSERT INTO mytable (id, a, b, c)
        VALUES (1, 'a1', 'b1', 'c1'),
        (2, 'a2', 'b2', 'c2'),
        (3, 'a3', 'b3', 'c3'),
        (4, 'a4', 'b4', 'c4'),
        (5, 'a5', 'b5', 'c5'),
        (6, 'a6', 'b6', 'c6')
        ON DUPLICATE KEY UPDATE id=VALUES(id),
        a=VALUES(a),
        b=VALUES(b),
        c=VALUES(c);
    */
        $sql = "";

        $columns = array_keys($array[0]);
        $columns_as_string = implode(', ', $columns);

        $sql .= "
      INSERT INTO $table
      (" . $columns_as_string . ")
      VALUES ";

        $len = count($array);
        foreach ($array as $index => $values) {
            $sql .= '("';
            $sql .= implode('", "', $array[$index]) . "\"";
            $sql .= ')';
            $sql .= ($index == $len - 1) ? "" : ", \n";
        }

        $sql .= "\nON DUPLICATE KEY UPDATE \n";

        $len = count($columns);
        foreach ($columns as $index => $column) {

            $sql .= "$column=VALUES($column)";
            $sql .= ($index == $len - 1) ? "" : ", \n";
        }

        $sql .= ";";

        return $sql;
    }

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

How to load/edit/run/save text files (.py) into an IPython notebook cell?

To write/save

%%writefile myfile.py

  • write/save cell contents into myfile.py (use -a to append). Another alias: %%file myfile.py

To run

%run myfile.py

  • run myfile.py and output results in the current cell

To load/import

%load myfile.py

  • load "import" myfile.py into the current cell

For more magic and help

%lsmagic

  • list all the other cool cell magic commands.

%COMMAND-NAME?

  • for help on how to use a certain command. i.e. %run?

Note

Beside the cell magic commands, IPython notebook (now Jupyter notebook) is so cool that it allows you to use any unix command right from the cell (this is also equivalent to using the %%bash cell magic command).

To run a unix command from the cell, just precede your command with ! mark. for example:

  • !python --version see your python version
  • !python myfile.py run myfile.py and output results in the current cell, just like %run (see the difference between !python and %run in the comments below).

Also, see this nbviewer for further explanation with examples. Hope this helps.

Python - Join with newline

The console is printing the representation, not the string itself.

If you prefix with print, you'll get what you expect.

See this question for details about the difference between a string and the string's representation. Super-simplified, the representation is what you'd type in source code to get that string.

How could I convert data from string to long in c#

long is internally represented as System.Int64 which is a 64-bit signed integer. The value you have taken "1100.25" is actually decimal and not integer hence it can not be converted to long.

You can use:

String strValue = "1100.25";
decimal lValue = Convert.ToDecimal(strValue);

to convert it to decimal value

Python 3: EOF when reading a line (Sublime Text 2 is angry)

help(input) shows what keyboard shortcuts produce EOF, namely, Unix: Ctrl-D, Windows: Ctrl-Z+Return:

input([prompt]) -> string

Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading.

You could reproduce it using an empty file:

$ touch empty
$ python3 -c "input()" < empty
Traceback (most recent call last):
  File "<string>", line 1, in <module>
EOFError: EOF when reading a line

You could use /dev/null or nul (Windows) as an empty file for reading. os.devnull shows the name that is used by your OS:

$ python3 -c "import os; print(os.devnull)"
/dev/null

Note: input() happily accepts input from a file/pipe. You don't need stdin to be connected to the terminal:

$ echo abc | python3 -c "print(input()[::-1])"
cba

Either handle EOFError in your code:

try:
    reply = input('Enter text')
except EOFError:
    break

Or configure your editor to provide a non-empty input when it runs your script e.g., by using a customized command line if it allows it: python3 "%f" < input_file

Fragments onResume from back stack

I have used enum FragmentTags to define all my fragment classes.

TAG_FOR_FRAGMENT_A(A.class),
TAG_FOR_FRAGMENT_B(B.class),
TAG_FOR_FRAGMENT_C(C.class)

pass FragmentTags.TAG_FOR_FRAGMENT_A.name() as fragment tag.

and now on

@Override
public void onBackPressed(){
   FragmentManager fragmentManager = getFragmentManager();
   Fragment current
   = fragmentManager.findFragmentById(R.id.fragment_container);
    FragmentTags fragmentTag = FragmentTags.valueOf(current.getTag());

  switch(fragmentTag){
    case TAG_FOR_FRAGMENT_A:
        finish();
        break;
   case TAG_FOR_FRAGMENT_B:
        fragmentManager.popBackStack();
        break;
   case default: 
   break;
}

How do I add a new sourceset to Gradle?

This was once written for Gradle 2.x / 3.x in 2016 and is far outdated!! Please have a look at the documented solutions in Gradle 4 and up


To sum up both old answers (get best and minimum viable of both worlds):

some warm words first:

  1. first, we need to define the sourceSet:

    sourceSets {
        integrationTest
    }
    
  2. next we expand the sourceSet from test, therefor we use the test.runtimeClasspath (which includes all dependenciess from test AND test itself) as classpath for the derived sourceSet:

    sourceSets {
        integrationTest {
            compileClasspath += sourceSets.test.runtimeClasspath
            runtimeClasspath += sourceSets.test.runtimeClasspath // ***)
        }
    }
    
    • note) somehow this redeclaration / extend for sourceSets.integrationTest.runtimeClasspath is needed, but should be irrelevant since runtimeClasspath always expands output + runtimeSourceSet, don't get it
  3. we define a dedicated task for just running integration tests:

    task integrationTest(type: Test) {
    }
    
  4. Configure the integrationTest test classes and classpaths use. The defaults from the java plugin use the test sourceSet

    task integrationTest(type: Test) {
        testClassesDir = sourceSets.integrationTest.output.classesDir
        classpath = sourceSets.integrationTest.runtimeClasspath
    }
    
  5. (optional) auto run after test

    integrationTest.dependsOn test
    

  6. (optional) add dependency from check (so it always runs when build or check are executed)

    tasks.check.dependsOn(tasks.integrationTest)
    
  7. (optional) add java,resources to the sourceSet to support auto-detection and create these "partials" in your IDE. i.e. IntelliJ IDEA will auto create sourceSet directories java and resources for each set if it doesn't exist:

    sourceSets {
         integrationTest {
             java
             resources
         }
    }
    

tl;dr

apply plugin: 'java'

// apply the runtimeClasspath from "test" sourceSet to the new one
// to include any needed assets: test, main, test-dependencies and main-dependencies
sourceSets {
    integrationTest {
        // not necessary but nice for IDEa's
        java
        resources

        compileClasspath += sourceSets.test.runtimeClasspath
        // somehow this redeclaration is needed, but should be irrelevant
        // since runtimeClasspath always expands compileClasspath
        runtimeClasspath += sourceSets.test.runtimeClasspath
    }
}

// define custom test task for running integration tests
task integrationTest(type: Test) {
    testClassesDir = sourceSets.integrationTest.output.classesDir
    classpath = sourceSets.integrationTest.runtimeClasspath
}
tasks.integrationTest.dependsOn(tasks.test)

referring to:

Unfortunatly, the example code on github.com/gradle/gradle/subprojects/docs/src/samples/java/customizedLayout/build.gradle or …/gradle/…/withIntegrationTests/build.gradle seems not to handle this or has a different / more complex / for me no clearer solution anyway!

Anaconda Installed but Cannot Launch Navigator

Open up a command terminal (CTRL+ALT+T) and try running this command:

anaconda-navigator

When I installed Anaconda, and read the website docs, they said that they tend to not add a file or menu path to run the navigator because there are so many different versions of different systems, instead they give the above terminal command to start the navigator GUI and advise on setting up a shortcut to do this process manually - if that works for you it shouldn't be too much trouble to do it this way - I do it like this personally

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

ExtJs Gridpanel store refresh

grid.getStore().reload({
  callback: function(){
    grid.getView().refresh();
  }
});

UIScrollView scroll to bottom programmatically

Setting the content offset to the height of the content size is wrong: it scrolls the bottom of the content to the top of the scroll view, and thus out of sight.

The correct solution is to scroll the bottom of the content to the bottom of the scroll view, like this (sv is the UIScrollView):

CGSize csz = sv.contentSize;
CGSize bsz = sv.bounds.size;
if (sv.contentOffset.y + bsz.height > csz.height) {
    [sv setContentOffset:CGPointMake(sv.contentOffset.x, 
                                     csz.height - bsz.height) 
                animated:YES];
}

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

How do I use the includes method in lodash to check if an object is in the collection?

The includes (formerly called contains and include) method compares objects by reference (or more precisely, with ===). Because the two object literals of {"b": 2} in your example represent different instances, they are not equal. Notice:

({"b": 2} === {"b": 2})
> false

However, this will work because there is only one instance of {"b": 2}:

var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true

On the other hand, the where(deprecated in v4) and find methods compare objects by their properties, so they don't require reference equality. As an alternative to includes, you might want to try some (also aliased as any):

_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true

How to set size for local image using knitr for markdown?

You can also read the image using png package for example and plot it like a regular plot using grid.raster from the grid package.

```{r fig.width=1, fig.height=10,echo=FALSE}
library(png)
library(grid)
img <- readPNG("path/to/your/image")
 grid.raster(img)
```

With this method you have full control of the size of you image.

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

How to merge multiple dicts with same key or different key?

To supplement the two-list solutions, here is a solution for processing a single list.

A sample list (NetworkX-related; manually formatted here for readability):

ec_num_list = [((src, tgt), ec_num['ec_num']) for src, tgt, ec_num in G.edges(data=True)]

print('\nec_num_list:\n{}'.format(ec_num_list))
ec_num_list:
[((82, 433), '1.1.1.1'),
  ((82, 433), '1.1.1.2'),
  ((22, 182), '1.1.1.27'),
  ((22, 3785), '1.2.4.1'),
  ((22, 36), '6.4.1.1'),
  ((145, 36), '1.1.1.37'),
  ((36, 154), '2.3.3.1'),
  ((36, 154), '2.3.3.8'),
  ((36, 72), '4.1.1.32'),
  ...] 

Note the duplicate values for the same edges (defined by the tuples). To collate those "values" to their corresponding "keys":

from collections import defaultdict
ec_num_collection = defaultdict(list)
for k, v in ec_num_list:
    ec_num_collection[k].append(v)

print('\nec_num_collection:\n{}'.format(ec_num_collection.items()))
ec_num_collection:
[((82, 433), ['1.1.1.1', '1.1.1.2']),   ## << grouped "values"
((22, 182), ['1.1.1.27']),
((22, 3785), ['1.2.4.1']),
((22, 36), ['6.4.1.1']),
((145, 36), ['1.1.1.37']),
((36, 154), ['2.3.3.1', '2.3.3.8']),    ## << grouped "values"
((36, 72), ['4.1.1.32']),
...] 

If needed, convert that list to dict:

ec_num_collection_dict = {k:v for k, v in zip(ec_num_collection, ec_num_collection)}

print('\nec_num_collection_dict:\n{}'.format(dict(ec_num_collection)))
  ec_num_collection_dict:
  {(82, 433): ['1.1.1.1', '1.1.1.2'],
  (22, 182): ['1.1.1.27'],
  (22, 3785): ['1.2.4.1'],
  (22, 36): ['6.4.1.1'],
  (145, 36): ['1.1.1.37'],
  (36, 154): ['2.3.3.1', '2.3.3.8'],
  (36, 72): ['4.1.1.32'],
  ...}

References

How can I do a BEFORE UPDATED trigger with sql server?

It is true that there aren't "before triggers" in MSSQL. However, you could still track the changes that were made on the table, by using the "inserted" and "deleted" tables together. When an update causes the trigger to fire, the "inserted" table stores the new values and the "deleted" table stores the old values. Once having this info, you could relatively easy simulate the "before trigger" behaviour.

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

A single listening port can accept more than one connection simultaneously.

There is a '64K' limit that is often cited, but that is per client per server port, and needs clarifying.

Each TCP/IP packet has basically four fields for addressing. These are:

source_ip source_port destination_ip destination_port
<----- client ------> <--------- server ------------>

Inside the TCP stack, these four fields are used as a compound key to match up packets to connections (e.g. file descriptors).

If a client has many connections to the same port on the same destination, then three of those fields will be the same - only source_port varies to differentiate the different connections. Ports are 16-bit numbers, therefore the maximum number of connections any given client can have to any given host port is 64K.

However, multiple clients can each have up to 64K connections to some server's port, and if the server has multiple ports or either is multi-homed then you can multiply that further.

So the real limit is file descriptors. Each individual socket connection is given a file descriptor, so the limit is really the number of file descriptors that the system has been configured to allow and resources to handle. The maximum limit is typically up over 300K, but is configurable e.g. with sysctl.

The realistic limits being boasted about for normal boxes are around 80K for example single threaded Jabber messaging servers.

Get list of JSON objects with Spring RestTemplate

If you would prefer a List of POJOs, one way to do it is like this:

class SomeObject {
    private int id;
    private String name;
}

public <T> List<T> getApi(final String path, final HttpMethod method) {     
    final RestTemplate restTemplate = new RestTemplate();
    final ResponseEntity<List<T>> response = restTemplate.exchange(
      path,
      method,
      null,
      new ParameterizedTypeReference<List<T>>(){});
    List<T> list = response.getBody();
    return list;
}

And use it like so:

 List<SomeObject> list = someService.getApi("http://localhost:8080/some/api",HttpMethod.GET);

Explanation for the above can be found here (https://www.baeldung.com/spring-rest-template-list) and is paraphrased below.

"There are a couple of things happening in the code above. First, we use ResponseEntity as our return type, using it to wrap the list of objects we really want. Second, we are calling RestTemplate.exchange() instead of getForObject().

This is the most generic way to use RestTemplate. It requires us to specify the HTTP method, optional request body, and a response type. In this case, we use an anonymous subclass of ParameterizedTypeReference for the response type.

This last part is what allows us to convert the JSON response into a list of objects that are the appropriate type. When we create an anonymous subclass of ParameterizedTypeReference, it uses reflection to capture information about the class type we want to convert our response to.

It holds on to this information using Java’s Type object, and we no longer have to worry about type erasure."

Prevent the keyboard from displaying on activity start

To expand upon the accepted answer by @Lucas:

Call this from your activity in one of the early life cycle events:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

Kotlin Example:

override fun onResume() {
  super.onResume()

  window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
}

How to write subquery inside the OUTER JOIN Statement

You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.

SELECT
       cs.CUSID
       ,dp.DEPID
FROM
    CUSTMR cs
        LEFT OUTER JOIN (
            SELECT
                    DEPID
                    ,DEPNAME
                FROM
                    DEPRMNT 
                WHERE
                    dp.DEPADDRESS = 'TOKYO'
        ) ss
            ON (
                ss.DEPID = cs.CUSID
                AND ss.DEPNAME = cs.CUSTNAME
            )
WHERE
    cs.CUSID != '' 

How to update maven repository in Eclipse?

In newer versions of Eclipse that use the M2E plugin it is:

Right-click on your project(s) --> Maven --> Update Project...

In the following dialog is a checkbox for forcing the update ("Force Update of Snapshots/Releases")

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

How to show loading spinner in jQuery?

Use the loading plugin: http://plugins.jquery.com/project/loading

$.loading.onAjax({img:'loading.gif'});

Error inflating when extending a class

The thing to understand here is that:

The constructor ViewClassName(Context context, AttributeSet attrs ) is called when inflating the customView via xml. You see you are not using the new keyword to instantiate your object i.e. you are not doing new GhostSurfaceCameraView(). Doing this you are calling the first constructor i.e. public View (Context context).

Whereas when inflating view from XML, i.e. when using setContentView(R.layout.ghostviewscreen); or using findViewById, you, NO, not you!, the android system calls the ViewClassName(Context context, AttributeSet attrs ) constructor.

This is clear when reading the documentation : "Constructor that is called when inflating a view from XML." See: https://developer.android.com/reference/android/view/View.html#View(android.content.Context,%20android.util.AttributeSet)

Hence, never forget basic polymorphism and never forget reading through the documentation. It saves a ton of headache.

Show history of a file?

Have you tried this:

gitk path/to/file

How to generate auto increment field in select query

DECLARE @id INT 
SET @id = 0 
UPDATE cartemp
SET @id = CarmasterID = @id + 1 
GO

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

using jQuery .animate to animate a div from right to left?

This worked for me

$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

New location for mysql config file is

/etc/mysql/mysql.conf.d/mysqld.cnf

How do I POST a x-www-form-urlencoded request using Fetch?

Even simpler:

body: new URLSearchParams({
      'userName': '[email protected]',
      'password': 'Password!',
      'grant_type': 'password'
    }),

Docs: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch

Pretty graphs and charts in Python

PLplot is a cross-platform software package for creating scientific plots. They aren't very pretty (eye catching), but they look good enough. Have a look at some examples (both source code and pictures).

The PLplot core library can be used to create standard x-y plots, semi-log plots, log-log plots, contour plots, 3D surface plots, mesh plots, bar charts and pie charts. It runs on Windows (2000, XP and Vista), Linux, Mac OS X, and other Unices.

Can't install laravel installer via composer

It says that it requires zip extension

laravel/installer v1.4.0 requires ext-zip...

Install using (to install the default version):

sudo apt install php-zip

Or, if you're running a specific version of PHP:

# For php v7.0
sudo apt-get install php7.0-zip

# For php v7.1
sudo apt-get install php7.1-zip

# For php v7.2
sudo apt-get install php7.2-zip

# For php v7.3
sudo apt-get install php7.3-zip

# For php v7.4
sudo apt-get install php7.4-zip

How to rename a file using svn?

Using TortoiseSVN worked easily on Windows for me.

http://tortoisesvn.net/

Right click file -> TortoiseSVN menu -> Repo-browser -> right click file in repository -> rename -> press Enter -> click Ok

Using SVN 1.8.8 TortoiseSVN version 1.8.5

Renaming files using node.js

For synchronous renaming use fs.renameSync

fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');

Nginx -- static file serving confusion with root & alias

alias is used to replace the location part path (LPP) in the request path, while the root is used to be prepended to the request path.

They are two ways to map the request path to the final file path.

alias could only be used in location block, and it will override the outside root.

alias and root cannot be used in location block together.

how does unix handle full path name with space and arguments?

Since spaces are used to separate command line arguments, they have to be escaped from the shell. This can be done with either a backslash () or quotes:

"/path/with/spaces in it/to/a/file"
somecommand -spaced\ option
somecommand "-spaced option"
somecommand '-spaced option'

This is assuming you're running from a shell. If you're writing code, you can usually pass the arguments directly, avoiding the problem:

Example in perl. Instead of doing:

print("code sample");system("somecommand -spaced option");

you can do

print("code sample");system("somecommand", "-spaced option");

Since when you pass the system() call a list, it doesn't break arguments on spaces like it does with a single argument call.

What is the difference between Sublime text and Github's Atom

In addition to the points from prior answers, it's worth clarifying the differences between these two products from the perspective of choices made in their development.

Sublime is binary compiled for the platform. Its core is written in C/C++ and a number of its features are implemented in Python, which is also the language used for extending it. Atom is written in Node.js/Coffeescript and runs under webkit, with Coffeescript being the extension language. Though similar in UI and UX, Sublime performs significantly better than Atom especially in "heavy lifting" like working with large files, complex SnR or plugins that do heavy processing on files/buffers. Though I expect improvements in Atom as it matures, design & platform choices limit performance.

The "closed" part of Sublime includes the API and UI. Apart from skins/themes and colourisers, the API currently makes it difficult to modify other aspects of the UI. For example, Sublime plugins can't interact with the sidebar, control or draw on the editing area (except in some limited ways eg. in the gutter) or manipulate the statusbar beyond basic text. Atom's "closed" part is unknown at the moment, but I get the sense it's smaller. Atom has a richer API (though poorly documented at present) with the design goal of allowing greater control of its UI. Being closely coupled with webkit offers numerous capabilities for UI feature enhancements not presently possible with Sublime. However, Sublime's extensions perform closer to native, so those that perform compute-intensive, highly repetitive or complex text manipulations in large buffers are feasible in Sublime.

Since more of Atom will be open, Github open-sourced Atom on May 6th. As a result it's likely that support and pace of development will be rapid. By contrast, Sublime's development has slowed significantly of late - but it's not dead. In particular there are a number of bugs, many quite trivial, that haven't been fixed by the developer. None are showstopping imo, but if you want something in rapid development with regular bugfixing and enhancements, Sublime will frustrate. That said, installable Atom packages for Windows and Linux are yet to be released and activity on the codebase seems to have cooled in the weeks before and since the announcement, according to Github's stats.

In terms of IDE functions, from a webdev perspective Atom will allow extensions to the point of approaching products like Webstorm, though none have appeared yet. It remains to be seen how Atom will perform with such "heavy" extensions, since the editor natively feels sluggish. Due to restrictions in the API and lack of underlying webkit, Sublime won't allow this level of UI customisation although the developer may extend the API to support such features in future. Again, Sublime's underlying performance allows for things that involve computational grunt; ST3's symbol indexing being an example that performs well even with big projects. And though Atom's UI is certainly modelled upon Sublime, some refinements are noticeably missing, such as Sublime's learning panels and tab-complete popups which weight the defaults in accordance with those you most use.

I see these products as complementary. The fact that they share similar visuals and keystrokes just adds to the fact. There will be situations where the use of either has advantages. Presently, Sublime is a mature product with feature parity across all three platforms, and a rich set of plugins. Atom is the new kid whose features will rapidly grow; it doesn't feel production ready just yet and there are concerns in the area of performance.

[Update/Edit: May 18, 2015]

A note about improvements to these two editors since the time of writing the above.

In addition to bugfixes and improvements to its core, Atom has experienced a rapid growth in third-party extensions, with autocomplete-plus becoming part of the standard Atom distribution. Extension quality varies widely and a particular irritation is the frequency by which unstable third party packages can crash the editor. Within the last year, Atom has moved to using React by way of shifting reflow/repaint activity to the GPU for performance reasons, significantly improving the responsiveness of the UI for typical editing actions (scrolling, cursor movement etc.). While this has markedly improved the feel of the editor, it still feels cumbersome for CPU intensive tasks as described above, and is still slow in startup. Apart from performance improvements, Atom feels significantly more stable across the board.

Development of Sublime has picked up again since Jan 2015, with bugfixes, some minor new features (tooltip API, build system improvements) and a major development in the form of a new yaml-based .sublime-syntax definition (to eventually replace the old xml .tmLanguage). Together with a custom regex engine which replaces Onigurama, the new system offers more potential for precise regex matching, is significantly faster (up to 4x) and can perform multiple matches in parallel. Apart from colouring syntax, Sublime uses these components for symbol indexing (goto definition etc.) and other language-aware features. In addition to further speeding up Sublime, particularly for large files, this feature should open up the potential for performant language-specific features such as code-refactoring etc.. Further 'big developments' are promised, though the author remains, as ever, tight lipped about them.

How do I change tab size in Vim?

To make the change for one session, use this command:

:set tabstop=4

To make the change permanent, add it to ~/.vimrc or ~/.vim/vimrc:

set tabstop=4

This will affect all files, not just css. To only affect css files:

autocmd Filetype css setlocal tabstop=4

as stated in Michal's answer.

UILabel - Wordwrap text

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.

If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.

Why does git perform fast-forward merges by default?

Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.

Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master.

alt text
(From nvie.com, Vincent Driessen, post "A successful Git branching model")

Incorporating a finished feature on develop

Finished features may be merged into the develop branch to add them to the upcoming release:

$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.

Jakub Narebski also mentions the config merge.ff:

By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set to false, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the --no-ff option from the command line).
When set to 'only', only such fast-forward merges are allowed (equivalent to giving the --ff-only option from the command line).


The fast-forward is the default because:

  • short-lived branches are very easy to create and use in Git
  • short-lived branches often isolate many commits that can be reorganized freely within that branch
  • those commits are actually part of the main branch: once reorganized, the main branch is fast-forwarded to include them.

But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.

In this case, you can end up setting this kind of config file:

[branch "master"]
# This is the list of cmdline options that should be added to git-merge 
# when I merge commits into the master branch.

# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.

# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.

mergeoptions = --no-commit --no-ff

The OP adds in the comments:

I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?

Jefromi answers:

I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.

To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.

More generally, I add:

it really depends on your development workflow:

  • if it is linear, one branch makes sense.
  • If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.

See "When should you branch?"

Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".

Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.

Multiple conditions in ngClass - Angular 4

You are trying to assign an array to ngClass, but the syntax for the array elements is wrong since you separate them with a || instead of a ,.

Try this:

<section [ngClass]="[menu1 ? 'class1' : '',  menu2 ? 'class1' : '', (something && (menu1 || menu2)) ? 'class2' : '']">

This other option should also work:

<section [ngClass.class1]="menu1 || menu2" [ngClass.class2] = "(menu1 || menu2) && something">    

Easiest way to copy a table from one database to another?

I use Navicat for MySQL...

It makes all database manipulation easy !

You simply select both databases in Navicat and then use.

 INSERT INTO Database2.Table1 SELECT * from Database1.Table1

Check whether a path is valid

There are plenty of good solutions in here, but as none of then check if the path is rooted in an existing drive here's another one:

private bool IsValidPath(string path)
{
    // Check if the path is rooted in a driver
    if (path.Length < 3) return false;
    Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
    if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;

    // Check if such driver exists
    IEnumerable<string> allMachineDrivers = DriveInfo.GetDrives().Select(drive => drive.Name);
    if (!allMachineDrivers.Contains(path.Substring(0, 3))) return false;

    // Check if the rest of the path is valid
    string InvalidFileNameChars = new string(Path.GetInvalidPathChars());
    InvalidFileNameChars += @":/?*" + "\"";
    Regex containsABadCharacter = new Regex("[" + Regex.Escape(InvalidFileNameChars) + "]");
    if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
        return false;
    if (path[path.Length - 1] == '.') return false;

    return true;
}

This solution does not take relative paths into account.

How can I set up an editor to work with Git on Windows?

Update September 2015 (6 years later)

The last release of git-for-Windows (2.5.3) now includes:

By configuring git config core.editor notepad, users can now use notepad.exe as their default editor.
Configuring git config format.commitMessageColumns 72 will be picked up by the notepad wrapper and line-wrap the commit message after the user edits it.

See commit 69b301b by Johannes Schindelin (dscho).

And Git 2.16 (Q1 2018) will show a message to tell the user that it is waiting for the user to finish editing when spawning an editor, in case the editor opens to a hidden window or somewhere obscure and the user gets lost.

See commit abfb04d (07 Dec 2017), and commit a64f213 (29 Nov 2017) by Lars Schneider (larsxschneider).
Helped-by: Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 0c69a13, 19 Dec 2017)

launch_editor(): indicate that Git waits for user input

When a graphical GIT_EDITOR is spawned by a Git command that opens and waits for user input (e.g. "git rebase -i"), then the editor window might be obscured by other windows.
The user might be left staring at the original Git terminal window without even realizing that s/he needs to interact with another window before Git can proceed. To this user Git appears hanging.

Print a message that Git is waiting for editor input in the original terminal and get rid of it when the editor returns, if the terminal supports erasing the last line


Original answer

I just tested it with git version 1.6.2.msysgit.0.186.gf7512 and Notepad++5.3.1

I prefer to not have to set an EDITOR variable, so I tried:

git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\""
# or
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\" %*"

That always gives:

C:\prog\git>git config --global --edit
"c:\Program Files\Notepad++\notepad++.exe" %*: c:\Program Files\Notepad++\notepad++.exe: command not found
error: There was a problem with the editor '"c:\Program Files\Notepad++\notepad++.exe" %*'.

If I define a npp.bat including:

"c:\Program Files\Notepad++\notepad++.exe" %*

and I type:

C:\prog\git>git config --global core.editor C:\prog\git\npp.bat

It just works from the DOS session, but not from the git shell.
(not that with the core.editor configuration mechanism, a script with "start /WAIT..." in it would not work, but only open a new DOS window)


Bennett's answer mentions the possibility to avoid adding a script, but to reference directly the program itself between simple quotes. Note the direction of the slashes! Use / NOT \ to separate folders in the path name!

git config --global core.editor \
"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

Or if you are in a 64 bit system:

git config --global core.editor \
"'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

But I prefer using a script (see below): that way I can play with different paths or different options without having to register again a git config.


The actual solution (with a script) was to realize that:
what you refer to in the config file is actually a shell (/bin/sh) script, not a DOS script.

So what does work is:

C:\prog\git>git config --global core.editor C:/prog/git/npp.bat

with C:/prog/git/npp.bat:

#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"

or

#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$*"

With that setting, I can do 'git config --global --edit' from DOS or Git Shell, or I can do 'git rebase -i ...' from DOS or Git Shell.
Bot commands will trigger a new instance of notepad++ (hence the -multiInst' option), and wait for that instance to be closed before going on.

Note that I use only '/', not \'. And I installed msysgit using option 2. (Add the git\bin directory to the PATH environment variable, but without overriding some built-in windows tools)

The fact that the notepad++ wrapper is called .bat is not important.
It would be better to name it 'npp.sh' and to put it in the [git]\cmd directory though (or in any directory referenced by your PATH environment variable).


See also:


lightfire228 adds in the comments:

For anyone having an issue where N++ just opens a blank file, and git doesn't take your commit message, see "Aborting commit due to empty message": change your .bat or .sh file to say:

"<path-to-n++" .git/COMMIT_EDITMSG -<arguments>. 

That will tell notepad++ to open the temp commit file, rather than a blank new one.

Filename timestamp in Windows CMD batch script getting truncated

See Stack Overflow question How to get current datetime on Windows command line, in a suitable format for using in a filename?.

Create a file, date.bat:

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-3 delims=/:/ " %%a in ('time /t') do (set mytime=%%a-%%b-%%c)
set mytime=%mytime: =% 
echo %mydate%_%mytime%

Run date.bat:

C:\>date.bat
2012-06-14_12-47-PM

UPDATE:

You can also do it with one line like this:

for /f "tokens=2-8 delims=.:/ " %%a in ("%date% %time%") do set DateNtime=%%c-%%a-%%b_%%d-%%e-%%f.%%g

Can "git pull --all" update all my local branches?

As of git 2.9:

git pull --rebase --autostash

See https://git-scm.com/docs/git-rebase

Automatically create a temporary stash before the operation begins, and apply it after the operation ends. This means that you can run rebase on a dirty worktree. However, use with care: the final stash application after a successful rebase might result in non-trivial conflicts.

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Graphical user interface Tutorial in C

My favourite UI tutorials all come from zetcode.com:

These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

tl;dr

The answer is NEVER! (unless you really know what you're doing)

9/10 times the solution can be resolved with a proper understanding of encoding/decoding.

1/10 people have an incorrectly defined locale or environment and need to set:

PYTHONIOENCODING="UTF-8"  

in their environment to fix console printing problems.

What does it do?

sys.setdefaultencoding("utf-8") (struck through to avoid re-use) changes the default encoding/decoding used whenever Python 2.x needs to convert a Unicode() to a str() (and vice-versa) and the encoding is not given. I.e:

str(u"\u20AC")
unicode("€")
"{}".format(u"\u20AC") 

In Python 2.x, the default encoding is set to ASCII and the above examples will fail with:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

(My console is configured as UTF-8, so "€" = '\xe2\x82\xac', hence exception on \xe2)

or

UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)

sys.setdefaultencoding("utf-8") will allow these to work for me, but won't necessarily work for people who don't use UTF-8. The default of ASCII ensures that assumptions of encoding are not baked into code

Console

sys.setdefaultencoding("utf-8") also has a side effect of appearing to fix sys.stdout.encoding, used when printing characters to the console. Python uses the user's locale (Linux/OS X/Un*x) or codepage (Windows) to set this. Occasionally, a user's locale is broken and just requires PYTHONIOENCODING to fix the console encoding.

Example:

$ export LANG=en_GB.gibberish
$ python
>>> import sys
>>> sys.stdout.encoding
'ANSI_X3.4-1968'
>>> print u"\u20AC"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 0: ordinal not in range(128)
>>> exit()

$ PYTHONIOENCODING=UTF-8 python
>>> import sys
>>> sys.stdout.encoding
'UTF-8'
>>> print u"\u20AC"
€

What's so bad with sys.setdefaultencoding("utf-8")?

People have been developing against Python 2.x for 16 years on the understanding that the default encoding is ASCII. UnicodeError exception handling methods have been written to handle string to Unicode conversions on strings that are found to contain non-ASCII.

From https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/

def welcome_message(byte_string):
    try:
        return u"%s runs your business" % byte_string
    except UnicodeError:
        return u"%s runs your business" % unicode(byte_string,
            encoding=detect_encoding(byte_string))

print(welcome_message(u"Angstrom (Å®)".encode("latin-1"))

Previous to setting defaultencoding this code would be unable to decode the “Å” in the ascii encoding and then would enter the exception handler to guess the encoding and properly turn it into unicode. Printing: Angstrom (Å®) runs your business. Once you’ve set the defaultencoding to utf-8 the code will find that the byte_string can be interpreted as utf-8 and so it will mangle the data and return this instead: Angstrom (U) runs your business.

Changing what should be a constant will have dramatic effects on modules you depend upon. It's better to just fix the data coming in and out of your code.

Example problem

While the setting of defaultencoding to UTF-8 isn't the root cause in the following example, it shows how problems are masked and how, when the input encoding changes, the code breaks in an unobvious way: UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 3131: invalid start byte

Confirm deletion in modal / dialog using Twitter Bootstrap?

Following solution is better than bootbox.js, because

  • It can do everything bootbox.js can do;
  • The use syntax is simpler
  • It allows you to elegantly control the color of your message using "error", "warning" or "info"
  • Bootbox is 986 lines long, mine only 110 lines long

digimango.messagebox.js:

_x000D_
_x000D_
const dialogTemplate = '\_x000D_
    <div class ="modal" id="digimango_messageBox" role="dialog">\_x000D_
        <div class ="modal-dialog">\_x000D_
            <div class ="modal-content">\_x000D_
                <div class ="modal-body">\_x000D_
                    <p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\_x000D_
                    <p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\_x000D_
                </div>\_x000D_
                <div class ="modal-footer">\_x000D_
                    <button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\_x000D_
                    <button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\_x000D_
                </div>\_x000D_
            </div>\_x000D_
        </div>\_x000D_
    </div>';_x000D_
_x000D_
_x000D_
// See the comment inside function digimango_onOkClick(event) {_x000D_
var digimango_numOfDialogsOpened = 0;_x000D_
_x000D_
_x000D_
function messageBox(msg, significance, options, actionConfirmedCallback) {_x000D_
    if ($('#digimango_MessageBoxContainer').length == 0) {_x000D_
        var iDiv = document.createElement('div');_x000D_
        iDiv.id = 'digimango_MessageBoxContainer';_x000D_
        document.getElementsByTagName('body')[0].appendChild(iDiv);_x000D_
        $("#digimango_MessageBoxContainer").html(dialogTemplate);_x000D_
    }_x000D_
_x000D_
    var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;_x000D_
_x000D_
    if (options == null) {_x000D_
        okButtonName = 'OK';_x000D_
        cancelButtonName = null;_x000D_
        showTextBox = null;_x000D_
        textBoxDefaultText = null;_x000D_
    } else {_x000D_
        okButtonName = options.okButtonName;_x000D_
        cancelButtonName = options.cancelButtonName;_x000D_
        showTextBox = options.showTextBox;_x000D_
        textBoxDefaultText = options.textBoxDefaultText;_x000D_
    }_x000D_
_x000D_
    if (showTextBox == true) {_x000D_
        if (textBoxDefaultText == null)_x000D_
            $('#digimango_messageBoxTextArea').val('');_x000D_
        else_x000D_
            $('#digimango_messageBoxTextArea').val(textBoxDefaultText);_x000D_
_x000D_
        $('#digimango_messageBoxTextArea').show();_x000D_
    }_x000D_
    else_x000D_
        $('#digimango_messageBoxTextArea').hide();_x000D_
_x000D_
    if (okButtonName != null)_x000D_
        $('#digimango_messageBoxOkButton').html(okButtonName);_x000D_
    else_x000D_
        $('#digimango_messageBoxOkButton').html('OK');_x000D_
_x000D_
    if (cancelButtonName == null)_x000D_
        $('#digimango_messageBoxCancelButton').hide();_x000D_
    else {_x000D_
        $('#digimango_messageBoxCancelButton').show();_x000D_
        $('#digimango_messageBoxCancelButton').html(cancelButtonName);_x000D_
    }_x000D_
_x000D_
    $('#digimango_messageBoxOkButton').unbind('click');_x000D_
    $('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);_x000D_
_x000D_
    $('#digimango_messageBoxCancelButton').unbind('click');_x000D_
    $('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);_x000D_
_x000D_
    var content = $("#digimango_messageBoxMessage");_x000D_
_x000D_
    if (significance == 'error')_x000D_
        content.attr('class', 'text-danger');_x000D_
    else if (significance == 'warning')_x000D_
        content.attr('class', 'text-warning');_x000D_
    else_x000D_
        content.attr('class', 'text-success');_x000D_
_x000D_
    content.html(msg);_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $("#digimango_messageBox").modal();_x000D_
_x000D_
    digimango_numOfDialogsOpened++;_x000D_
}_x000D_
_x000D_
function digimango_onOkClick(event) {_x000D_
    // JavaScript's nature is unblocking. So the function call in the following line will not block,_x000D_
    // thus the last line of this function, which is to hide the dialog, is executed before user_x000D_
    // clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count_x000D_
    // how many dialogs is currently showing. If we know there is still a dialog being shown, we do_x000D_
    // not execute the last line in this function._x000D_
    if (typeof (event.data.callback) != 'undefined')_x000D_
        event.data.callback($('#digimango_messageBoxTextArea').val());_x000D_
_x000D_
    digimango_numOfDialogsOpened--;_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $('#digimango_messageBox').modal('hide');_x000D_
}_x000D_
_x000D_
function digimango_onCancelClick() {_x000D_
    digimango_numOfDialogsOpened--;_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $('#digimango_messageBox').modal('hide');_x000D_
}
_x000D_
_x000D_
_x000D_

To use digimango.messagebox.js:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title>A useful generic message box</title>_x000D_
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />_x000D_
_x000D_
    <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />_x000D_
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>_x000D_
    <script src="~/Scripts/bootstrap.js" type="text/javascript"></script>_x000D_
    <script src="~/Scripts/bootbox.js" type="text/javascript"></script>_x000D_
_x000D_
    <script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
    <script type="text/javascript">_x000D_
        function testAlert() {_x000D_
            messageBox('Something went wrong!', 'error');_x000D_
        }_x000D_
_x000D_
        function testAlertWithCallback() {_x000D_
            messageBox('Something went wrong!', 'error', null, function () {_x000D_
                messageBox('OK clicked.');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testConfirm() {_x000D_
            messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {_x000D_
                messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testPrompt() {_x000D_
            messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {_x000D_
                messageBox('User entered "' + userInput + '".');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testPromptWithDefault() {_x000D_
            messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {_x000D_
                messageBox('User entered "' + userInput + '".');_x000D_
            });_x000D_
        }_x000D_
_x000D_
    </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <a href="#" onclick="testAlert();">Test alert</a> <br/>_x000D_
    <a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />_x000D_
    <a href="#" onclick="testConfirm();">Test confirm</a> <br/>_x000D_
    <a href="#" onclick="testPrompt();">Test prompt</a><br />_x000D_
    <a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_ enter image description here

The maximum value for an int type in Go

I would use math package for getting the maximal value and minimal value :

func printMinMaxValue() {
    // integer max
    fmt.Printf("max int64 = %+v\n", math.MaxInt64)
    fmt.Printf("max int32 = %+v\n", math.MaxInt32)
    fmt.Printf("max int16 = %+v\n", math.MaxInt16)

    // integer min
    fmt.Printf("min int64 = %+v\n", math.MinInt64)
    fmt.Printf("min int32 = %+v\n", math.MinInt32)

    fmt.Printf("max flloat64= %+v\n", math.MaxFloat64)
    fmt.Printf("max float32= %+v\n", math.MaxFloat32)

    // etc you can see more int the `math`package
}

Ouput :

max int64 = 9223372036854775807
max int32 = 2147483647
max int16 = 32767
min int64 = -9223372036854775808
min int32 = -2147483648
max flloat64= 1.7976931348623157e+308
max float32= 3.4028234663852886e+38

set initial viewcontroller in appdelegate - swift

I had done it in Objective-C. I hope it will be useful for you.

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

UIViewController *viewController;

NSUserDefaults *loginUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *check=[loginUserDefaults objectForKey:@"Checklog"];

if ([check isEqualToString:@"login"]) {
    
    viewController = [storyboard instantiateViewControllerWithIdentifier:@"SWRevealViewController"];
} else {
    
    viewController = [storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
}


self.window.rootViewController = viewController;
[self.window makeKeyAndVisible];