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.

Which header file do you include to use bool type in c in linux?

bool is just a macro that expands to _Bool. You can use _Bool with no #include very much like you can use int or double; it is a C99 keyword.

The macro is defined in <stdbool.h> along with 3 other macros.

The macros defined are

  • bool: macro expands to _Bool
  • false: macro expands to 0
  • true: macro expands to 1
  • __bool_true_false_are_defined: macro expands to 1

How to escape the % (percent) sign in C's printf?

The backslash in C is used to escape characters in strings. Strings would not recognize % as a special character, and therefore no escape would be necessary. printf is another matter: use %% to print one %.

"Multiple definition", "first defined here" errors

You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.

commands.h

#ifndef COMMANDS_H_
#define COMMANDS_H_

void f123();

#endif

commands.c

#include "commands.h"

void f123()
{
    /* code */
}

Convert hex string (char []) to int?

Something like this could be useful:

char str[] = "0x1800785";
int num;

sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num); 

Read man sscanf

What is a difference between unsigned int and signed int in C?

ISO C states what the differences are.

The int data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h as INT_MIN and INT_MAX respectively.

An unsigned int has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX from that same header file.

Beyond that, the standard does not mandate twos complement notation for encoding the values, that's just one of the possibilities. The three allowed types would have encodings of the following for 5 and -5 (using 16-bit data types):

        two's complement  |  ones' complement   |   sign/magnitude
    +---------------------+---------------------+---------------------+
 5  | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101 |
-5  | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101 |
    +---------------------+---------------------+---------------------+
  • In two's complement, you get a negative of a number by inverting all bits then adding 1.
  • In ones' complement, you get a negative of a number by inverting all bits.
  • In sign/magnitude, the top bit is the sign so you just invert that to get the negative.

Note that positive values have the same encoding for all representations, only the negative values are different.

Note further that, for unsigned values, you do not need to use one of the bits for a sign. That means you get more range on the positive side (at the cost of no negative encodings, of course).

And no, 5 and -5 cannot have the same encoding regardless of which representation you use. Otherwise, there'd be no way to tell the difference.


As an aside, there are currently moves underway, in both C and C++ standards, to nominate two's complement as the only encoding for negative integers.

printf \t option

That's something controlled by your terminal, not by printf.

printf simply sends a \t to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.

How to make child process die after parent exits?

Install a trap handler to catch SIGINT, which kills off your child process if it's still alive, though other posters are correct that it won't catch SIGKILL.

Open a .lockfile with exclusive access and have the child poll on it trying to open it - if the open succeeds, the child process should exit

Understanding INADDR_ANY for socket programming

INADDR_ANY is used when you don't need to bind a socket to a specific IP. When you use this value as the address when calling bind(), the socket accepts connections to all the IPs of the machine.

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

Difference between static memory allocation and dynamic memory allocation

Static memory allocation. Memory allocated will be in stack.

int a[10];

Dynamic memory allocation. Memory allocated will be in heap.

int *a = malloc(sizeof(int) * 10);

and the latter should be freed since there is no Garbage Collector(GC) in C.

free(a);

C - freeing structs

This way you only need to free the structure because the fields are arrays with static sizes which will be allocated as part of the structure. This is also the reason that the addresses you see match: the array is the first thing in that structure. If you declared the fields as char * you would have to manually malloc and free them as well.

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 set all elements of an array to zero or any same value?

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 };    // Will initialize all elements to 0
int myArray[10] = { 5 };    // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0
/************************************************************************************/
int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i;  // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
    myArray[i] = 5;
}
/************************************************************************************/
int myArray[10] = {[0 ... 9] = 5}; // This works only in GCC

fork() child and parent processes

It is printing the statement twice because it is printing it for both the parent and the child. The parent has a parent id of 0

Try something like this:

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),getppid());
 else 
    printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), getppid() );

What do .c and .h file extensions mean to C?

.c : c file (where the real action is, in general)

.h : header file (to be included with a preprocessor #include directive). Contains stuff that is normally deemed to be shared with other parts of your code, like function prototypes, #define'd stuff, extern declaration for global variables (oh, the horror) and the like.

Technically, you could put everything in a single file. A whole C program. million of lines. But we humans tend to organize things. So you create different C files, each one containing particular functions. That's all nice and clean. Then suddenly you realize that a declaration you have into a given C file should exist also in another C file. So you would duplicate them. The best is therefore to extract the declaration and put it into a common file, which is the .h

For example, in the cs50.h you find what are called "forward declarations" of your functions. A forward declaration is a quick way to tell the compiler how a function should be called (e.g. what input params) and what it returns, so it can perform proper checking (for example if you call a function with the wrong number of parameters, it will complain).

Another example. Suppose you write a .c file containing a function performing regular expression matching. You want your function to accept the regular expression, the string to match, and a parameter that tells if the comparison has to be case insensitive.

in the .c you will therefore put

bool matches(string regexp, string s, int flags) { the code }

Now, assume you want to pass the following flags:

0: if the search is case sensitive

1: if the search is case insensitive

And you want to keep yourself open to new flags, so you did not put a boolean. playing with numbers is hard, so you define useful names for these flags

#define MATCH_CASE_SENSITIVE 0
#define MATCH_CASE_INSENSITIVE 1

This info goes into the .h, because if any program wants to use these labels, it has no way of knowing them unless you include the info. Of course you can put them in the .c, but then you would have to include the .c code (whole!) which is a waste of time and a source of trouble.

Is there a typical state machine implementation pattern?

I found a really slick C implementation of Moore FSM on the edx.org course Embedded Systems - Shape the World UTAustinX - UT.6.02x, chapter 10, by Jonathan Valvano and Ramesh Yerraballi....

struct State {
  unsigned long Out;  // 6-bit pattern to output
  unsigned long Time; // delay in 10ms units 
  unsigned long Next[4]; // next state for inputs 0,1,2,3
}; 

typedef const struct State STyp;

//this example has 4 states, defining constants/symbols using #define
#define goN   0
#define waitN 1
#define goE   2
#define waitE 3


//this is the full FSM logic coded into one large array of output values, delays, 
//and next states (indexed by values of the inputs)
STyp FSM[4]={
 {0x21,3000,{goN,waitN,goN,waitN}}, 
 {0x22, 500,{goE,goE,goE,goE}},
 {0x0C,3000,{goE,goE,waitE,waitE}},
 {0x14, 500,{goN,goN,goN,goN}}};
unsigned long currentState;  // index to the current state 

//super simple controller follows
int main(void){ volatile unsigned long delay;
//embedded micro-controller configuration omitteed [...]
  currentState = goN;  
  while(1){
    LIGHTS = FSM[currentState].Out;  // set outputs lines (from FSM table)
    SysTick_Wait10ms(FSM[currentState].Time);
    currentState = FSM[currentState].Next[INPUT_SENSORS];  
  }
}

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

A NULL pointer points to memory that doesn't exist. This may be address 0x00000000 or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator:

int a, b, c; // some integers
int *pi;     // a pointer to an integer

a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference

This is exactly the same thing as a NullReferenceException in C#, except that pointers in C can point to any data object, even elements inside an array.

self referential struct definition?

In C, you cannot reference the typedef that you're creating withing the structure itself. You have to use the structure name, as in the following test program:

#include <stdio.h>
#include <stdlib.h>

typedef struct Cell {
  int cellSeq;
  struct Cell* next; /* 'tCell *next' will not work here */
} tCell;

int main(void) {
    int i;
    tCell *curr;
    tCell *first;
    tCell *last;

    /* Construct linked list, 100 down to 80. */

    first = malloc (sizeof (tCell));
    last = first;
    first->cellSeq = 100;
    first->next = NULL;
    for (i = 0; i < 20; i++) {
        curr = malloc (sizeof (tCell));
        curr->cellSeq = last->cellSeq - 1;
        curr->next = NULL;
        last->next = curr;
        last = curr;
    }

    /* Walk the list, printing sequence numbers. */

    curr = first;
    while (curr != NULL) {
        printf ("Sequence = %d\n", curr->cellSeq);
        curr = curr->next;
    }

    return 0;
}

Although it's probably a lot more complicated than this in the standard, you can think of it as the compiler knowing about struct Cell on the first line of the typedef but not knowing about tCell until the last line :-) That's how I remember that rule.

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

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

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

How to read from stdin with fgets()?

If you want to concatenate the input, then replace printf("%s\n", buffer); with strcat(big_buffer, buffer);. Also create and initialize the big buffer at the beginning: char *big_buffer = new char[BIG_BUFFERSIZE]; big_buffer[0] = '\0';. You should also prevent a buffer overrun by verifying the current buffer length plus the new buffer length does not exceed the limit: if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE). The modified program would look like this:

#include <stdio.h>
#include <string.h>

#define BUFFERSIZE 10
#define BIG_BUFFERSIZE 1024

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    char *big_buffer = new char[BIG_BUFFERSIZE];
    big_buffer[0] = '\0';
    printf("Enter a message: \n");
    while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
    {
        if ((strlen(big_buffer) + strlen(buffer)) < BIG_BUFFERSIZE)
        {
            strcat(big_buffer, buffer);
        }
    }
    return 0;
}

Undefined reference to sqrt (or other mathematical functions)

Just adding the #include <math.h> in c source file and -lm in Makefile at the end will work for me.

    gcc -pthread -o p3 p3.c -lm

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

The termination of an array of characters with a null character is just a convention that is specifically for strings in C. You are dealing with something completely different -- an array of character pointers -- so it really has no relation to the convention for C strings. Sure, you could choose to terminate it with a null pointer; that perhaps could be your convention for arrays of pointers. There are other ways to do it. You can't ask people how it "should" work, because you're assuming some convention that isn't there.

error: function returns address of local variable

All the answer explain the problem really good.

However, I would like to add another information.

I faced the same problem at the moment I wanted the output of a function to be a vector.

In this situation, the common solution is to declare the output as an argument of the function itself. This way, the alloc of the variable and the physical space necessary to store the information are managed outside the function. Pseudocode to explain the classical solution is:

void function(int input, int* output){
    //...
    output[0] = something;
    output[1] = somethig_else;
    //...
    return;
}

In this case, the example code within the question should be changed in:

void foo(int x, char* a){
     if(x < 0){
        char b = "blah";
        //...
        strcpy(a, b);
        //..
        return;
      }
    //..
}

%i or %d to print integer in C using printf()?

They are completely equivalent when used with printf(). Personally, I prefer %d, it's used more often (should I say "it's the idiomatic conversion specifier for int"?).

(One difference between %i and %d is that when used with scanf(), then %d always expects a decimal integer, whereas %i recognizes the 0 and 0x prefixes as octal and hexadecimal, but no sane programmer uses scanf() anyway so this should not be a concern.)

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

How to compare strings in C conditional preprocessor-directives

Use numeric values instead of strings.

Finally to convert the constants JACK or QUEEN to a string, use the stringize (and/or tokenize) operators.

Meaning of "referencing" and "dereferencing" in C

Referencing

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

Example:

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

Dereferencing

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

Example:

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

Why is the gets function so dangerous that it should not be used?

Because gets doesn't do any kind of check while getting bytes from stdin and putting them somewhere. A simple example:

char array1[] = "12345";
char array2[] = "67890";

gets(array1);

Now, first of all you are allowed to input how many characters you want, gets won't care about it. Secondly the bytes over the size of the array in which you put them (in this case array1) will overwrite whatever they find in memory because gets will write them. In the previous example this means that if you input "abcdefghijklmnopqrts" maybe, unpredictably, it will overwrite also array2 or whatever.

The function is unsafe because it assumes consistent input. NEVER USE IT!

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.

The most efficient way to implement an integer based power function pow(int, int)

Just as a follow up to comments on the efficiency of exponentiation by squaring.

The advantage of that approach is that it runs in log(n) time. For example, if you were going to calculate something huge, such as x^1048575 (2^20 - 1), you only have to go thru the loop 20 times, not 1 million+ using the naive approach.

Also, in terms of code complexity, it is simpler than trying to find the most optimal sequence of multiplications, a la Pramod's suggestion.

Edit:

I guess I should clarify before someone tags me for the potential for overflow. This approach assumes that you have some sort of hugeint library.

What primitive data type is time_t?

You can use the function difftime. It returns the difference between two given time_t values, the output value is double (see difftime documentation).

time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0); 
printf("%g",actual_time_sec);

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

Difference between return 1, return 0, return -1 and exit?

return from main() is equivalent to exit

the program terminates immediately execution with exit status set as the value passed to return or exit

return in an inner function (not main) will terminate immediately the execution of the specific function returning the given result to the calling function.

exit from anywhere on your code will terminate program execution immediately.


status 0 means the program succeeded.

status different from 0 means the program exited due to error or anomaly.

If you exit with a status different from 0 you're supposed to print an error message to stderr so instead of using printf better something like

if(errorOccurred) {
    fprintf(stderr, "meaningful message here\n");
    return -1;
}

note that (depending on the OS you're on) there are some conventions about return codes.

Google for "exit status codes" or similar and you'll find plenty of information on SO and elsewhere.


Worth mentioning that the OS itself may terminate your program with specific exit status codes if you attempt to do some invalid operations like reading memory you have no access to.

How to use the addr2line command in Linux?

You need to specify an offset to addr2line, not a virtual address (VA). Presumably if you had address space randomization turned off, you could use a full VA, but in most modern OSes, address spaces are randomized for a new process.

Given the VA 0x4005BDC by valgrind, find the base address of your process or library in memory. Do this by examining the /proc/<PID>/maps file while your program is running. The line of interest is the text segment of your process, which is identifiable by the permissions r-xp and the name of your program or library.

Let's say that the base VA is 0x0x4005000. Then you would find the difference between the valgrind supplied VA and the base VA: 0xbdc. Then, supply that to add2line:

addr2line -e a.out -j .text 0xbdc

And see if that gets you your line number.

Best C/C++ Network Library

Aggregated List of Libraries

Initialize/reset struct to zero/null

The way to do such a thing when you have modern C (C99) is to use a compound literal.

a = (const struct x){ 0 };

This is somewhat similar to David's solution, only that you don't have to worry to declare an the empty structure or whether to declare it static. If you use the const as I did, the compiler is free to allocate the compound literal statically in read-only storage if appropriate.

What does "collect2: error: ld returned 1 exit status" mean?

Try running task manager to determine if your program is still running.

If it is running then stop it and run it again. the [Error] ld returned 1 exit status will not come back

How to find the remainder of a division in C?

Use the modulus operator %, it returns the remainder.

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);
}

Why am I getting "void value not ignored as it ought to be"?

The original poster is quoting a GCC compiler error message, but even by reading this thread, it's not clear that the error message is properly addressed - except by @pmg's answer. (+1, btw)


error: void value not ignored as it ought to be

This is a GCC error message that means the return-value of a function is 'void', but that you are trying to assign it to a non-void variable.

Example:

void myFunction()
{
   //...stuff...
}

int main()
{
   int myInt = myFunction(); //Compile error!

    return 0;
}

You aren't allowed to assign void to integers, or any other type.

In the OP's situation:

int a = srand(time(NULL));

...is not allowed. srand(), according to the documentation, returns void.

This question is a duplicate of:

I am responding, despite it being duplicates, because this is the top result on Google for this error message. Because this thread is the top result, it's important that this thread gives a succinct, clear, and easily findable result.

Where do I find the definition of size_t?

Practically speaking size_t represents the number of bytes you can address. On most modern architectures for the last 10-15 years that has been 32 bits which has also been the size of a unsigned int. However we are moving to 64bit addressing while the uint will most likely stay at 32bits (it's size is not guaranteed in the c++ standard). To make your code that depends on the memory size portable across architectures you should use a size_t. For example things like array sizes should always use size_t's. If you look at the standard containers the ::size() always returns a size_t.

Also note, visual studio has a compile option that can check for these types of errors called "Detect 64-bit Portability Issues".

`getchar()` gives the same output as the input string

According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:

putchar(c);
printf("\n");     
c = getchar();

Now look at the output compared to the original code.

Another example that will explain you the concept of getchar and buffered stdin :

void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}

Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.

This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.

Rounding up to next power of 2

I'm trying to get nearest lower power of 2 and made this function. May it help you.Just multiplied nearest lower number times 2 to get nearest upper power of 2

int nearest_upper_power(int number){
    int temp=number;
    while((number&(number-1))!=0){
        temp<<=1;
        number&=temp;
    }
    //Here number is closest lower power 
    number*=2;
    return number;
}

how to stop a loop arduino

This will turn off interrupts and put the CPU into (permanent until reset/power toggled) sleep:

cli();
sleep_enable();
sleep_cpu();

See also http://arduino.land/FAQ/content/7/47/en/how-to-stop-an-arduino-sketch.html, for more details.

Sleep function in Windows, using C

Include the following function at the start of your code, whenever you want to busy wait. This is distinct from sleep, because the process will be utilizing 100% cpu while this function is running.

void sleep(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock())
        ;
}

Note that the name sleep for this function is misleading, since the CPU will not be sleeping at all.

C - function inside struct

You are trying to group code according to struct. C grouping is by file. You put all the functions and internal variables in a header or a header and a object ".o" file compiled from a c source file.

It is not necessary to reinvent object-orientation from scratch for a C program, which is not an object oriented language.

I have seen this before. It is a strange thing. Coders, some of them, have an aversion to passing an object they want to change into a function to change it, even though that is the standard way to do so.

I blame C++, because it hid the fact that the class object is always the first parameter in a member function, but it is hidden. So it looks like it is not passing the object into the function, even though it is.

Client.addClient(Client& c); // addClient first parameter is actually 
                             // "this", a pointer to the Client object.

C is flexible and can take passing things by reference.

A C function often returns only a status byte or int and that is often ignored. In your case a proper form might be

 err = addClient( container_t  cnt, client_t c);
 if ( err != 0 )
   { fprintf(stderr, "could not add client (%d) \n", err ); 

addClient would be in Client.h or Client.c

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

fcntl() has always worked reliably for me. In any case, here is the function I use to enable/disable blocking on a socket:

#include <fcntl.h>

/** Returns true on success, or false if there was an error */
bool SetSocketBlockingEnabled(int fd, bool blocking)
{
   if (fd < 0) return false;

#ifdef _WIN32
   unsigned long mode = blocking ? 0 : 1;
   return (ioctlsocket(fd, FIONBIO, &mode) == 0) ? true : false;
#else
   int flags = fcntl(fd, F_GETFL, 0);
   if (flags == -1) return false;
   flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
   return (fcntl(fd, F_SETFL, flags) == 0) ? true : false;
#endif
}

How to make parent wait for all child processes to finish?

Use waitpid() like this:

pid_t childPid;  // the child process that the execution will soon run inside of. 
childPid = fork();

if(childPid == 0)  // fork succeeded 
{   
   // Do something   
   exit(0); 
}

else if(childPid < 0)  // fork failed 
{    
   // log the error
}

else  // Main (parent) process after fork succeeds 
{    
    int returnStatus;    
    waitpid(childPid, &returnStatus, 0);  // Parent process waits here for child to terminate.

    if (returnStatus == 0)  // Verify child process terminated without error.  
    {
       printf("The child process terminated normally.");    
    }

    if (returnStatus == 1)      
    {
       printf("The child process terminated with an error!.");    
    }
}

C: printf a float value

You can do it like this:

printf("%.6f", myFloat);

6 represents the number of digits after the decimal separator.

Getting IPV4 address from a sockaddr structure

inet_ntoa() works for IPv4; inet_ntop() works for both IPv4 and IPv6.

Given an input struct sockaddr *res, here are two snippets of code (tested on macOS):

Using inet_ntoa()

#include <arpa/inet.h>

struct sockaddr_in *addr_in = (struct sockaddr_in *)res;
char *s = inet_ntoa(addr_in->sin_addr);
printf("IP address: %s\n", s);

Using inet_ntop()

#include <arpa/inet.h>
#include <stdlib.h>

char *s = NULL;
switch(res->sa_family) {
    case AF_INET: {
        struct sockaddr_in *addr_in = (struct sockaddr_in *)res;
        s = malloc(INET_ADDRSTRLEN);
        inet_ntop(AF_INET, &(addr_in->sin_addr), s, INET_ADDRSTRLEN);
        break;
    }
    case AF_INET6: {
        struct sockaddr_in6 *addr_in6 = (struct sockaddr_in6 *)res;
        s = malloc(INET6_ADDRSTRLEN);
        inet_ntop(AF_INET6, &(addr_in6->sin6_addr), s, INET6_ADDRSTRLEN);
        break;
    }
    default:
        break;
}
printf("IP address: %s\n", s);
free(s);

What is a segmentation fault?

A segmentation fault or access violation occurs when a program attempts to access a memory location that is not exist, or attempts to access a memory location in a way that is not allowed.

 /* "Array out of bounds" error 
   valid indices for array foo
   are 0, 1, ... 999 */
   int foo[1000];
   for (int i = 0; i <= 1000 ; i++) 
   foo[i] = i;

Here i[1000] not exist, so segfault occurs.

Causes of segmentation fault:

it arise primarily due to errors in use of pointers for virtual memory addressing, particularly illegal access.

De-referencing NULL pointers – this is special-cased by memory management hardware.

Attempting to access a nonexistent memory address (outside process’s address space).

Attempting to access memory the program does not have rights to (such as kernel structures in process context).

Attempting to write read-only memory (such as code segment).

How to initialize array to 0 in C?

If you'd like to initialize the array to values other than 0, with gcc you can do:

int array[1024] = { [ 0 ... 1023 ] = -1 };

This is a GNU extension of C99 Designated Initializers. In older GCC, you may need to use -std=gnu99 to compile your code.

Ranges of floating point datatype in C?

Infinity, NaN and subnormals

These are important caveats that no other answer has mentioned so far.

First read this introduction to IEEE 754 and subnormal numbers: What is a subnormal floating point number?

Then, for single precision floats (32-bit):

  • IEEE 754 says that if the exponent is all ones (0xFF == 255), then it represents either NaN or Infinity.

    This is why the largest non-infinite number has exponent 0xFE == 254 and not 0xFF.

    Then with the bias, it becomes:

    254 - 127 == 127
    
  • FLT_MIN is the smallest normal number. But there are smaller subnormal ones! Those take up the -127 exponent slot.

All asserts of the following program pass on Ubuntu 18.04 amd64:

#include <assert.h>
#include <float.h>
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>

float float_from_bytes(
    uint32_t sign,
    uint32_t exponent,
    uint32_t fraction
) {
    uint32_t bytes;
    bytes = 0;
    bytes |= sign;
    bytes <<= 8;
    bytes |= exponent;
    bytes <<= 23;
    bytes |= fraction;
    return *(float*)&bytes;
}

int main(void) {
    /* All 1 exponent and non-0 fraction means NaN.
     * There are of course many possible representations,
     * and some have special semantics such as signalling vs not.
     */
    assert(isnan(float_from_bytes(0, 0xFF, 1)));
    assert(isnan(NAN));
    printf("nan                  = %e\n", NAN);

    /* All 1 exponent and 0 fraction means infinity. */
    assert(INFINITY == float_from_bytes(0, 0xFF, 0));
    assert(isinf(INFINITY));
    printf("infinity             = %e\n", INFINITY);

    /* ANSI C defines FLT_MAX as the largest non-infinite number. */
    assert(FLT_MAX == 0x1.FFFFFEp127f);
    /* Not 0xFF because that is infinite. */
    assert(FLT_MAX == float_from_bytes(0, 0xFE, 0x7FFFFF));
    assert(!isinf(FLT_MAX));
    assert(FLT_MAX < INFINITY);
    printf("largest non infinite = %e\n", FLT_MAX);

    /* ANSI C defines FLT_MIN as the smallest non-subnormal number. */
    assert(FLT_MIN == 0x1.0p-126f);
    assert(FLT_MIN == float_from_bytes(0, 1, 0));
    assert(isnormal(FLT_MIN));
    printf("smallest normal      = %e\n", FLT_MIN);

    /* The smallest non-zero subnormal number. */
    float smallest_subnormal = float_from_bytes(0, 0, 1);
    assert(smallest_subnormal == 0x0.000002p-126f);
    assert(0.0f < smallest_subnormal);
    assert(!isnormal(smallest_subnormal));
    printf("smallest subnormal   = %e\n", smallest_subnormal);

    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run with:

gcc -ggdb3 -O0 -std=c11 -Wall -Wextra -Wpedantic -Werror -o subnormal.out subnormal.c
./subnormal.out

Output:

nan                  = nan
infinity             = inf
largest non infinite = 3.402823e+38
smallest normal      = 1.175494e-38
smallest subnormal   = 1.401298e-45

Convert Python program to C/C++ code?

Shed Skin is "a (restricted) Python-to-C++ compiler".

C free(): invalid pointer

You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.

There are two main types of memory you seem to be confusing - stack memory and heap memory.

  • Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main, it sets aside some memory for your variables you've declared (p,token, and so on).

  • Heap memory lives from when you malloc it to when you free it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!

You have a few errors:

  • You're trying to free memory that's not heap memory. Don't do that.

  • You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.

For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).

EDIT: The malloc function does allocate heap memory*.

"9.9.1 The malloc and free Functions

The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."

~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011

EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.

Static linking vs dynamic linking

It is pretty simple, really. When you make a change in your source code, do you want to wait 10 minutes for it to build or 20 seconds? Twenty seconds is all I can put up with. Beyond that, I either get out the sword or start thinking about how I can use separate compilation and linking to bring it back into the comfort zone.

Flushing buffers in C

Flushing the output buffers:

printf("Buffered, will be flushed");
fflush(stdout); // Prints to screen or whatever your standard out is

or

fprintf(fd, "Buffered, will be flushed");
fflush(fd);  //Prints to a file

Can be a very helpful technique. Why would you want to flush an output buffer? Usually when I do it, it's because the code is crashing and I'm trying to debug something. The standard buffer will not print everytime you call printf() it waits until it's full then dumps a bunch at once. So if you're trying to check if you're making it to a function call before a crash, it's helpful to printf something like "got here!", and sometimes the buffer hasn't been flushed before the crash happens and you can't tell how far you've really gotten.

Another time that it's helpful, is in multi-process or multi-thread code. Again, the buffer doesn't always flush on a call to a printf(), so if you want to know the true order of execution of multiple processes you should fflush the buffer after every print.

I make a habit to do it, it saves me a lot of headache in debugging. The only downside I can think of to doing so is that printf() is an expensive operation (which is why it doesn't by default flush the buffer).


As far as flushing the input buffer (stdin), you should not do that. Flushing stdin is undefined behavior according to the C11 standard §7.21.5.2 part 2:

If stream points to an output stream ... the fflush function causes any unwritten data for that stream ... to be written to the file; otherwise, the behavior is undefined.

On some systems, Linux being one as you can see in the man page for fflush(), there's a defined behavior but it's system dependent so your code will not be portable.

Now if you're worried about garbage "stuck" in the input buffer you can use fpurge() on that. See here for more on fflush() and fpurge()

Using true and false in C

I prefer (1) when i define a variable but in expressions i never compare against true and false just take the implicit C definition of if(flag) or if(!flag) or if(ptr). Thats the C way to do things.

What can be the reasons of connection refused errors?

From the standpoint of a Checkpoint firewall, you will see a message from the firewall if you actually choose Reject as an Action thereby exposing to a propective attacker the presence of a firewall in front of the server. The firewall will silently drop all connections that doesn't match the policy. Connection refused almost always comes from the server

How is a CRC32 checksum calculated?

The polynomial for CRC32 is:

x32 + x26 + x23 + x22 + x16 + x12 + x11 + x10 + x8 + x7 + x5 + x4 + x2 + x + 1

Or in hex and binary:

0x 01 04 C1 1D B7
1 0000 0100 1100 0001 0001 1101 1011 0111

The highest term (x32) is usually not explicitly written, so it can instead be represented in hex just as

0x 04 C1 1D B7

Feel free to count the 1s and 0s, but you'll find they match up with the polynomial, where 1 is bit 0 (or the first bit) and x is bit 1 (or the second bit).

Why this polynomial? Because there needs to be a standard given polynomial and the standard was set by IEEE 802.3. Also it is extremely difficult to find a polynomial that detects different bit errors effectively.

You can think of the CRC-32 as a series of "Binary Arithmetic with No Carries", or basically "XOR and shift operations". This is technically called Polynomial Arithmetic.

To better understand it, think of this multiplication:

(x^3 + x^2 + x^0)(x^3 + x^1 + x^0)
= (x^6 + x^4 + x^3
 + x^5 + x^3 + x^2
 + x^3 + x^1 + x^0)
= x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0

If we assume x is base 2 then we get:

x^7 + x^3 + x^2 + x^1 + x^0

Why? Because 3x^3 is 11x^11 (but we need only 1 or 0 pre digit) so we carry over:

=1x^110 + 1x^101 + 1x^100          + 11x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^101 + 1x^100 + 1x^100 + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^101 + 1x^101          + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^110 + 1x^110                   + 1x^11 + 1x^10 + 1x^1 + x^0
=1x^111                            + 1x^11 + 1x^10 + 1x^1 + x^0

But mathematicians changed the rules so that it is mod 2. So basically any binary polynomial mod 2 is just addition without carry or XORs. So our original equation looks like:

=( 1x^110 + 1x^101 + 1x^100 + 11x^11 + 1x^10 + 1x^1 + x^0 ) MOD 2
=( 1x^110 + 1x^101 + 1x^100 +  1x^11 + 1x^10 + 1x^1 + x^0 )
= x^6 + x^5 + x^4 + 3*x^3 + x^2 + x^1 + x^0 (or that original number we had)

I know this is a leap of faith but this is beyond my capability as a line-programmer. If you are a hard-core CS-student or engineer I challenge to break this down. Everyone will benefit from this analysis.

So to work out a full example:

   Original message                : 1101011011
   Polynomial of (W)idth 4         :      10011
   Message after appending W zeros : 11010110110000

Now we divide the augmented Message by the Poly using CRC arithmetic. This is the same division as before:

            1100001010 = Quotient (nobody cares about the quotient)
       _______________
10011 ) 11010110110000 = Augmented message (1101011011 + 0000)
=Poly   10011,,.,,....
        -----,,.,,....
         10011,.,,....
         10011,.,,....
         -----,.,,....
          00001.,,....
          00000.,,....
          -----.,,....
           00010,,....
           00000,,....
           -----,,....
            00101,....
            00000,....
            -----,....
             01011....
             00000....
             -----....
              10110...
              10011...
              -----...
               01010..
               00000..
               -----..
                10100.
                10011.
                -----.
                 01110
                 00000
                 -----
                  1110 = Remainder = THE CHECKSUM!!!!

The division yields a quotient, which we throw away, and a remainder, which is the calculated checksum. This ends the calculation. Usually, the checksum is then appended to the message and the result transmitted. In this case the transmission would be: 11010110111110.

Only use a 32-bit number as your divisor and use your entire stream as your dividend. Throw out the quotient and keep the remainder. Tack the remainder on the end of your message and you have a CRC32.

Average guy review:

         QUOTIENT
        ----------
DIVISOR ) DIVIDEND
                 = REMAINDER
  1. Take the first 32 bits.
  2. Shift bits
  3. If 32 bits are less than DIVISOR, go to step 2.
  4. XOR 32 bits by DIVISOR. Go to step 2.

(Note that the stream has to be dividable by 32 bits or it should be padded. For example, an 8-bit ANSI stream would have to be padded. Also at the end of the stream, the division is halted.)

How to suppress "unused parameter" warnings in C?

With gcc with the unused attribute:

int foo (__attribute__((unused)) int bar) {
    return 0;
}

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

These are identical for printf but different for scanf. For printf, both %d and %i designate a signed decimal integer. For scanf, %d and %i also means a signed integer but %i inteprets the input as a hexadecimal number if preceded by 0x and octal if preceded by 0 and otherwise interprets the input as decimal.

What do \t and \b do?

\t is the tab character, and is doing exactly what you're anticipating based on the action of \b - it goes to the next tab stop, then gets decremented, and then goes to the next tab stop (which is in this case the same tab stop, because of the \b.

Fastest way to zero out a 2d array in C?

Well, the fastest way to do it is to not do it at all.

Sounds odd I know, here's some pseudocode:

int array [][];
bool array_is_empty;


void ClearArray ()
{
   array_is_empty = true;
}

int ReadValue (int x, int y)
{
   return array_is_empty ? 0 : array [x][y];
}

void SetValue (int x, int y, int value)
{
   if (array_is_empty)
   {
      memset (array, 0, number of byte the array uses);
      array_is_empty = false;
   }
   array [x][y] = value;
}

Actually, it's still clearing the array, but only when something is being written to the array. This isn't a big advantage here. However, if the 2D array was implemented using, say, a quad tree (not a dynamic one mind), or a collection of rows of data, then you can localise the effect of the boolean flag, but you'd need more flags. In the quad tree just set the empty flag for the root node, in the array of rows just set the flag for each row.

Which leads to the question "why do you want to repeatedly zero a large 2d array"? What is the array used for? Is there a way to change the code so that the array doesn't need zeroing?

For example, if you had:

clear array
for each set of data
  for each element in data set
    array += element 

that is, use it for an accumulation buffer, then changing it like this would improve the performance no end:

 for set 0 and set 1
   for each element in each set
     array = element1 + element2

 for remaining data sets
   for each element in data set
     array += element 

This doesn't require the array to be cleared but still works. And that will be far faster than clearing the array. Like I said, the fastest way is to not do it in the first place.

How to compile without warnings being treated as errors?

Thanks for all the helpful suggestions. I finally made sure that there are no warnings in my code, but again was getting this warning from sqlite3:

Assuming signed overflow does not occur when assuming that (X - c) <= X is always true

which I fixed by adding the following CFLAG:

-fno-strict-overflow

getch and arrow codes

    void input_from_key_board(int &ri, int &ci)
{
    char ch = 'x';
    if (_kbhit())
    {
        ch = _getch();
        if (ch == -32)
        {
            ch = _getch();
            switch (ch)
            {
            case 72: { ri--; break; }
            case 80: { ri++; break; }
            case 77: { ci++; break; }
            case 75: { ci--; break; }

            }
        }
        else if (ch == '\r'){ gotoRowCol(ri++, ci -= ci); }
        else if (ch == '\t'){ gotoRowCol(ri, ci += 5); }
        else if (ch == 27) { system("ipconfig"); }
        else if (ch == 8){ cout << " "; gotoRowCol(ri, --ci); if (ci <= 0)gotoRowCol(ri--, ci); }
        else { cout << ch; gotoRowCol(ri, ci++); }
        gotoRowCol(ri, ci);
    }
}

Programmatically find the number of cores on a machine

This functionality is part of the C++11 standard.

#include <thread>

unsigned int nthreads = std::thread::hardware_concurrency();

For older compilers, you can use the Boost.Thread library.

#include <boost/thread.hpp>

unsigned int nthreads = boost::thread::hardware_concurrency();

In either case, hardware_concurrency() returns the number of threads that the hardware is capable of executing concurrently based on the number of CPU cores and hyper-threading units.

Finding the length of an integer in C

int get_int_len (int value){
  int l=1;
  while(value>9){ l++; value/=10; }
  return l;
}

and second one will work for negative numbers too:

int get_int_len_with_negative_too (int value){
  int l=!value;
  while(value){ l++; value/=10; }
  return l;
}

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

If you can use a C++ compiler to build the object file that you want to contain your version string, then we can do exactly what you want! The only magic here is that C++ allows you to use expressions to statically initialize an array, while C doesn't. The expressions need to be fully computable at compile time, but these expressions are, so it's no problem.

We build up the version string one byte at a time, and get exactly what we want.

// source file version_num.h

#ifndef VERSION_NUM_H

#define VERSION_NUM_H


#define VERSION_MAJOR 1
#define VERSION_MINOR 4


#endif // VERSION_NUM_H

// source file build_defs.h

#ifndef BUILD_DEFS_H

#define BUILD_DEFS_H


// Example of __DATE__ string: "Jul 27 2012"
//                              01234567890

#define BUILD_YEAR_CH0 (__DATE__[ 7])
#define BUILD_YEAR_CH1 (__DATE__[ 8])
#define BUILD_YEAR_CH2 (__DATE__[ 9])
#define BUILD_YEAR_CH3 (__DATE__[10])


#define BUILD_MONTH_IS_JAN (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_FEB (__DATE__[0] == 'F')
#define BUILD_MONTH_IS_MAR (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
#define BUILD_MONTH_IS_APR (__DATE__[0] == 'A' && __DATE__[1] == 'p')
#define BUILD_MONTH_IS_MAY (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
#define BUILD_MONTH_IS_JUN (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_JUL (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
#define BUILD_MONTH_IS_AUG (__DATE__[0] == 'A' && __DATE__[1] == 'u')
#define BUILD_MONTH_IS_SEP (__DATE__[0] == 'S')
#define BUILD_MONTH_IS_OCT (__DATE__[0] == 'O')
#define BUILD_MONTH_IS_NOV (__DATE__[0] == 'N')
#define BUILD_MONTH_IS_DEC (__DATE__[0] == 'D')


#define BUILD_MONTH_CH0 \
    ((BUILD_MONTH_IS_OCT || BUILD_MONTH_IS_NOV || BUILD_MONTH_IS_DEC) ? '1' : '0')

#define BUILD_MONTH_CH1 \
    ( \
        (BUILD_MONTH_IS_JAN) ? '1' : \
        (BUILD_MONTH_IS_FEB) ? '2' : \
        (BUILD_MONTH_IS_MAR) ? '3' : \
        (BUILD_MONTH_IS_APR) ? '4' : \
        (BUILD_MONTH_IS_MAY) ? '5' : \
        (BUILD_MONTH_IS_JUN) ? '6' : \
        (BUILD_MONTH_IS_JUL) ? '7' : \
        (BUILD_MONTH_IS_AUG) ? '8' : \
        (BUILD_MONTH_IS_SEP) ? '9' : \
        (BUILD_MONTH_IS_OCT) ? '0' : \
        (BUILD_MONTH_IS_NOV) ? '1' : \
        (BUILD_MONTH_IS_DEC) ? '2' : \
        /* error default */    '?' \
    )

#define BUILD_DAY_CH0 ((__DATE__[4] >= '0') ? (__DATE__[4]) : '0')
#define BUILD_DAY_CH1 (__DATE__[ 5])



// Example of __TIME__ string: "21:06:19"
//                              01234567

#define BUILD_HOUR_CH0 (__TIME__[0])
#define BUILD_HOUR_CH1 (__TIME__[1])

#define BUILD_MIN_CH0 (__TIME__[3])
#define BUILD_MIN_CH1 (__TIME__[4])

#define BUILD_SEC_CH0 (__TIME__[6])
#define BUILD_SEC_CH1 (__TIME__[7])


#if VERSION_MAJOR > 100

#define VERSION_MAJOR_INIT \
    ((VERSION_MAJOR / 100) + '0'), \
    (((VERSION_MAJOR % 100) / 10) + '0'), \
    ((VERSION_MAJOR % 10) + '0')

#elif VERSION_MAJOR > 10

#define VERSION_MAJOR_INIT \
    ((VERSION_MAJOR / 10) + '0'), \
    ((VERSION_MAJOR % 10) + '0')

#else

#define VERSION_MAJOR_INIT \
    (VERSION_MAJOR + '0')

#endif

#if VERSION_MINOR > 100

#define VERSION_MINOR_INIT \
    ((VERSION_MINOR / 100) + '0'), \
    (((VERSION_MINOR % 100) / 10) + '0'), \
    ((VERSION_MINOR % 10) + '0')

#elif VERSION_MINOR > 10

#define VERSION_MINOR_INIT \
    ((VERSION_MINOR / 10) + '0'), \
    ((VERSION_MINOR % 10) + '0')

#else

#define VERSION_MINOR_INIT \
    (VERSION_MINOR + '0')

#endif



#endif // BUILD_DEFS_H

// source file main.c

#include "version_num.h"
#include "build_defs.h"

// want something like: 1.4.1432.2234

const unsigned char completeVersion[] =
{
    VERSION_MAJOR_INIT,
    '.',
    VERSION_MINOR_INIT,
    '-', 'V', '-',
    BUILD_YEAR_CH0, BUILD_YEAR_CH1, BUILD_YEAR_CH2, BUILD_YEAR_CH3,
    '-',
    BUILD_MONTH_CH0, BUILD_MONTH_CH1,
    '-',
    BUILD_DAY_CH0, BUILD_DAY_CH1,
    'T',
    BUILD_HOUR_CH0, BUILD_HOUR_CH1,
    ':',
    BUILD_MIN_CH0, BUILD_MIN_CH1,
    ':',
    BUILD_SEC_CH0, BUILD_SEC_CH1,
    '\0'
};


#include <stdio.h>

int main(int argc, char **argv)
{
    printf("%s\n", completeVersion);
    // prints something similar to: 1.4-V-2013-05-09T15:34:49
}

This isn't exactly the format you asked for, but I still don't fully understand how you want days and hours mapped to an integer. I think it's pretty clear how to make this produce any desired string.

How do I make a simple makefile for gcc on Linux?

For example this simple Makefile should be sufficient:

CC=gcc 
CFLAGS=-Wall

all: program
program: program.o
program.o: program.c program.h headers.h

clean:
    rm -f program program.o
run: program
    ./program

Note there must be <tab> on the next line after clean and run, not spaces.

UPDATE Comments below applied

How to pause in C?

Under POSIX systems, the best solution seems to use:

#include <unistd.h>

pause ();

If the process receives a signal whose effect is to terminate it (typically by typing Ctrl+C in the terminal), then pause will not return and the process will effectively be terminated by this signal. A more advanced usage is to use a signal-catching function, called when the corresponding signal is received, after which pause returns, resuming the process.

Note: using getchar() will not work is the standard input is redirected; hence this more general solution.

Fastest method of screen capturing on Windows

In my Impression, the GDI approach and the DX approach are different in its nature. painting using GDI applies the FLUSH method, the FLUSH approach draws the frame then clear it and redraw another frame in the same buffer, this will result in flickering in games require high frame rate.

  1. WHY DX quicker? in DX (or graphics world), a more mature method called double buffer rendering is applied, where two buffers are present, when present the front buffer to the hardware, you can render to the other buffer as well, then after the frame 1 is finished rendering, the system swap to the other buffer( locking it for presenting to hardware , and release the previous buffer ), in this way the rendering inefficiency is greatly improved.
  2. WHY turning down hardware acceleration quicker? although with double buffer rendering, the FPS is improved, but the time for rendering is still limited. modern graphic hardware usually involves a lot of optimization during rendering typically like anti-aliasing, this is very computation intensive, if you don't require that high quality graphics, of course you can just disable this option. and this will save you some time.

I think what you really need is a replay system, which I totally agree with what people discussed.

concatenate char array in C

You can concatenate strings by using the sprintf() function. In your case, for example:

char file[80];
sprintf(file,"%s%s",name,extension);

And you'll end having the concatenated string in "file".

Strings and character with printf

The name of an array is the address of its first element, so name is a pointer to memory containing the string "siva".

Also you don't need a pointer to display a character; you are just electing to use it directly from the array in this case. You could do this instead:

char c = *name;
printf("%c\n", c);

What is a "callback" in C and how are they implemented?

Callbacks in C are usually implemented using function pointers and an associated data pointer. You pass your function on_event() and data pointers to a framework function watch_events() (for example). When an event happens, your function is called with your data and some event-specific data.

Callbacks are also used in GUI programming. The GTK+ tutorial has a nice section on the theory of signals and callbacks.

What are .a and .so files?

Archive libraries (.a) are statically linked i.e when you compile your program with -c option in gcc. So, if there's any change in library, you need to compile and build your code again.

The advantage of .so (shared object) over .a library is that they are linked during the runtime i.e. after creation of your .o file -o option in gcc. So, if there's any change in .so file, you don't need to recompile your main program. But make sure that your main program is linked to the new .so file with ln command.

This will help you to build the .so files. http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html

Hope this helps.

How to generate a random number between 0 and 1?

Here's a general procedure for producing a random number in a specified range:

int randInRange(int min, int max)
{
  return min + (int) (rand() / (double) (RAND_MAX + 1) * (max - min + 1));
}

Depending on the PRNG algorithm being used, the % operator may result in a very non-random sequence of numbers.

Integer to IP Address - C

void ul2chardec(char*pcIP, unsigned long ulIPN){
int i; int k=0; char c0, c1;
for (i = 0; i<4; i++){
    c0 = ((((ulIPN & (0xff << ((3 - i) * 8))) >> ((3 - i) * 8))) / 100) + 0x30;
    if (c0 != '0'){ *(pcIP + k) = c0; k++; }
    c1 = (((((ulIPN & (0xff << ((3 - i) * 8))) >> ((3 - i) * 8))) % 100) / 10) + 0x30;
    if (!(c1 =='0' && c0=='0')){ *(pcIP + k) = c1; k++; }
    *(pcIP +k) = (((((ulIPN & (0xff << ((3 - i) * 8)))) >> ((3 - i) * 8))) % 10) + 0x30;
    k++;
    if (i<3){ *(pcIP + k) = '.'; k++;}
}
*(pcIP + k) = 0; // pcIP should be x10 bytes

}

Openssl : error "self signed certificate in certificate chain"

If you're running Charles and trying to build a container then you'll most likely get this error.

Make sure to disable Charles (macos) proxy under proxy -> macOS proxy

Charles is an

HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet.

So anything similar may cause the same issue.

How to concatenate string and int in C?

Strings are hard work in C.

#include <stdio.h>

int main()
{
   int i;
   char buf[12];

   for (i = 0; i < 100; i++) {
      snprintf(buf, 12, "pre_%d_suff", i); // puts string into buffer
      printf("%s\n", buf); // outputs so you can see it
   }
}

The 12 is enough bytes to store the text "pre_", the text "_suff", a string of up to two characters ("99") and the NULL terminator that goes on the end of C string buffers.

This will tell you how to use snprintf, but I suggest a good C book!

max value of integer

That's because in C - integer on 32 bit machine doesn't mean that 32 bits are used for storing it, it may be 16 bits as well. It depends on the machine (implementation-dependent).

What is the proper #include for the function 'sleep()'?

this is what I use for a cross-platform code:

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

int main()
{
  pollingDelay = 100
  //do stuff

  //sleep:
  #ifdef _WIN32
  Sleep(pollingDelay);
  #else
  usleep(pollingDelay*1000);  /* sleep for 100 milliSeconds */
  #endif

  //do stuff again
  return 0;
}

How to calculate the CPU usage of a process by PID in Linux from C?

Use strace found the CPU usage need to be calculated by a time period:

# top -b -n 1 -p 3889
top - 16:46:37 up  1:04,  3 users,  load average: 0.00, 0.01, 0.02
Tasks:   1 total,   0 running,   1 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.0 us,  0.0 sy,  0.0 ni,100.0 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem :  5594496 total,  5158284 free,   232132 used,   204080 buff/cache
KiB Swap:  3309564 total,  3309564 free,        0 used.  5113756 avail Mem 

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
 3889 root      20   0  162016   2220   1544 S   0.0  0.0   0:05.77 top
# strace top -b -n 1 -p 3889
.
.
.
stat("/proc/3889", {st_mode=S_IFDIR|0555, st_size=0, ...}) = 0
open("/proc/3889/stat", O_RDONLY)       = 7
read(7, "3889 (top) S 3854 3889 3854 3481"..., 1024) = 342
.
.
.

nanosleep({0, 150000000}, NULL)         = 0
.
.
.
stat("/proc/3889", {st_mode=S_IFDIR|0555, st_size=0, ...}) = 0
open("/proc/3889/stat", O_RDONLY)       = 7
read(7, "3889 (top) S 3854 3889 3854 3481"..., 1024) = 342
.
.
.

typeof operator in C

It is a C extension from the GCC compiler , see http://gcc.gnu.org/onlinedocs/gcc/Typeof.html

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.

Reversing a string in C

That's a good question ant2009. You can use a standalone function to reverse the string. The code is...

#include <stdio.h>
#define MAX_CHARACTERS 99

int main( void );
int strlen( char __str );

int main() {
    char *str[ MAX_CHARACTERS ];
    char *new_string[ MAX_CHARACTERS ];
    int i, j;

    printf( "enter string: " );
    gets( *str );

    for( i = 0; j = ( strlen( *str ) - 1 ); i < strlen( *str ), j > -1; i++, j-- ) {
        *str[ i ] = *new_string[ j ];
    }
    printf( "Reverse string is: %s", *new_string" );
    return ( 0 );
}

int strlen( char __str[] ) {
    int count;
    for( int i = 0; __str[ i ] != '\0'; i++ ) {
         ++count;
    }
    return ( count );
}

Converting an integer to binary in C

Result in string

The following function converts an integer to binary in a string (n is the number of bits):

// Convert an integer to binary (in a string)
void int2bin(unsigned integer, char* binary, int n=8)
{  
  for (int i=0;i<n;i++)   
    binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
  binary[n]='\0';
}

Test online on repl.it.

Source : AnsWiki.

Result in string with memory allocation

The following function converts an integer to binary in a string and allocate memory for the string (n is the number of bits):

// Convert an integer to binary (in a string)
char* int2bin(unsigned integer, int n=8)
{
  char* binary = (char*)malloc(n+1);
  for (int i=0;i<n;i++)   
    binary[i] = (integer & (int)1<<(n-i-1)) ? '1' : '0';
  binary[n]='\0';
  return binary;
}

This option allows you to write something like printf ("%s", int2bin(78)); but be careful, memory allocated for the string must be free later.

Test online on repl.it.

Source : AnsWiki.

Result in unsigned int

The following function converts an integer to binary in another integer (8 bits maximum):

// Convert an integer to binary (in an unsigned)
unsigned int int_to_int(unsigned int k) {
    return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}

Test online on repl.it

Display result

The following function displays the binary conversion

// Convert an integer to binary and display the result
void int2bin(unsigned integer, int n=8)
{  
  for (int i=0;i<n;i++)   
    putchar ( (integer & (int)1<<(n-i-1)) ? '1' : '0' );
}

Test online on repl.it.

Source : AnsWiki.

Finding length of char array

If anyone is looking for a quick fix for this, here's how you do it.

while (array[i] != '\0') i++;

The variable i will hold the used length of the array, not the entire initialized array. I know it's a late post, but it may help someone.

Is there a standard sign function (signum, sgn) in C/C++?

int sign(float n)
{     
  union { float f; std::uint32_t i; } u { n };
  return 1 - ((u.i >> 31) << 1);
}

This function assumes:

  • binary32 representation of floating point numbers
  • a compiler that make an exception about the strict aliasing rule when using a named union

How can I convert an integer to a hexadecimal string in C?

To convert an integer to a string also involves char array or memory management.

To handle that part for such short arrays, code could use a compound literal, since C99, to create array space, on the fly. The string is valid until the end of the block.

#define UNS_HEX_STR_SIZE ((sizeof (unsigned)*CHAR_BIT + 3)/4 + 1)
//                         compound literal v--------------------------v
#define U2HS(x) unsigned_to_hex_string((x), (char[UNS_HEX_STR_SIZE]) {0}, UNS_HEX_STR_SIZE)

char *unsigned_to_hex_string(unsigned x, char *dest, size_t size) {
  snprintf(dest, size, "%X", x);
  return dest;
}

int main(void) {
  // 3 array are formed v               v        v
  printf("%s %s %s\n", U2HS(UINT_MAX), U2HS(0), U2HS(0x12345678));
  char *hs = U2HS(rand());
  puts(hs);
  // `hs` is valid until the end of the block
}

Output

FFFFFFFF 0 12345678
5851F42D

How do I lowercase a string in C?

If we're going to be as sloppy as to use tolower(), do this:

char blah[] = "blah blah Blah BLAH blAH\0"; int i=0; while(blah[i]|=' ', blah[++i]) {}

But, well, it kinda explodes if you feed it some symbols/numerals, and in general it's evil. Good interview question, though.

Print the address or pointer for value in C

I believe this would be most correct.

printf("%p", (void *)emp1);
printf("%p", (void *)*emp1);

printf() is a variadic function and must be passed arguments of the right types. The standard says %p takes void *.

How can I get the nth character of a string?

You would do:

char c = str[1];

Or even:

char c = "Hello"[1];

edit: updated to find the "E".

How do I print the percent sign(%) in c

Your problem is that you have to change:

printf("%"); 

to

printf("%%");

Or you could use ASCII code and write:

printf("%c", 37);

:)

Using Cygwin to Compile a C program; Execution error

You might be better off editing a file inside of cygwin shell. Normally it has default user directory when you start it up. You can edit a file from the shell doing something like "vi somefile.c" or "emacs somefile.c". That's assuming vi or emacs are installed in cygwin.

If you want to file on your desktop, you'll have to go to a path similar (on XP) to "/cygwindrive/c/Documents\ and\ Settings/Frank/Desktop" (If memory serves correctly). Just cd to that path, and run your command on the file.

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__PRETTY_FUNCTION__ handles C++ features: classes, namespaces, templates and overload

main.cpp

#include <iostream>

namespace N {
    class C {
        public:
            template <class T>
            static void f(int i) {
                (void)i;
                std::cout << "__func__            " << __func__ << std::endl
                          << "__FUNCTION__        " << __FUNCTION__ << std::endl
                          << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
            }
            template <class T>
            static void f(double f) {
                (void)f;
                std::cout << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
            }
    };
}

int main() {
    N::C::f<char>(1);
    N::C::f<void>(1.0);
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

Output:

__func__            f
__FUNCTION__        f
__PRETTY_FUNCTION__ static void N::C::f(int) [with T = char]
__PRETTY_FUNCTION__ static void N::C::f(double) [with T = void]

You may also be interested in stack traces with function names: print call stack in C or C++

Tested in Ubuntu 19.04, GCC 8.3.0.

C++20 std::source_location::function_name

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf went into C++20, so we have yet another way to do it.

The documentation says:

constexpr const char* function_name() const noexcept;

6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.

where NTBS means "Null Terminated Byte String".

I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:

#include <iostream>
#include <string_view>
#include <source_location>
 
void log(std::string_view message,
         const std::source_location& location std::source_location::current()
) {
    std::cout << "info:"
              << location.file_name() << ":"
              << location.line() << ":"
              << location.function_name() << " "
              << message << '\n';
}
 
int main() {
    log("Hello world!");
}

Possible output:

info:main.cpp:16:main Hello world!

so note how this returns the caller information, and is therefore perfect for usage in logging, see also: Is there a way to get function name inside a C++ function?

Why would anybody use C over C++?

Fears of performance or bloat are not good reason to forgo C++. Every language has its potential pitfalls and trade offs - good programmers learn about these and where necessary develop coping strategies, poor programmers will fall foul and blame the language.

Interpreted Python is in many ways considered to be a "slow" language, but for non-trivial tasks a skilled Python programmer can easily produce code that executes faster than that of an inexperienced C developer.

In my industry, video games, we write high performance code in C++ by avoiding things such as RTTI, exceptions, or virtual-functions in inner loops. These can be extremely useful but have performance or bloat problems that it's desirable to avoid. If we were to go a step further and switch entirely to C we would gain little and lose the most useful constructs of C++.

The biggest practical reason for preferring C is that support is more widespread than C++. There are many platforms, particularly embedded ones, that do not even have C++ compilers.

There is also the matter of compatibility for vendors. While C has a stable and well-defined ABI (Application Binary Interface) C++ does not. The ABI in C++ is more complicated due to such things as vtables and constructurs/destructors so is implemented differently with every vendor, and even versions of a vendors toolchain.

In real-terms this means you cannot take a library generated by one compiler and link it with code or a library from another which creates a nightmare for distributed projects or middleware providers of binary libraries.

CMake unable to determine linker language with C++

In my case, it was just because there were no source file in the target. All of my library was template with source code in the header. Adding an empty file.cpp solved the problem.

What is the meaning of Bus: error 10 in C

this is because str is pointing to a string literal means a constant string ...but you are trying to modify it by copying . Note : if it would have been an error due to memory allocation it would have been given segmentation fault at the run time .But this error is coming due to constant string modification or you can go through the below for more details abt bus error :

Bus errors are rare nowadays on x86 and occur when your processor cannot even attempt the memory access requested, typically:

  • using a processor instruction with an address that does not satisfy its alignment requirements.

Segmentation faults occur when accessing memory which does not belong to your process, they are very common and are typically the result of:

  • using a pointer to something that was deallocated.
  • using an uninitialized hence bogus pointer.
  • using a null pointer.
  • overflowing a buffer.

To be more precise this is not manipulating the pointer itself that will cause issues, it's accessing the memory it points to (dereferencing).

Is there Java HashMap equivalent in PHP?

Arrays in PHP can have Key Value structure.

remote rejected master -> master (pre-receive hook declined)

Make sure that your Rails app is in the root of the repo, the Gemfile is present and properly named. It is basically not able to detect your code base as one of the supported project types and hence failing it. Also, even if you do have a proper project, make sure it is part of the repository and you have committed it fine (git status will help you here and a ls should help you verify the project structure).

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

Instead of passing reference object passed the saved object, below is explanation which solve my issue:

//wrong
entityManager.persist(role);
user.setRole(role);
entityManager.persist(user)

//right
Role savedEntity= entityManager.persist(role);
user.setRole(savedEntity);
entityManager.persist(user)

No provider for HttpClient

I found slimier problem. Please import the HttpClientModule in your app.module.ts file as follow:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
],

imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

Java Byte Array to String to Byte Array

String coolString = "cool string";

byte[] byteArray = coolString.getBytes();

String reconstitutedString = new String(byteArray);

System.out.println(reconstitutedString);

That outputs "cool string" to the console.

It's pretty darn easy.

Response to preflight request doesn't pass access control check

It's easy to solve this issue just with few steps easily,without worrying about anything. Kindly,Follow the steps to solve it .

  1. open (https://www.npmjs.com/package/cors#enabling-cors-pre-flight)
  2. go to installation and copy the command npm install cors to install via node terminal
  3. go to Simple Usage (Enable All CORS Requests) by scrolling.then copy and paste the complete declartion in ur project and run it...that will work for sure.. copy the comment code and paste in ur app.js or any other project and give a try ..this will work.this will unlock every cross origin resource sharing..so we can switch between serves for your use

How do I break out of a loop in Scala?

Here is a tail recursive version. Compared to the for-comprehensions it is a bit cryptic, admittedly, but I'd say its functional :)

def run(start:Int) = {
  @tailrec
  def tr(i:Int, largest:Int):Int = tr1(i, i, largest) match {
    case x if i > 1 => tr(i-1, x)
    case _ => largest
  }

  @tailrec
  def tr1(i:Int,j:Int, largest:Int):Int = i*j match {
    case x if x < largest || j < 2 => largest
    case x if x.toString.equals(x.toString.reverse) => tr1(i, j-1, x)
    case _ => tr1(i, j-1, largest)
  }

  tr(start, 0)
}

As you can see, the tr function is the counterpart of the outer for-comprehensions, and tr1 of the inner one. You're welcome if you know a way to optimize my version.

Using json_encode on objects in PHP (regardless of scope)

In RedBeanPHP 2.0 there is a mass-export function which turns an entire collection of beans into arrays. This works with the JSON encoder..

json_encode( R::exportAll( $beans ) );

Codesign error: Provisioning profile cannot be found after deleting expired profile

One suggestion I'll make since no one yet has said it: PLEASE PLEASE PLEASE make a backup of your whole .xcodeproj file BEFORE you start modifying it's contents. Screwing up the project file and having no backup will lead to a very very unpleasant experience.

Being able to back out of an edit can be a godsend.

How to use orderby with 2 fields in linq?

MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

Note that you can use as well the Descending keyword in the OrderBy (in case you need). So another possible answer is:

MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate);

Programmatically set image to UIImageView with Xcode 6.1/Swift

This code is in the wrong place:

var image : UIImage = UIImage(named:"afternoon")!
bgImage = UIImageView(image: image)
bgImage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(bgImage)

You must place it inside a function. I recommend moving it inside the viewDidLoad function.

In general, the only code you can add within the class that's not inside of a function are variable declarations like:

@IBOutlet weak var bgImage: UIImageView!

Calculate time difference in Windows batch file

Based on previous answers, here are reusable "procedures" and a usage example for calculating the elapsed time:

@echo off
setlocal

set starttime=%TIME%
echo Start Time: %starttime%

REM ---------------------------------------------
REM --- PUT THE CODE YOU WANT TO MEASURE HERE ---
REM ---------------------------------------------

set endtime=%TIME%
echo End Time: %endtime%
call :elapsed_time %starttime% %endtime% duration
echo Duration: %duration%

endlocal
echo on & goto :eof

REM --- HELPER PROCEDURES ---

:time_to_centiseconds
:: %~1 - time
:: %~2 - centiseconds output variable
setlocal
set _time=%~1
for /F "tokens=1-4 delims=:.," %%a in ("%_time%") do (
   set /A "_result=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
endlocal & set %~2=%_result%
goto :eof

:centiseconds_to_time
:: %~1 - centiseconds
:: %~2 - time output variable
setlocal
set _centiseconds=%~1
rem now break the centiseconds down to hors, minutes, seconds and the remaining centiseconds
set /A _h=%_centiseconds% / 360000
set /A _m=(%_centiseconds% - %_h%*360000) / 6000
set /A _s=(%_centiseconds% - %_h%*360000 - %_m%*6000) / 100
set /A _hs=(%_centiseconds% - %_h%*360000 - %_m%*6000 - %_s%*100)
rem some formatting
if %_h% LSS 10 set _h=0%_h%
if %_m% LSS 10 set _m=0%_m%
if %_s% LSS 10 set _s=0%_s%
if %_hs% LSS 10 set _hs=0%_hs%
set _result=%_h%:%_m%:%_s%.%_hs%
endlocal & set %~2=%_result%
goto :eof

:elapsed_time
:: %~1 - time1 - start time
:: %~2 - time2 - end time
:: %~3 - elapsed time output
setlocal
set _time1=%~1
set _time2=%~2
call :time_to_centiseconds %_time1% _centi1
call :time_to_centiseconds %_time2% _centi2
set /A _duration=%_centi2%-%_centi1%
call :centiseconds_to_time %_duration% _result
endlocal & set %~3=%_result%
goto :eof

How to test if a string is basically an integer in quotes using Ruby

Personally I like the exception approach although I would make it a little more terse:

class String
  def integer?(str)
    !!Integer(str) rescue false
  end
end

However, as others have already stated, this doesn't work with Octal strings.

Convert data file to blob

A file object is an instance of Blob but a blob object is not an instance of File

new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true

new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false

new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false

If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
    let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
    console.log(blob);
};
reader.readAsArrayBuffer(file);

As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];

file.arrayBuffer().then((arrayBuffer) => {
    let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
    console.log(blob);
});

If your environment supports async/await you can use a one-liner like below

let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));

Java switch statement: Constant expression required, but it IS constant

Got this error in Android while doing something like this:

 roleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            switch (parent.getItemAtPosition(position)) {
                case ADMIN_CONSTANT: //Threw the error

            }

despite declaring a constant:

public static final String ADMIN_CONSTANT= "Admin";

I resolved the issue by changing my code to this:

roleSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            String selectedItem = String.valueOf(parent.getItemAtPosition(position));
            switch (selectedItem) {
                case ADMIN_CONSTANT:

            }

What are the alternatives now that the Google web search API has been deprecated?

Here is an option at the bottom of the Custom Search Control Panel: "Sites to search", you can choose "Search the entire web but emphasize included sites"

Custom Search Control Panel - Sites to search

Change the column label? e.g.: change column "A" to column "Name"

I would like to present another answer to this as the currently accepted answer doesn't work for me (I use LibreOffice). This solution should work in Excel, LibreOffice and OpenOffice:

First, insert a new row at the beginning of the sheet. Within that row, define the names you need: new row

Then, in the menu bar, go to View -> Freeze Cells -> Freeze First Row. It'll look like this now: new top row

Now whenever you scroll down in the document, the first row will be "pinned" to the top: new behaviour

Box shadow in IE7 and IE8

in ie8 you can try

-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0')";
 filter: progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0');

caveat: in ie8 you loose smooth fonts for some reason, they will look ragged

Can't bind to 'formGroup' since it isn't a known property of 'form'

This problem occurs due to missing import of FormsModule,ReactiveFormsModule .I also came with same problem. My case was diff. as i was working with modules.So i missed above imports in my parent modules though i had imported it into child modules,it wasn't working.

Then i imported it into my parent modules as below, and it worked!

import { ReactiveFormsModule,FormsModule  } from '@angular/forms';
import { AlertModule } from 'ngx-bootstrap';

         @NgModule({
          imports: [
            CommonModule,
            FormsModule,
            ReactiveFormsModule,
    ],
      declarations: [MyComponent]
    })

XMLHttpRequest module not defined/found

With the xhr2 library you can globally overwrite XMLHttpRequest from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.

global.XMLHttpRequest = require('xhr2');

Getting list of tables, and fields in each, in a database

This will return the database name, table name, column name and the datatype of the column specified by a database parameter:

declare @database nvarchar(25)
set @database = ''

SELECT cu.table_catalog,cu.VIEW_SCHEMA, cu.VIEW_NAME, cu.TABLE_NAME,   
cu.COLUMN_NAME,c.DATA_TYPE,c.character_maximum_length
from INFORMATION_SCHEMA.VIEW_COLUMN_USAGE as cu
JOIN INFORMATION_SCHEMA.COLUMNS as c
on cu.TABLE_SCHEMA = c.TABLE_SCHEMA and c.TABLE_CATALOG = 
cu.TABLE_CATALOG
and c.TABLE_NAME = cu.TABLE_NAME
and c.COLUMN_NAME = cu.COLUMN_NAME
where cu.TABLE_CATALOG = @database
order by cu.view_name,c.COLUMN_NAME

How to sort an STL vector?

Like explained in other answers you need to provide a comparison function. If you would like to keep the definition of that function close to the sort call (e.g. if it only makes sense for this sort) you can define it right there with boost::lambda. Use boost::lambda::bind to call the member function.

To e.g. sort by member variable or function data1:

#include <algorithm>
#include <vector>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
using boost::lambda::bind;
using boost::lambda::_1;
using boost::lambda::_2;

std::vector<myclass> object(10000);
std::sort(object.begin(), object.end(),
    bind(&myclass::data1, _1) < bind(&myclass::data1, _2));

Javascript Get Values from Multiple Select Option Box

Here i am posting the answer just for reference which may become useful.

<!DOCTYPE html>
<html>
<head>
<script>
function show()
{
     var InvForm = document.forms.form;
     var SelBranchVal = "";
     var x = 0;
     for (x=0;x<InvForm.kb.length;x++)
         {
            if(InvForm.kb[x].selected)
            {
             //alert(InvForm.kb[x].value);
             SelBranchVal = InvForm.kb[x].value + "," + SelBranchVal ;
            }
         }
         alert(SelBranchVal);
}
</script>
</head>
<body>
<form name="form">
<select name="kb" id="kb" onclick="show();" multiple>
<option value="India">India</option>
<option selected="selected" value="US">US</option>
<option value="UK">UK</option>
<option value="Japan">Japan</option>
</select>
<!--input type="submit" name="cmdShow" value="Customize Fields"
 onclick="show();" id="cmdShow" /-->
</form>
</body>
</html>

How to add results of two select commands in same query

If you want to make multiple operation use

select (sel1.s1+sel2+s2)

(select sum(hours) s1 from resource) sel1
join 
(select sum(hours) s2 from projects-time)sel2
on sel1.s1=sel2.s2

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

try using a different valid login using RUNAS command

runas /user:domain\user “C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\ssmsee.exe” 

runas /user:domain\user “C:\WINDOWS\system32\mmc.exe /s \”C:\Program Files\Microsoft SQL Server\80\Tools\BINN\SQL Server Enterprise Manager.MSC\”" 

runas /user:domain\user isqlw 

How do I generate a SALT in Java for Salted-Hash?

You were right regarding how you want to generate salt i.e. its nothing but a random number. For this particular case it would protect your system from possible Dictionary attacks. Now, for the second problem what you could do is instead of using UTF-8 encoding you may want to use Base64. Here, is a sample for generating a hash. I am using Apache Common Codecs for doing the base64 encoding you may select one of your own

public byte[] generateSalt() {
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[20];
        random.nextBytes(bytes);
        return bytes;
    }

public String bytetoString(byte[] input) {
        return org.apache.commons.codec.binary.Base64.encodeBase64String(input);
    }

public byte[] getHashWithSalt(String input, HashingTechqniue technique, byte[] salt) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance(technique.value);
        digest.reset();
        digest.update(salt);
        byte[] hashedBytes = digest.digest(stringToByte(input));
        return hashedBytes;
    }
public byte[] stringToByte(String input) {
        if (Base64.isBase64(input)) {
            return Base64.decodeBase64(input);

        } else {
            return Base64.encodeBase64(input.getBytes());
        }
    }

Here is some additional reference of the standard practice in password hashing directly from OWASP

C++ Singleton design pattern

Here is my view on how to do proper singletons (and other non-trivial static objects): https://github.com/alex4747-pub/proper_singleton

Summary:

  1. Use static initialization list to instantiate singletons at the right time: after entering main and before enabling multi-threading
  2. Add minor improvements to make it unit-test friendly.

Where is SQL Profiler in my SQL Server 2008?

Also ensure that "client tools" are selected in the install options. However if SQL Managment Studio 2008 exists then it is likely that you installed the express edition.

Show just the current branch in Git

With Git 2.22 (Q2 2019), you will have a simpler approach: git branch --show-current.

See commit 0ecb1fc (25 Oct 2018) by Daniels Umanovskis (umanovskis).
(Merged by Junio C Hamano -- gitster -- in commit 3710f60, 07 Mar 2019)

branch: introduce --show-current display option

When called with --show-current, git branch will print the current branch name and terminate.
Only the actual name gets printed, without refs/heads.
In detached HEAD state, nothing is output.

Intended both for scripting and interactive/informative use.
Unlike git branch --list, no filtering is needed to just get the branch name.

See the original discussion on the Git mailing list in Oct. 2018, and the actual pathc.

javascript pushing element at the beginning of an array

Use unshift, which modifies the existing array by adding the arguments to the beginning:

TheArray.unshift(TheNewObject);

Unordered List (<ul>) default indent

Most html tags have some default properties. A css reset will help you change the default properties.

What I usually do is:

{ padding: 0; margin: 0; font-face:Arial; }

Although the font is up to you!

Mvn install or Mvn package

The proper way is mvn package if you did things correctly for the core part of your build then there should be no need to install your packages in the local repository.

In addition if you use Travis you can "cache" your dependencies because it will not touch your $HOME.m2/repository if you use package for your own project.

In practicality if you even attempt to do a mvn site you usually need to do a mvn install before. There's just too many bugs with either site or it's numerous poorly maintained plugins.

Changing cursor to waiting in javascript/jquery

The following is my preferred way, and will change the cursor everytime a page is about to change i.e. beforeunload

$(window).on('beforeunload', function(){
   $('*').css("cursor", "progress");
});

How can I permanently enable line numbers in IntelliJ?

Ok in intelliJ 14 Ultimate using the Mac version this is it.

IntelliJ Idea > Preferences > Editor > General > Appearance > Show Line Numbers

List vs tuple, when to use each?

There's a strong culture of tuples being for heterogeneous collections, similar to what you'd use structs for in C, and lists being for homogeneous collections, similar to what you'd use arrays for. But I've never quite squared this with the mutability issue mentioned in the other answers. Mutability has teeth to it (you actually can't change a tuple), while homogeneity is not enforced, and so seems to be a much less interesting distinction.

How to sort an array of integers correctly

sort_mixed

Object.defineProperty(Array.prototype,"sort_mixed",{
    value: function () { // do not use arrow function
        var N = [], L = [];
        this.forEach(e => {
            Number.isFinite(e) ? N.push(e) : L.push(e);
        });
        N.sort((a, b) => a - b);
        L.sort();
        [...N, ...L].forEach((v, i) => this[i] = v);
        return this;
    })

try a =[1,'u',"V",10,4,"c","A"].sort_mixed(); console.log(a)

How can I upgrade specific packages using pip and a requirements file?

Defining a specific version to upgrade helped me instead of only the upgrade command.

pip3 install larapy-installer==0.4.01 -U

How to get Current Directory?

Please don't forget to initialize your buffers to something before utilizing them. And just as important, give your string buffers space for the ending null

TCHAR path[MAX_PATH+1] = L"";
DWORD len = GetCurrentDirectory(MAX_PATH, path);

Reference

How to specify HTTP error code?

I tried

res.status(400);
res.send('message');

..but it was giving me error:

(node:208) UnhandledPromiseRejectionWarning: Error: Can't set headers after they are sent.

This work for me

res.status(400).send(yourMessage);

CSS file not refreshing in browser

Do Shift+F5 in Windows. The cache really frustrates in this kind of stuff

How to resolve symbolic links in a shell script

This is a symlink resolver in Bash that works whether the link is a directory or a non-directory:

function readlinks {(
  set -o errexit -o nounset
  declare n=0 limit=1024 link="$1"

  # If it's a directory, just skip all this.
  if cd "$link" 2>/dev/null
  then
    pwd -P
    return 0
  fi

  # Resolve until we are out of links (or recurse too deep).
  while [[ -L $link ]] && [[ $n -lt $limit ]]
  do
    cd "$(dirname -- "$link")"
    n=$((n + 1))
    link="$(readlink -- "${link##*/}")"
  done
  cd "$(dirname -- "$link")"

  if [[ $n -ge $limit ]]
  then
    echo "Recursion limit ($limit) exceeded." >&2
    return 2
  fi

  printf '%s/%s\n' "$(pwd -P)" "${link##*/}"
)}

Note that all the cd and set stuff takes place in a subshell.

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Is embedding background image data into CSS as Base64 good or bad practice?

Base64 adds about 10% to the image size after GZipped but that outweighs the benefits when it comes to mobile. Since there is a overall trend with responsive web design, it is highly recommended.

W3C also recommends this approach for mobile and if you use asset pipeline in rails, this is a default feature when compressing your css

http://www.w3.org/TR/mwabp/#bp-conserve-css-images

Initializing IEnumerable<string> In C#

You cannot instantiate an interface - you must provide a concrete implementation of IEnumerable.

Referencing another schema in Mongoose

Late reply, but adding that Mongoose also has the concept of Subdocuments

With this syntax, you should be able to reference your userSchema as a type in your postSchema like so:

var userSchema = new Schema({
    twittername: String,
    twitterID: Number,
    displayName: String,
    profilePic: String,
});

var postSchema = new Schema({
    name: String,
    postedBy: userSchema,
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

Note the updated postedBy field with type userSchema.

This will embed the user object within the post, saving an extra lookup required by using a reference. Sometimes this could be preferable, other times the ref/populate route might be the way to go. Depends on what your application is doing.

Text that shows an underline on hover

Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!

HTML

<span class="menu">Menu</span>

SCSS

.menu {
    position: relative;
    text-decoration: none;
    font-weight: 400;
    color: blue;
    transition: all .35s ease;

    &::before {
        content: "";
        position: absolute;
        width: 100%;
        height: 2px;
        bottom: 0;
        left: 0;
        background-color: yellow;
        visibility: hidden;
        -webkit-transform: scaleX(0);
        transform: scaleX(0);
        -webkit-transition: all 0.3s ease-in-out 0s;
        transition: all 0.3s ease-in-out 0s;
    }

    &:hover {
        color: yellow;

        &::before {
            visibility: visible;
            -webkit-transform: scaleX(1);
            transform: scaleX(1);
        }
    }
}

Accessing Google Account Id /username via Android

This Method to get Google Username:

 public String getUsername() {
    AccountManager manager = AccountManager.get(this);
    Account[] accounts = manager.getAccountsByType("com.google");
    List<String> possibleEmails = new LinkedList<String>();

    for (Account account : accounts) {
        // TODO: Check possibleEmail against an email regex or treat
        // account.name as an email address only for certain account.type
        // values.
        possibleEmails.add(account.name);
    }

    if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
        String email = possibleEmails.get(0);
        String[] parts = email.split("@");
        if (parts.length > 0 && parts[0] != null)
            return parts[0];
        else
            return null;
    } else
        return null;
}

simple this method call ....

And Get Google User in Gmail id::

 accounts = AccountManager.get(this).getAccounts();
    Log.e("", "Size: " + accounts.length);
    for (Account account : accounts) {

        String possibleEmail = account.name;
        String type = account.type;

        if (type.equals("com.google")) {
            strGmail = possibleEmail;

            Log.e("", "Emails: " + strGmail);
            break;
        }
    }

After add permission in manifest;

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<uses-permission android:name="android.permission.GET_ACCOUNTS" />

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

I had a similar situation on Mac, and the following process worked for me:

In the terminal, type

vi ~/.profile

Then add this line in the file, and save

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk<version>.jdk/Contents/Home

where version is the one on your computer, such as 1.7.0_25.

Exit the editor, then type the following command make it become effective

source ~/.profile 

Then type java -version to check the result

java -version 

What is .profile file?

.profile file is a hidden file. It is an optional file which tells the system which commands to run when the user whose profile file it is logs in. For example, if my username is bruno and there is a .profile file in /Users/bruno/, all of its contents will be executed during the log-in procedure.

Source: http://computers.tutsplus.com/tutorials/speed-up-your-terminal-workflow-with-command-aliases-and-profile--mac-30515

Generating all permutations of a given string

A very basic solution in Java is to use recursion + Set ( to avoid repetitions ) if you want to store and return the solution strings :

public static Set<String> generatePerm(String input)
{
    Set<String> set = new HashSet<String>();
    if (input == "")
        return set;

    Character a = input.charAt(0);

    if (input.length() > 1)
    {
        input = input.substring(1);

        Set<String> permSet = generatePerm(input);

        for (String x : permSet)
        {
            for (int i = 0; i <= x.length(); i++)
            {
                set.add(x.substring(0, i) + a + x.substring(i));
            }
        }
    }
    else
    {
        set.add(a + "");
    }
    return set;
}

scp from remote host to local host

You need the ip of the other pc and do:

scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop

it will ask you for 'user's password on the other pc.

Compiling C++11 with g++

You can refer to following link for which features are supported in particular version of compiler. It has an exhaustive list of feature support in compiler. Looks GCC follows standard closely and implements before any other compiler.

Regarding your question you can compile using

  1. g++ -std=c++11 for C++11
  2. g++ -std=c++14 for C++14
  3. g++ -std=c++17 for C++17
  4. g++ -std=c++2a for C++20, although all features of C++20 are not yet supported refer this link for feature support list in GCC.

The list changes pretty fast, keep an eye on the list, if you are waiting for particular feature to be supported.

What's the fastest way to delete a large folder in Windows?

Using Windows Command Prompt:

rmdir /s /q folder

Using Powershell:

powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"

Note that in more cases del and rmdir wil leave you with leftover files, where Powershell manages to delete the files.

Mailto on submit button

What you need to do is use the onchange event listener in the form and change the href attribute of the send button according to the context of the mail:

<form id="form" onchange="mail(this)">
  <label>Name</label>
  <div class="row margin-bottom-20">
    <div class="col-md-6 col-md-offset-0">
      <input class="form-control" name="name" type="text">
    </div>
  </div>

  <label>Email <span class="color-red">*</span></label>
  <div class="row margin-bottom-20">
    <div class="col-md-6 col-md-offset-0">
      <input class="form-control" name="email" type="text">
    </div>
  </div>

  <label>Date of visit/departure </label>
  <div class="row margin-bottom-20">
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control w8em" name="adate" type="text">
      <script>
        datePickerController.createDatePicker({
          // Associate the text input to a DD/MM/YYYY date format
          formElements: {
            "adate": "%d/%m/%Y"
          }
        });
      </script>
    </div>
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" name="ddate" type="date">
    </div>
  </div>

  <label>No. of people travelling with</label>
  <div class="row margin-bottom-20">
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" placeholder="Adults" min=1 name="adult" type="number">
    </div>
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" placeholder="Children" min=0 name="childeren" type="number">
    </div>
  </div>

  <label>Cities you want to visit</label><br />
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Cassablanca">Cassablanca</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Fez">Fez</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Tangier">Tangier</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Marrakech">Marrakech</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Rabat">Rabat</label>
  </div>

  <div class="row margin-bottom-20">
    <div class="col-md-8 col-md-offset-0">
      <textarea rows="4" placeholder="Activities Intersted in" name="activities" class="form-control"></textarea>
    </div>
  </div>


  <div class="row margin-bottom-20">
    <div class="col-md-8 col-md-offset-0">
      <textarea rows="6" class="form-control" name="comment" placeholder="Comment"></textarea>
    </div>
  </div>

  <p><a id="send" class="btn btn-primary">Create Message</a></p>
</form>

JavaScript

function mail(form) {
    var name = form.name.value;
    var city = "";
    var adate = form.adate.value;
    var ddate = form.ddate.value;
    var activities = form.activities.value;
    var adult = form.adult.value;
    var child = form.childeren.value;
    var comment = form.comment.value;
    var warning = ""
    for (i = 0; i < form.city.length; i++) {
        if (form.city[i].checked)
            city += " " + form.city[i].value;
    }
    var str = "mailto:[email protected]?subject=travel to morocco&body=";
    if (name.length > 0) {
        str += "Hi my name is " + name + ", ";
    } else {
        warning += "Name is required"
    }
    if (city.length > 0) {
        str += "I am Intersted in visiting the following citis: " + city + ", ";
    }
    if (activities.length > 0) {
        str += "I am Intersted in following activities: " + activities + ". "
    }
    if (adate.length > 0) {
        str += "I will be ariving on " + adate;
    }
    if (ddate.length > 0) {
        str += " And departing on " + ddate;
    }
    if (adult.length > 0) {
        if (adult == 1 && child == null) {
            str += ". I will be travelling alone"
        } else if (adult > 1) {
            str += ".We will have a group of " + adult + " adults ";
        }
        if (child == null) {
            str += ".";
        } else if (child > 1) {
            str += "along with " + child + " children.";
        } else if (child == 1) {
            str += "along with a child.";
        }
    }

    if (comment.length > 0) {
        str += "%0D%0A" + comment + "."
    }

    if (warning.length > 0) {
        alert(warning)
    } else {
        str += "%0D%0ARegards,%0D%0A" + name;
        document.getElementById('send').href = str;
    }
}

How to convert DataSet to DataTable

DataSet is collection of DataTables.... you can get the datatable from DataSet as below.

//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset

"java.lang.OutOfMemoryError : unable to create new native Thread"

You have a chance to face the java.lang.OutOfMemoryError: Unable to create new native thread whenever the JVM asks for a new thread from the OS. Whenever the underlying OS cannot allocate a new native thread, this OutOfMemoryError will be thrown. The exact limit for native threads is very platform-dependent thus its recommend to find out those limits by running a test similar to the below link example. But, in general, the situation causing java.lang.OutOfMemoryError: Unable to create new native thread goes through the following phases:

  1. A new Java thread is requested by an application running inside the JVM
  2. JVM native code proxies the request to create a new native thread to the OS The OS tries to create a new native thread which requires memory to be allocated to the thread
  3. The OS will refuse native memory allocation either because the 32-bit Java process size has depleted its memory address space – e.g. (2-4) GB process size limit has been hit – or the virtual memory of the OS has been fully depleted
  4. The java.lang.OutOfMemoryError: Unable to create new native thread error is thrown.

Reference: https://plumbr.eu/outofmemoryerror/unable-to-create-new-native-thread

Pass a PHP array to a JavaScript function

You can pass PHP arrays to JavaScript using json_encode PHP function.

<?php
    $phpArray = array(
        0 => "Mon", 
        1 => "Tue", 
        2 => "Wed", 
        3 => "Thu",
        4 => "Fri", 
        5 => "Sat",
        6 => "Sun",
    )
?>

<script type="text/javascript">

    var jArray = <?php echo json_encode($phpArray); ?>;

    for(var i=0; i<jArray.length; i++){
        alert(jArray[i]);
    }

 </script>

Facebook Graph API error code list

While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.

Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.

How can I parse JSON with C#?

Try the following code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");
JArray array = new JArray();
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var objText = reader.ReadToEnd();

    JObject joResponse = JObject.Parse(objText);
    JObject result = (JObject)joResponse["result"];
    array = (JArray)result["Detail"];
    string statu = array[0]["dlrStat"].ToString();
}

How to make a promise from setTimeout

Implementation:

// Promisify setTimeout
const pause = (ms, cb, ...args) =>
  new Promise((resolve, reject) => {
    setTimeout(async () => {
      try {
        resolve(await cb?.(...args))
      } catch (error) {
        reject(error)
      }
    }, ms)
  })

Tests:

// Test 1
pause(1000).then(() => console.log('called'))
// Test 2
pause(1000, (a, b, c) => [a, b, c], 1, 2, 3).then(value => console.log(value))
// Test 3
pause(1000, () => {
  throw Error('foo')
}).catch(error => console.error(error))

Node.js https pem error: routines:PEM_read_bio:no start line

I removed this error by write the following code

Open Terminal

  1. openssl req -newkey rsa:2048 -new -nodes -keyout key.pem -out csr.pem

  2. openssl x509 -req -days 365 -in csr.pem -signkey key.pem -out server.crt

Now use the server.crt and key.pem file

app.js or server.js file

var https = require('https');
var https_options = {
  key: fs.readFileSync('key.pem', 'utf8'),
  cert: fs.readFileSync('server.crt', 'utf8')
};

var server = https.createServer(https_options, app).listen(PORT);
console.log('HTTPS Server listening on %s:%s', HOST, PORT);

It works but the certificate is not trusted. You can view the image in image file.

enter image description here

Change limit for "Mysql Row size too large"

The question has been asked on serverfault too.

You may want to take a look at this article which explains a lot about MySQL row sizes. It's important to note that even if you use TEXT or BLOB fields, your row size could still be over 8K (limit for InnoDB) because it stores the first 768 bytes for each field inline in the page.

The simplest way to fix this is to use the Barracuda file format with InnoDB. This basically gets rid of the problem altogether by only storing the 20 byte pointer to the text data instead of storing the first 768 bytes.


The method that worked for the OP there was:

  1. Add the following to the my.cnf file under [mysqld] section.

    innodb_file_per_table=1
    innodb_file_format = Barracuda
    
  2. ALTER the table to use ROW_FORMAT=COMPRESSED.

    ALTER TABLE nombre_tabla
        ENGINE=InnoDB
        ROW_FORMAT=COMPRESSED 
        KEY_BLOCK_SIZE=8;
    

There is a possibility that the above still does not resolve your issues. It is a known (and verified) bug with the InnoDB engine, and a temporary fix for now is to fallback to MyISAM engine as temporary storage. So, in your my.cnf file:

internal_tmp_disk_storage_engine=MyISAM

Python and SQLite: insert into table

conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
  c.execute('insert into tablename values (?,?,?)', item)

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

I was using Postman to test my Laravel API.

I received an error that stated

"SQLSTATE[42S22]: Column not found: 1054 Unknown column" because Laravel was trying to automatically create two columns "created_at" and "updated_at".

I had to enter public $timestamps = false; to my model. Then, I tested again with Postman and saw that an "id" = 0 variable was being created in my database.

I finally had to add public $incrementing false; to fix my API.

Calling a javascript function in another js file

Please note this only works if the

<script>

tags are in the body and NOT in the head.

So

<head>
...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</head>

=> unknown function fn1()

Fails and

<body>
...
<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</body>

works.

Pretty-Print JSON Data to a File using Python

If you already have existing JSON files which you want to pretty format you could use this:

    with open('twitterdata.json', 'r+') as f:
        data = json.load(f)
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()

How to convert int[] to Integer[] in Java?

Update: Though the below compiles, it throws a ArrayStoreException at runtime. Too bad. I'll let it stay for future reference.


Converting an int[], to an Integer[]:

int[] old;
...
Integer[] arr = new Integer[old.length];
System.arraycopy(old, 0, arr, 0, old.length);

I must admit I was a bit surprised that this compiles, given System.arraycopy being lowlevel and everything, but it does. At least in java7.

You can convert the other way just as easily.

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

faced the same problem: Gradle sync failed: failed to find Build Tools revision x.x.x

reason: the build tools for that version was not down loaded properly solution:

  1. Click File > Settings (on a Mac, Android Studio > Preferences) to open the Settings dialog.
  2. Go to Appearance & Behavior > System Settings > Android SDK (Or simply search for Android SDK on the search bar)
  3. Go to SDK Tools tab > Check the Show Package Details checkbox
  4. uncheck the specific version to remove it.
  5. click apply.

then follow the steps 1 to 3 and 6.

  1. Select the specific version of the build tool and click on the Apply button After the installation, sync the project

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1922-1' for key 'IDX_STOCK_PRODUCT'

your column value is already in database table it means your table column is Unique you should change your value and try again

List of remotes for a Git repository?

The answers so far tell you how to find existing branches:

git branch -r

Or repositories for the same project [see note below]:

git remote -v

There is another case. You might want to know about other project repositories hosted on the same server.

To discover that information, I use SSH or PuTTY to log into to host and ls to find the directories containing the other repositories. For example, if I cloned a repository by typing:

git clone ssh://git.mycompany.com/git/ABCProject

and want to know what else is available, I log into git.mycompany.com via SSH or PuTTY and type:

ls /git

assuming ls says:

 ABCProject DEFProject

I can use the command

 git clone ssh://git.mycompany.com/git/DEFProject

to gain access to the other project.

NOTE: Usually git remote simply tells me about origin -- the repository from which I cloned the project. git remote would be handy if you were collaborating with two or more people working on the same project and accessing each other's repositories directly rather than passing everything through origin.

How can I find the link URL by link text with XPath?

Too late for you, but for anyone else with the same question...

//a[contains(text(), 'programming')]/@href

Of course, 'programming' can be any text fragment.

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

You can make the query using convert to varbinary – it’s very easy. Example:

Select * from your_table where convert(varbinary, your_column) = convert(varbinary, 'aBcD') 

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

If you're using an embedded driver, the connectString is just

jdbc:derby:databaseName 

(whith options like;create=true;user=xxx etc).

If you're using client driver, the connect string can be left as is, but if changing the driver gives no result... excuse the question, but are you 100% sure you have started the Derby Network Server as per the Derby Tutorial?

Questions every good Database/SQL developer should be able to answer

I would give a badly written query and ask them how they would go about performance tuning it.

I would ask about set theory. If you don't understand operating in sets, you can't effectively query a relational database.

I would give them some cursor examples and ask how they would rewrite them to make them set-based.

If the job involved imports and exports I would ask questions about SSIS (or other tools involved in doing this used by other datbases). If it involved writing reports, I would want to know that they understand aggregates and grouping (As well as Crystal Reports or SSRS or whatever ereporting tool you use).

I would ask the difference in results between these three queries:

select  a.field1
        , a.field2
        , b.field3
from table1 a
join table2 b
    on a.id = b.id
where a.field5 = 'test'
    and b.field3 = 1

select  a.field1
        , a.field2
        , b.field3
from table1 a
left join table2 b
    on a.id = b.id
where a.field5 = 'test'
    and b.field3 = 1

select  a.field1
        , a.field2
        , b.field3
from table1 a
left join table2 b
    on a.id = b.id and b.field3 = 1
where a.field5 = 'test'

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

I see most people confused about tf.shape(tensor) and tensor.get_shape() Let's make it clear:

  1. tf.shape

tf.shape is used for dynamic shape. If your tensor's shape is changable, use it. An example: a input is an image with changable width and height, we want resize it to half of its size, then we can write something like:
new_height = tf.shape(image)[0] / 2

  1. tensor.get_shape

tensor.get_shape is used for fixed shapes, which means the tensor's shape can be deduced in the graph.

Conclusion: tf.shape can be used almost anywhere, but t.get_shape only for shapes can be deduced from graph.

How to remove backslash on json_encode() function?

the solution that does work is this:

$str = preg_replace('/\\\"/',"\"", $str);

However you have to be extremely careful here because you need to make sure that all your values have their quotes escaped (which is generally true anyway, but especially so now that you will be stripping all the escapes from PHP's idiotic (and dysfunctional) "helper" functionality of adding unnecessary backslashes in front of all your object ids and values).

So, php, by default, double escapes your values that have a quote in them, so if you have a value of My name is "Joe" in your DB, php will bring this back as My name is \\"Joe\\".

This may or may not be useful to you. If it's not you can then take the extra step of replacing the leading slash there like this:

$str = preg_replace('/\\\\\"/',"\"", $str);

yeah... it's ugly... but it works.

You're then left with something that vaguely resembles actual JSON.

How can I convert a DOM element to a jQuery element?

var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element

How to run cron once, daily at 10pm

To run once, daily at 10PM you should do something like this:

0 22 * * *

enter image description here

Full size image: http://i.stack.imgur.com/BeXHD.jpg

Source: softpanorama.org

"Specified argument was out of the range of valid values"

I was also getting same issue as i tried using value 0 in non-based indexing,i.e starting with 1, not with zero

Installing Python 3 on RHEL

Python3 was recently added to EPEL7 as Python34.

There is ongoing (currently) effort to make packaging guidelines about how to package things for Python3 in EPEL7.

See https://bugzilla.redhat.com/show_bug.cgi?id=1219411
and https://lists.fedoraproject.org/pipermail/python-devel/2015-July/000721.html

How do I set the visibility of a text box in SSRS using an expression?

Twood, Visibility expression is the expressions you write on how you want the "visibility" to behave. So, if you would want to hide or show the textbox, you want to write this:

=IIf((CountRows("ScannerStatisticsData")=0),True,False)

This means, if the dataset is 0, you want to hide the textbox.

Fully custom validation error message with Rails

If you want to list them all in a nice list but without using the cruddy non human friendly name, you can do this...

object.errors.each do |attr,message|
  puts "<li>"+message+"</li>"
end

Java: how do I initialize an array size if it's unknown?

You should use a List for something like this, not an array. As a general rule of thumb, when you don't know how many elements you will add to an array before hand, use a List instead. Most would probably tackle this problem by using an ArrayList.

If you really can't use a List, then you'll probably have to use an array of some initial size (maybe 10?) and keep track of your array capacity versus how many elements you're adding, and copy the elements to a new, larger array if you run out of room (this is essentially what ArrayList does internally). Also note that, in the real world, you would never do it this way - you would use one of the standard classes that are made specifically for cases like this, such as ArrayList.

When to create variables (memory management)

It's really a matter of opinion. In your example, System.out.println(5) would be slightly more efficient, as you only refer to the number once and never change it. As was said in a comment, int is a primitive type and not a reference - thus it doesn't take up much space. However, you might want to set actual reference variables to null only if they are used in a very complicated method. All local reference variables are garbage collected when the method they are declared in returns.

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

Think of DIV as a grouping element. You put elements in a DIV element so that you can set their alignments

Whereas "p" is simply to create a new paragraph.

Inheritance and Overriding __init__ in python

In each class that you need to inherit from, you can run a loop of each class that needs init'd upon initiation of the child class...an example that can copied might be better understood...

class Female_Grandparent:
    def __init__(self):
        self.grandma_name = 'Grandma'

class Male_Grandparent:
    def __init__(self):
        self.grandpa_name = 'Grandpa'

class Parent(Female_Grandparent, Male_Grandparent):
    def __init__(self):
        Female_Grandparent.__init__(self)
        Male_Grandparent.__init__(self)

        self.parent_name = 'Parent Class'

class Child(Parent):
    def __init__(self):
        Parent.__init__(self)
#---------------------------------------------------------------------------------------#
        for cls in Parent.__bases__: # This block grabs the classes of the child
             cls.__init__(self)      # class (which is named 'Parent' in this case), 
                                     # and iterates through them, initiating each one.
                                     # The result is that each parent, of each child,
                                     # is automatically handled upon initiation of the 
                                     # dependent class. WOOT WOOT! :D
#---------------------------------------------------------------------------------------#



g = Female_Grandparent()
print g.grandma_name

p = Parent()
print p.grandma_name

child = Child()

print child.grandma_name

Bootstrap 3 Glyphicons are not working

I just renamed the font from bootstrap.css using Ctrl+c, Ctrl+v and it worked.

Add two numbers and display result in textbox with Javascript

_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
app.controller('myCtrl', function($scope) {_x000D_
_x000D_
    $scope.minus = function() {     _x000D_
_x000D_
     var a = Number($scope.a || 0);_x000D_
            var b = Number($scope.b || 0);_x000D_
            $scope.sum1 = a-b;_x000D_
    // $scope.sum = $scope.sum1+1; _x000D_
    alert($scope.sum1);_x000D_
    }_x000D_
_x000D_
   $scope.add = function() {     _x000D_
_x000D_
     var c = Number($scope.c || 0);_x000D_
            var d = Number($scope.d || 0);_x000D_
            $scope.sum2 = c+d;_x000D_
    alert($scope.sum2);_x000D_
    }_x000D_
});
_x000D_
<head>_x000D_
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>_x000D_
   </head>_x000D_
<body>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
     <h3>Using Double Negation</h3>_x000D_
_x000D_
    <p>First Number:_x000D_
        <input type="text" ng-model="a" />_x000D_
    </p>_x000D_
    <p>Second Number:_x000D_
        <input type="text" ng-model="b" />_x000D_
    </p>_x000D_
    <button id="minus" ng-click="minus()">Minus</button>_x000D_
    <!-- <p>Sum: {{ a - b }}</p>  -->_x000D_
 <p>Sum: {{ sum1 }}</p>_x000D_
_x000D_
    <p>First Number:_x000D_
        <input type="number" ng-model="c" />_x000D_
    </p>_x000D_
    <p>Second Number:_x000D_
        <input type="number" ng-model="d" />_x000D_
    </p>_x000D_
 <button id="minus" ng-click="add()">Add</button>_x000D_
    <p>Sum: {{ sum2 }}</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Differences between JDK and Java SDK

JDK is the SDK for Java.

SDK stands for 'Software Development Kit', a developers tools that enables one to write the code with more more ease, effectiveness and efficiency. SDKs come for various languages. They provide a lot of APIs (Application Programming Interfaces) that makes the programmer's work easy.

enter image description here

The SDK for Java is called as JDK, the Java Development Kit. So by saying SDK for Java you are actually referring to the JDK.

Assuming that you are new to Java, there is another term that you'll come across- JRE, the acronym for Java Runtime Environment. JRE is something that you need when you try to run software programs written in Java.

Java is a platform independent language. The JRE runs the JVM, the Java Virtual Machine, that enables you to run the software on any platform for which the JVM is available.

How do I get the max and min values from a set of numbers entered?

This is what I did and it works try and play around with it. It calculates total,avarage,minimum and maximum.

public static void main(String[] args) {
   int[] score= {56,90,89,99,59,67};
   double avg;
   int sum=0;
   int maxValue=0;
   int minValue=100;

   for(int i=0;i<6;i++){
       sum=sum+score[i];
   if(score[i]<minValue){
    minValue=score[i];
   }
   if(score[i]>maxValue){
    maxValue=score[i];
   }
   }
   avg=sum/6.0;
System.out.print("Max: "+maxValue+"," +" Min: "+minValue+","+" Avarage: "+avg+","+" Sum: "+sum);}

 }

How do I include a file over 2 directories back?

. = current directory
.. = parent directory

So ../ gets you one directory back not two.

Chain ../ as many times as necessary to go up 2 or more levels.

Test if number is odd or even

This code checks if the number is odd or even in PHP. In the example $a is 2 and you get even number. If you need odd then change the $a value

$a=2;
if($a %2 == 0){
    echo "<h3>This Number is <b>$a</b> Even</h3>";
}else{
    echo "<h3>This Number is <b>$a</b> Odd</h3>";
}

LDAP filter for blank (empty) attribute

Search for a null value by using \00

For example:

ldapsearch -D cn=admin -w pass -s sub -b ou=users,dc=acme 'manager=\00' uid manager

Make sure if you use the null value on the command line to use quotes around it to prevent the OS shell from sending a null character to LDAP. For example, this won't work:

 ldapsearch -D cn=admin -w pass -s sub -b ou=users,dc=acme manager=\00 uid manager

There are various sites that reference this, along with other special characters. Example:

How To: Best way to draw table in console app (C#)

Use MarkDownLog library (you can find it on NuGet)

you can simply use the extension ToMarkdownTable() to any collection, it does all the formatting for you.

 Console.WriteLine(
    yourCollection.Select(s => new
                    {
                        column1 = s.col1,
                        column2 = s.col2,
                        column3 = s.col3,
                        StaticColumn = "X"
                    })
                    .ToMarkdownTable());

Output looks something like this:

Column1  | Column2   | Column3   | StaticColumn   
--------:| ---------:| ---------:| --------------
         |           |           | X              

Download and install an ipa from self hosted url on iOS

There are online tools that simplify this process of sharing, for example https://abbashare.com or https://diawi.com Create an ipa file from xcode with adhoc or inhouse profile, and upload this file on these site. I prefer abbashare because save file on your dropbox and you can delete it whenever you want

How to Add Incremental Numbers to a New Column Using Pandas

Here:

df = df.reset_index()
df.columns[0] = 'New_ID'
df['New_ID'] = df.index + 880

What is a good Hash Function?

This is an example of a good one and also an example of why you would never want to write one. It is a Fowler / Noll / Vo (FNV) Hash which is equal parts computer science genius and pure voodoo:

unsigned fnv_hash_1a_32 ( void *key, int len ) {
    unsigned char *p = key;
    unsigned h = 0x811c9dc5;
    int i;

    for ( i = 0; i < len; i++ )
      h = ( h ^ p[i] ) * 0x01000193;

   return h;
}

unsigned long long fnv_hash_1a_64 ( void *key, int len ) {
    unsigned char *p = key;
    unsigned long long h = 0xcbf29ce484222325ULL;
    int i;

    for ( i = 0; i < len; i++ )
      h = ( h ^ p[i] ) * 0x100000001b3ULL;

   return h;
}

Edit:

  • Landon Curt Noll recommends on his site the FVN-1A algorithm over the original FVN-1 algorithm: The improved algorithm better disperses the last byte in the hash. I adjusted the algorithm accordingly.

omp parallel vs. omp parallel for

These are equivalent.

#pragma omp parallel spawns a group of threads, while #pragma omp for divides loop iterations between the spawned threads. You can do both things at once with the fused #pragma omp parallel for directive.

What and where are the stack and heap?

Others have directly answered your question, but when trying to understand the stack and the heap, I think it is helpful to consider the memory layout of a traditional UNIX process (without threads and mmap()-based allocators). The Memory Management Glossary web page has a diagram of this memory layout.

The stack and heap are traditionally located at opposite ends of the process's virtual address space. The stack grows automatically when accessed, up to a size set by the kernel (which can be adjusted with setrlimit(RLIMIT_STACK, ...)). The heap grows when the memory allocator invokes the brk() or sbrk() system call, mapping more pages of physical memory into the process's virtual address space.

In systems without virtual memory, such as some embedded systems, the same basic layout often applies, except the stack and heap are fixed in size. However, in other embedded systems (such as those based on Microchip PIC microcontrollers), the program stack is a separate block of memory that is not addressable by data movement instructions, and can only be modified or read indirectly through program flow instructions (call, return, etc.). Other architectures, such as Intel Itanium processors, have multiple stacks. In this sense, the stack is an element of the CPU architecture.

List all of the possible goals in Maven 2?

Lets make it very simple:

Maven Lifecycles: 1. Clean 2. Default (build) 3. Site

Maven Phases of the Default Lifecycle: 1. Validate 2. Compile 3. Test 4. Package 5. Verify 6. Install 7. Deploy

Note: Don't mix or get confused with maven goals with maven lifecycle.

See Maven Build Lifecycle Basics1

Converting any string into camel case

I just ended up doing this:

String.prototype.toCamelCase = function(str) {
    return str
        .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
        .replace(/\s/g, '')
        .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

I was trying to avoid chaining together multiple replace statements. Something where I'd have $1, $2, $3 in my function. But that type of grouping is hard to understand, and your mention about cross browser problems is something I never thought about as well.

How do I enable the column selection mode in Eclipse?

First of all your mouse key must be focus in editor to enable Toggle Block Selection Mode

enter image description here

Click on toggleButton as shown in figure and it will enable Vertical selection. After selection toggle it again.

How can I use grep to find a word inside a folder?

Run(terminal) the following command inside the directory. It will recursively check inside subdirectories too.

grep -r 'your string goes here' * 

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

It may be better to set the surefire-plugin version in the parent pom, otherwise including it as a dependency will override any configuration (includes file patterns etc) that may be inherited, e.g. from Spring Boots spring-boot-starter-test pom using pluginManagement

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.0</version>
            </plugin>
        </plugins>
    </pluginManagement>
</build>

How to navigate to a directory in C:\ with Cygwin?

cd c: is supported now in cygwin

Facebook API: Get fans of / people who like a page

For s3m3n's answer, Facebook fans plugin (e.g. LAMODA) has limitation now, you get less and less new fans on continuous requests. You may try my modified PHP script to visualize results: https://gist.github.com/liruqi/7f425bd570fa8a7c73be#file-facebook_fans_by_plugin-php

Another approach is Facebook graph search. On search result page: People who like pages named "Lamoda" , open Chrome console and run JavaScript:

var run = 0;
var mails = {}
total = 3000; //????,??????????

function getEmails (cont) {
    var friendbutton=cont.getElementsByClassName("_ohe");
    for(var i=0; i<friendbutton.length; i++) {
        var link = friendbutton[i].getAttribute("href");

        if(link && link.substr(0,25)=="https://www.facebook.com/") {
            var parser = document.createElement('a');
            parser.href = link;
            if (parser.pathname) {
                path = parser.pathname.substr(1);
                if (path == "profile.php") {
                    search = parser.search.substr(1);
                    var args = search.split('&');
                    email = args[0].split('=')[1] + "@facebook.com\n";
                } else {
                    email = parser.pathname.substr(1) + "@facebook.com\n";
                }
                if (mails[email] > 0) {
                    continue;
                }
                mails[email] = 1;
                console.log(email);
            }
        }
    }
}

function moreScroll() {
    var text="";
    containerID = "BrowseResultsContainer"
    if (run > 0) {
        containerID = "fbBrowseScrollingPagerContainer" + (run-1);
    }
    var cont = document.getElementById(containerID);
    if (cont) {
        run++;
        var id = run - 2;
        if (id >= 0) {
            setTimeout(function() {
                containerID = "fbBrowseScrollingPagerContainer" + (id);
                var delcont = document.getElementById(containerID);
                if (delcont) {
                getEmails(delcont);
                delcont.parentNode.removeChild(delcont);
                }
                window.scrollTo(0, document.body.scrollHeight - 10);
            }, 1000);
        }
    } else {
        console.log("# " + containerID);
    }
    if (run < total) {
        window.scrollTo(0, document.body.scrollHeight + 10);
    }
    setTimeout(moreScroll, 2000);
}//1000?????,?????????

moreScroll();

It would load new fans and print user id/email, remove old DOM nodes to avoid page crash. You may find this script here

Find out where MySQL is installed on Mac OS X

for me it was installed in /usr/local/opt

The command I used for installation is brew install [email protected]

Convert date to another timezone in JavaScript

Provide the desired time zone, for example "Asia/Tehran" to change the current time to that timezone. I used "Asia/Seoul".

You can use the following codes. change the style if you need to do so.

please keep in mind that if you want to have h:m:s format instead of HH:MM:SS, you'll have to remove "function kcwcheckT(i)".

_x000D_
_x000D_
function kcwcheckT(i) {
  if (i < 10) {
    i = "0" + i;
  }
  return i;
}
function kcwt() {
var d = new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"});
d = new Date(d);
  var h = d.getHours();
  var m = d.getMinutes();
  var s = d.getSeconds();
  h = kcwcheckT(h);
  m = kcwcheckT(m);
  s = kcwcheckT(s);
  document.getElementById("kcwcurtime").innerHTML = h + ":" + m + ":" + s;
  var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("kcwcurday").innerHTML = days[d.getDay()]
}
kcwt();
window.setInterval(kcwt, 1000);
_x000D_
@import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');

.kcwsource {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;}
.kcwsource p {font-family: 'Nunito', sans-serif;}


.CurTbx {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;}
.kcwcstyle {font-family: 'Nunito', sans-serif; font-size: 22px;display: inline-block;}
.kcwcurstinf {font-family: 'Nunito', sans-serif; font-size: 18px;display: inline-block;margin: 0;}
.kcwcurday {margin: 0;}
.kcwcurst {margin: 0 10px 0 5px;}

/*Using the css below you can make your style responsive!*/

@media (max-width: 600px){
  .kcwcstyle {font-size: 14px;}
  .kcwcurstinf {font-size: 12px;}
}
_x000D_
<div class="kcwsource"><p>This Pen was originally developed for <a href="http://kocowafa.com" target="_blank">KOCOWAFA.com</a></p></div>
<div class="CurTbx"><p class="kcwcurst kcwcstyle" id="kcwcurday"></p><p class="kcwcurst kcwcstyle" id="kcwcurtime"></p><p class="kcwcurstinf">(Seoul, Korea)</p></div>
_x000D_
_x000D_
_x000D_

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

In Certain situations, Setting the UICollectionViewFlowLayout in viewDidLoador ViewWillAppear may not effect on the collectionView.

Setting the UICollectionViewFlowLayout in viewDidAppear may cause see the changes of the cells sizes in runtime.

Another Solution, in Swift 3 :

extension YourViewController : UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let collectionViewWidth = collectionView.bounds.width
        return CGSize(width: collectionViewWidth/3, height: collectionViewWidth/3)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 20
    }
}

SELECT COUNT in LINQ to SQL C#

Like that

var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();

or even easier

var purchCount = myBlaContext.purchases.Count()

How to close a web page on a button click, a hyperlink or a link button click?

public class Form1 : Form
{
public Form1()
{
    InitializeComponents(); // or whatever that method is called :)
    this.button.Click += new RoutedEventHandler(buttonClick);
}

private void buttonClick(object sender, EventArgs e)
{
    this.Close();
}
}

Convert UTC dates to local time in PHP

Date arithmetic is not needed if you just want to display the same timestamp in different timezones:

$format = "M d, Y h:ia";
$timestamp = gmdate($format);

date_default_timezone_set("UTC");
$utc_datetime = date($format, $timestamp);

date_default_timezone_set("America/Guayaquil");
$local_datetime = date($format, $timestamp);

Foreach Control in form, how can I do something to all the TextBoxes in my Form?

If you are using C# 3.0 or higher you can do the following

foreach ( TextBox tb in this.Controls.OfType<TextBox>()) {
  ..
}

Without C# 3.0 you can do the following

foreach ( Control c in this.Controls ) {
  TextBox tb = c as TextBox;
  if ( null != tb ) {
    ...
  }
}

Or even better, write OfType in C# 2.0.

public static IEnumerable<T> OfType<T>(IEnumerable e) where T : class { 
  foreach ( object cur in e ) {
    T val = cur as T;
    if ( val != null ) {
      yield return val;
    }
  }
}

foreach ( TextBox tb in OfType<TextBox>(this.Controls)) {
  ..
}

Overriding interface property type defined in Typescript d.ts file

It's funny I spend the day investigating possibility to solve the same case. I found that it not possible doing this way:

// a.ts - module
export interface A {
    x: string | any;
}

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

interface B extends A {
    x: SomeOtherType;
}

Cause A module may not know about all available types in your application. And it's quite boring port everything from everywhere and doing code like this.

export interface A {
    x: A | B | C | D ... Million Types Later
}

You have to define type later to have autocomplete works well.


So you can cheat a bit:

// a.ts - module
export interface A {
    x: string;
}

Left the some type by default, that allow autocomplete works, when overrides not required.

Then

// b.ts - module
import {A} from './a';

type SomeOtherType = {
  coolStuff: number
}

// @ts-ignore
interface B extends A {
    x: SomeOtherType;
}

Disable stupid exception here using @ts-ignore flag, saying us the we doing something wrong. And funny thing everything works as expected.

In my case I'm reducing the scope vision of type x, its allow me doing code more stricted. For example you have list of 100 properties, and you reduce it to 10, to avoid stupid situations

Check if user is using IE

Or this really short version, returns true if the browsers is Internet Explorer:

function isIe() {
    return window.navigator.userAgent.indexOf("MSIE ") > 0
        || !!navigator.userAgent.match(/Trident.*rv\:11\./);
}

How to play .mp4 video in videoview in android?

Check the format of the video you are rendering. Rendering of mp4 format started from API level 11 and the format must be mp4(H.264)

I encountered the same problem, I had to convert my video to many formats before I hit the format: Use total video converter to convert the video to mp4. It works like a charm.

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = evt.target || evt.srcElement;
  if (node.name == 'edit') {
    node.value = "Modify";
  }
}

</script>

<table id="table1" border="1" onclick="handleClick(event);">
    <thead>
      <tr>
          <th>Select
    </thead>
    <tbody>
       <tr> 
           <td>
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">
               </form>

   </tbody>
</table>

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Starting with C++20, you can use the starts_with method.

std::string s = "abcd";
if (s.starts_with("abc")) {
    ...
}

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Agreed with jcadcell comments, but had to use JDK 1.8 because my eclipse need that. So I just copied the MSVCR71.DLL from jdk1.6 and pasted into jdk1.8 in both the folder jdk1.8.0_121\bin and jdk1.8.0_121\jre\bin

and it Worked .... Wow... Thanks :)

jQuery deferreds and promises - .then() vs .done()

In addition to the answers above:

The real power of .then is the possibility to chain ajax calls in a fluent way, and thus avoiding callback hell.

For example:

$.getJSON( 'dataservice/General', {action:'getSessionUser'} )
    .then( function( user ) {
        console.log( user );
        return $.getJSON( 'dataservice/Address', {action:'getFirstAddress'} );
    })
    .then( function( address ) {
        console.log( address );
    })

Here the second .then follows the returned $.getJSON

Checking if jquery is loaded using Javascript

As per this link:

if (typeof jQuery == 'undefined') {
    // jQuery IS NOT loaded, do stuff here.
}


there are a few more in comments of the link as well like,

if (typeof jQuery == 'function') {...}

//or

if (typeof $== 'function') {...}

// or

if (jQuery) {
    alert("jquery is loaded");
} else {
    alert("Not loaded");
}


Hope this covers most of the good ways to get this thing done!!

How do I get the Date & Time (VBS)

Here's various date and time information you can pull in vbscript running under Windows Script Host (WSH):

Now   = 2/29/2016 1:02:03 PM
Date  = 2/29/2016
Time  = 1:02:03 PM
Timer = 78826.31     ' seconds since midnight

FormatDateTime(Now)                = 2/29/2016 1:02:03 PM
FormatDateTime(Now, vbGeneralDate) = 2/29/2016 1:02:03 PM
FormatDateTime(Now, vbLongDate)    = Monday, February 29, 2016
FormatDateTime(Now, vbShortDate)   = 2/29/2016
FormatDateTime(Now, vbLongTime)    = 1:02:03 PM
FormatDateTime(Now, vbShortTime)   = 13:02

Year(Now)   = 2016
Month(Now)  = 2
Day(Now)    = 29
Hour(Now)   = 13
Minute(Now) = 2
Second(Now) = 3

Year(Date)   = 2016
Month(Date)  = 2
Day(Date)    = 29

Hour(Time)   = 13
Minute(Time) = 2
Second(Time) = 3

Function LPad (str, pad, length)
    LPad = String(length - Len(str), pad) & str
End Function

LPad(Month(Date), "0", 2)    = 02
LPad(Day(Date), "0", 2)      = 29
LPad(Hour(Time), "0", 2)     = 13
LPad(Minute(Time), "0", 2)   = 02
LPad(Second(Time), "0", 2)   = 03

Weekday(Now)                     = 2
WeekdayName(Weekday(Now), True)  = Mon
WeekdayName(Weekday(Now), False) = Monday
WeekdayName(Weekday(Now))        = Monday

MonthName(Month(Now), True)  = Feb
MonthName(Month(Now), False) = February
MonthName(Month(Now))        = February

Set os = GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@")
os.LocalDateTime = 20131204215346.562000-300
Left(os.LocalDateTime, 4)    = 2013 ' year
Mid(os.LocalDateTime, 5, 2)  = 12   ' month
Mid(os.LocalDateTime, 7, 2)  = 04   ' day
Mid(os.LocalDateTime, 9, 2)  = 21   ' hour
Mid(os.LocalDateTime, 11, 2) = 53   ' minute
Mid(os.LocalDateTime, 13, 2) = 46   ' second

Dim wmi : Set wmi = GetObject("winmgmts:root\cimv2")
Set timeZones = wmi.ExecQuery("SELECT Bias, Caption FROM Win32_TimeZone")
For Each tz In timeZones
    tz.Bias    = -300
    tz.Caption = (UTC-05:00) Eastern Time (US & Canada)
Next

Source

how to break the _.each function in underscore.js

Update:

_.find would be better as it breaks out of the loop when the element is found:

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){ 
              count = count +1;
              if(arrEl.id === 1 ){
                  return arrEl;
              }
            });

console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1

** Old **

If you want to conditionally break out of a loop, use _.filter api instead of _.each. Here is a code snippet

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){ 
                  if(arrEl.id === 1 ){
                      return arrEl;
                  }
                });
console.log(filteredEl);
//output: {id:1,text:"foo"}

How do I order my SQLITE database in descending order, for an android app?

We have one more option to do order by

public Cursor getlistbyrank(String rank) {
        try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
        } catch (SQLException sqle) {
            Log.e("Exception on query:-", "" + sqle.getMessage());
            return null;
        }
    }

You can use this two method for order

how do I change text in a label with swift?

Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:

self.simpleLabel.text = "message"

Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.

Good tool for testing socket connections?

netcat (nc.exe) is the right tool. I have a feeling that any tool that does what you want it to do will have exactly the same problem with your antivirus software. Just flag this program as "OK" in your antivirus software (how you do this will depend on what type of antivirus software you use).

Of course you will also need to configure your sysadmin to accept that you're not trying to do anything illegal...

VBA - Range.Row.Count

This works for me especially in pivots table filtering when I want the count of cells with data on a filtered column. Reduce k accordingly (k - 1) if you have a header row for filtering:

k = Sheets("Sheet1").Range("$A:$A").SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count

How to getElementByClass instead of GetElementById with JavaScript?

Modern browsers have support for document.getElementsByClassName. You can see the full breakdown of which vendors provide this functionality at caniuse. If you're looking to extend support into older browsers, you may want to consider a selector engine like that found in jQuery or a polyfill.

Older Answer

You'll want to check into jQuery, which will allow the following:

$(".classname").hide(); // hides everything with class 'classname'

Google offers a hosted jQuery source-file, so you can reference it and be up-and-running in moments. Include the following in your page:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
  $(function(){
    $(".classname").hide();
  });
</script>

jQuery Find and List all LI elements within a UL within a specific DIV

$('li[rel=7]').siblings().andSelf();

// or:

$('li[rel=7]').parent().children();

Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:

var rels = [];

$('ul').each(function() {
    var localRels = [];

    $(this).find('li').each(function(){
        localRels.push( $(this).attr('rel') );
    });

    rels.push(localRels);
});

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

How do I load an HTML page in a <div> using JavaScript?

I finally found the answer to my problem. The solution is

function load_home() {
     document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}

How to parse a JSON file in swift?

I just wrote a class called JSON, which makes JSON handling in Swift as easy as JSON object in ES5.

Turn your swift object to JSON like so:

let obj:[String:AnyObject] = [
    "array": [JSON.null, false, 0, "",[],[:]],
    "object":[
        "null":   JSON.null,
        "bool":   true,
        "int":    42,
        "double": 3.141592653589793,
        "string": "a a\t?\n",
        "array":  [],
        "object": [:]
    ],
    "url":"http://blog.livedoor.com/dankogai/"
]

let json = JSON(obj)
json.toString()

...or string...

let json = JSON.parse("{\"array\":[...}")

...or URL.

let json = JSON.fromURL("http://api.dan.co.jp/jsonenv")
Tree Traversal

Just traverse elements via subscript:

json["object"]["null"].asNull       // NSNull()
// ...
json["object"]["string"].asString   // "a a\t?\n"
json["array"][0].asNull             // NSNull()
json["array"][1].asBool             // false
// ...

Just like SwiftyJSON you don't worry if the subscripted entry does not exist.

if let b = json["noexistent"][1234567890]["entry"].asBool {
    // ....
} else {
    let e = json["noexistent"][1234567890]["entry"].asError
    println(e)
}

If you are tired of subscripts, add your scheme like so:

//// schema by subclassing
class MyJSON : JSON {
    init(_ obj:AnyObject){ super.init(obj) }
    init(_ json:JSON)  { super.init(json) }
    var null  :NSNull? { return self["null"].asNull }
    var bool  :Bool?   { return self["bool"].asBool }
    var int   :Int?    { return self["int"].asInt }
    var double:Double? { return self["double"].asDouble }
    var string:String? { return self["string"].asString }
}

And you go:

let myjson = MyJSON(obj)
myjson.object.null
myjson.object.bool
myjson.object.int
myjson.object.double
myjson.object.string
// ...

Hope you like it.

With the new xCode 7.3+ its important to add your domain to the exception list (How can I add NSAppTransportSecurity to my info.plist file?), refer to this posting for instructions, otherwise you will get a transport authority error.

How do I convert dmesg timestamp to custom date format?

A caveat which the other answers don't seem to mention is that the time which is shown by dmesg doesn't take into account any sleep/suspend time. So there are cases where the usual answer of using dmesg -T doesn't work, and shows a completely wrong time.

A workaround for such situations is to write something to the kernel log at a known time and then use that entry as a reference to calculate the other times. Obviously, it will only work for times after the last suspend.

So to display the correct time for recent entries on machines which may have been suspended since their last boot, use something like this from my other answer here:

# write current time to kernel ring buffer so it appears in dmesg output
echo "timecheck: $(date +%s) = $(date +%F_%T)" | sudo tee /dev/kmsg

# use our "timecheck" entry to get the difference
# between the dmesg timestamp and real time
offset=$(dmesg | grep timecheck | tail -1 \
| perl -nle '($t1,$t2)=/^.(\d+)\S+ timecheck: (\d+)/; print $t2-$t1')

# pipe dmesg output through a Perl snippet to
# convert it's timestamp to correct readable times
dmesg | tail \
| perl -pe 'BEGIN{$offset=shift} s/^\[(\d+)\S+/localtime($1+$offset)/e' $offset

Are iframes considered 'bad practice'?

They are not bad, but actually helpful. I had a huge problem some time ago where I had to embed my twitter feed and it just wouldn't let md do it on the same page, so I set it on a different page, and put it in as an iframe.

They are also good because all browsers (and phone browsers) support them. They can not be considered a bad practice, as long as you use them correctly.

Angular ng-click with call to a controller function not working

I'm going to guess you aren't getting errors or you would've mentioned them. If that's the case, try removing the href attribute value so the page doesn't navigate away before your code is executed. In Angular it's perfectly acceptable to leave href attributes blank.

<a href="" data-router="article" ng-click="changeListName('metro')">

Also I don't know what data-router is doing but if you still aren't getting the proper result, that could be why.

How to get a certain element in a list, given the position?

If you frequently need to access the Nth element of a sequence, std::list, which is implemented as a doubly linked list, is probably not the right choice. std::vector or std::deque would likely be better.

That said, you can get an iterator to the Nth element using std::advance:

std::list<Object> l;
// add elements to list 'l'...

unsigned N = /* index of the element you want to retrieve */;
if (l.size() > N)
{
    std::list<Object>::iterator it = l.begin();
    std::advance(it, N);
    // 'it' points to the element at index 'N'
}

For a container that doesn't provide random access, like std::list, std::advance calls operator++ on the iterator N times. Alternatively, if your Standard Library implementation provides it, you may call std::next:

if (l.size() > N)
{
    std::list<Object>::iterator it = std::next(l.begin(), N);
}

std::next is effectively wraps a call to std::advance, making it easier to advance an iterator N times with fewer lines of code and fewer mutable variables. std::next was added in C++11.

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

There's also a shorthand ternary operator and it looks like this:

(expression1) ?: expression2 will return expression1 if it evaluates to true or expression2 otherwise.

Example:

$a = 'Apples';
echo ($a ?: 'Oranges') . ' are great!';

will return

Apples are great!

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

From the PHP Manual

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

private String convertToString(java.sql.Clob data)
{
    final StringBuilder builder= new StringBuilder();

    try
    {
        final Reader         reader = data.getCharacterStream();
        final BufferedReader br     = new BufferedReader(reader);

        int b;
        while(-1 != (b = br.read()))
        {
            builder.append((char)b);
        }

        br.close();
    }
    catch (SQLException e)
    {
        log.error("Within SQLException, Could not convert CLOB to string",e);
        return e.toString();
    }
    catch (IOException e)
    {
        log.error("Within IOException, Could not convert CLOB to string",e);
        return e.toString();
    }
    //enter code here
    return builder.toString();
}

Giving a border to an HTML table row, <tr>

_x000D_
_x000D_
<table cellpadding="0" cellspacing="0" width="100%" style="border: 1px;" rules="none">_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <th style="width: 96px;">Column 1</th>_x000D_
            <th style="width: 96px;">Column 2</th>_x000D_
            <th style="width: 96px;">Column 3</th>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
            <td style="border-left: thin solid; border-top: thin solid; border-bottom: thin solid;">&nbsp;</td>_x000D_
            <td style="border-top: thin solid; border-bottom: thin solid;">&nbsp;</td>_x000D_
            <td style="border-top: thin solid; border-bottom: thin solid; border-right: thin solid;">&nbsp;</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
            <td>&nbsp;</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to call multiple JavaScript functions in onclick event?

Sure, simply bind multiple listeners to it.

Short cutting with jQuery

_x000D_
_x000D_
$("#id").bind("click", function() {_x000D_
  alert("Event 1");_x000D_
});_x000D_
$(".foo").bind("click", function() {_x000D_
  alert("Foo class");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="foo" id="id">Click</div>
_x000D_
_x000D_
_x000D_

How to compare data between two table in different databases using Sql Server 2008?

I'v done things like this using the Checksum(*) function

In essance it creates a row level checksum on all the columns data, you could then compare the checksum of each row for each table to each other, use a left join, to find rows that are different.

Hope that made sense...

Better with an example....

select *
from 
( select checksum(*) as chk, userid as k from UserAccounts) as t1
left join 
( select checksum(*) as chk, userid as k from UserAccounts) as t2 on t1.k = t2.k
where t1.chk <> t2.chk 

How to get thread id of a pthread in linux c program?

This single line gives you pid , each threadid and spid.

 printf("before calling pthread_create getpid: %d getpthread_self: %lu tid:%lu\n",getpid(), pthread_self(), syscall(SYS_gettid));

Call a Class From another class

If your class2 looks like this having static members

public class2
{
    static int var = 1;

    public static void myMethod()
    {
      // some code

    }
}

Then you can simply call them like

class2.myMethod();
class2.var = 1;

If you want to access non-static members then you would have to instantiate an object.

class2 object = new class2();
object.myMethod();  // non static method
object.var = 1;     // non static variable

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

I was experiencing this error on Android 5.1.1 devices sending network requests using okhttp/4.0.0-RC1. Setting header Content-Length: <sizeof response> on the server side resolved the issue.

How to show form input fields based on select value?

I got its answer. Here is my code

<label for="db">Choose type</label>
<select name="dbType" id=dbType">
   <option>Choose Database Type</option>
   <option value="oracle">Oracle</option>
   <option value="mssql">MS SQL</option>
   <option value="mysql">MySQL</option>
   <option value="other">Other</option>
</select>

<div id="other" class="selectDBType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>
</div>

And my script is

$(function() {

        $('#dbType').change(function() {
            $('.selectDBType').slideUp("slow");
            $('#' + $(this).val()).slideDown("slow");
        });
    });

Appending an element to the end of a list in Scala

List(1,2,3) :+ 4

Results in List[Int] = List(1, 2, 3, 4)

Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

jQuery $(this) keyword

When you perform an DOM query through jQuery like $('class-name') it actively searched the DOM for that element and returns that element with all the jQuery prototype methods attached.

When you're within the jQuery chain or event you don't have to rerun the DOM query you can use the context $(this). Like so:

$('.class-name').on('click', (evt) => {
    $(this).hide(); // does not run a DOM query
    $('.class-name').hide() // runs a DOM query
}); 

$(this) will hold the element that you originally requested. It will attach all the jQuery prototype methods again, but will not have to search the DOM again.

Some more information:

Web Performance with jQuery selectors

Quote from a web blog that doesn't exist anymore but I'll leave it in here for history sake:

In my opinion, one of the best jQuery performance tips is to minimize your use of jQuery. That is, find a balance between using jQuery and plain ol’ JavaScript, and a good place to start is with ‘this‘. Many developers use $(this) exclusively as their hammer inside callbacks and forget about this, but the difference is distinct:

When inside a jQuery method’s anonymous callback function, this is a reference to the current DOM element. $(this) turns this into a jQuery object and exposes jQuery’s methods. A jQuery object is nothing more than a beefed-up array of DOM elements.

How to read multiple Integer values from a single line of input in Java?

created this code specially for the Hacker earth exam


  Scanner values = new Scanner(System.in);  //initialize scanner
  int[] arr = new int[6]; //initialize array 
  for (int i = 0; i < arr.length; i++) {
      arr[i] = (values.hasNext() == true ? values.nextInt():null);
      // it will read the next input value
  }

 /* user enter =  1 2 3 4 5
    arr[1]= 1
    arr[2]= 2
    and soo on 
 */ 

How to pretty-print a numpy.array without scientific notation and with given precision?

FYI Numpy 1.15 (release date pending) will include a context manager for setting print options locally. This means that the following will work the same as the corresponding example in the accepted answer (by unutbu and Neil G) without having to write your own context manager. E.g., using their example:

x = np.random.random(10)
with np.printoptions(precision=3, suppress=True):
    print(x)
    # [ 0.073  0.461  0.689  0.754  0.624  0.901  0.049  0.582  0.557  0.348]

How to evaluate http response codes from bash/shell script?

Another variation:

       status=$(curl -sS  -I https://www.healthdata.gov/user/login  2> /dev/null | head -n 1 | cut -d' ' -f2)
status_w_desc=$(curl -sS  -I https://www.healthdata.gov/user/login  2> /dev/null | head -n 1 | cut -d' ' -f2-)

Python TypeError: not enough arguments for format string

Note that the % syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

This also fixes the error that you happened to have.

How to read files and stdout from a running Docker container

Sharing files between a docker container and the host system, or between separate containers is best accomplished using volumes.

Having your app running in another container is probably your best solution since it will ensure that your whole application can be well isolated and easily deployed. What you're trying to do sounds very close to the setup described in this excellent blog post, take a look!

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

CORS is Cross Origin Resource Sharing, you get this error if you are trying to access from one domain to another domain.

Try using JSONP. In your case, JSONP should work fine because it only uses the GET method.

Try something like this:

var url = "https://api.getevents.co/event?&lat=41.904196&lng=12.465974";
$http({
    method: 'JSONP',
    url: url
}).
success(function(status) {
    //your code when success
}).
error(function(status) {
    //your code when fails
});

Cannot create Maven Project in eclipse

I am using Spring STS 3.8.3. I had a similar problem. I fixed it by using information from this thread And also by fixing some maven settings. click Spring Tool Suite -> Preferences -> Maven and uncheck the box that says "Do not automatically update dependencies from remote depositories" Also I checked the boxes that say "Download Artifact Sources" and "download Artifact javadoc".

Show how many characters remaining in a HTML text box using JavaScript

try this code in here...this is done using javascript onKeyUp() function...

<script>
function toCount(entrance,exit,text,characters) {  
var entranceObj=document.getElementById(entrance);  
var exitObj=document.getElementById(exit);  
var length=characters - entranceObj.value.length;  
if(length <= 0) {  
length=0;  
text='<span class="disable"> '+text+' <\/span>';  
entranceObj.value=entranceObj.value.substr(0,characters);  
}  
exitObj.innerHTML = text.replace("{CHAR}",length);  
}
</script>

textarea counter demo

Import Excel Data into PostgreSQL 9.3

A method that I use is to load the table into R as a data.frame, then use dbWriteTable to push it to PostgreSQL. These two steps are shown below.

Load Excel data into R

R's data.frame objects are database-like, where named columns have explicit types, such as text or numbers. There are several ways to get a spreadsheet into R, such as XLConnect. However, a really simple method is to select the range of the Excel table (including the header), copy it (i.e. CTRL+C), then in R use this command to get it from the clipboard:

d <- read.table("clipboard", header=TRUE, sep="\t", quote="\"", na.strings="", as.is=TRUE)

If you have RStudio, you can easily view the d object to make sure it is as expected.

Push it to PostgreSQL

Ensure you have RPostgreSQL installed from CRAN, then make a connection and send the data.frame to the database:

library(RPostgreSQL)
conn <- dbConnect(PostgreSQL(), dbname="mydb")

dbWriteTable(conn, "some_table_name", d)

Now some_table_name should appear in the database.

Some common clean-up steps can be done from pgAdmin or psql:

ALTER TABLE some_table_name RENAME "row.names" TO id;
ALTER TABLE some_table_name ALTER COLUMN id TYPE integer USING id::integer;
ALTER TABLE some_table_name ADD PRIMARY KEY (id);

RegEx match open tags except XHTML self-contained tags

If you're simply trying to find those tags (without ambitions of parsing) try this regular expression:

/<[^/]*?>/g

I wrote it in 30 seconds, and tested here: http://gskinner.com/RegExr/

It matches the types of tags you mentioned, while ignoring the types you said you wanted to ignore.

How to debug Angular JavaScript Code

Maybe you can use Angular Augury A Google Chrome Dev Tools extension for debugging Angular 2 and above applications.

Remove last 3 characters of string or number in javascript

you just need to divide the Date Time stamp by 1000 like:

var a = 1437203995000;
a = (a)/1000;

How to create two columns on a web page?

Basically you need 3 divs. First as wrapper, second as left and third as right.

.wrapper {
 width:500px;
 overflow:hidden;
}

.left {
 width:250px;
 float:left;
}

.right {
 width:250px;
 float:right;
}

Example how to make 2 columns http://jsfiddle.net/huhu/HDGvN/


CSS Cheat Sheet for reference

Where is HttpContent.ReadAsAsync?

If you are already using Newtonsoft.Json and don't want to install Microsoft.AspNet.WebApi.Client:

 var myInstance = JsonConvert.DeserializeObject<MyClass>(
   await response.Content.ReadAsStringAsync());

Is there a W3C valid way to disable autocomplete in a HTML form?

I think there's a simpler way. Create a hidden input with a random name (via javascript) and set the username to that. Repeat with the password. This way your backend script knows exactly what the appropriate field name is, while keeping autocomplete in the dark.

I'm probably wrong, but it's just an idea.

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

Issue in installing php7.2-mcrypt

As an alternative, you can install 7.1 version of mcrypt and create a symbolic link to it:

Install php7.1-mcrypt:

sudo apt install php7.1-mcrypt

Create a symbolic link:

sudo ln -s /etc/php/7.1/mods-available/mcrypt.ini /etc/php/7.2/mods-available

After enabling mcrypt by sudo phpenmod mcrypt, it gets available.

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

The APK file does not exist on disk

I've solved building an apk using the Build option from the top window and Build APK. No need to do something weird.

How do I format date and time on ssrs report?

I am using this

=Format(Now(), "dd/MM/yyyy hh:mm tt")

ng-mouseover and leave to toggle item using mouse in angularjs

I would simply make the assignment happen in the ng-mouseover and ng-mouseleave; no need to bother js file :)

<ul ng-repeat="task in tasks">
    <li ng-mouseover="hoverEdit = true" ng-mouseleave="hoverEdit = false">{{task.name}}</li>
    <span ng-show="hoverEdit"><a>Edit</a></span>
</ul>

Select Last Row in the Table

Use the latest scope provided by Laravel out of the box.

Model::latest()->first();

That way you're not retrieving all the records. A nicer shortcut to orderBy.

How to pass multiple arguments in processStartInfo?

For makecert, your startInfo.FileName should be the complete path of makecert (or just makecert.exe if it's in standard path) then the Arguments would be -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer now I'm bit unfamiliar with how certificate store works, but perhaps you'll need to set startInfo.WorkingDirectory if you're referring the .cer files outside the certificate store

How can I make robocopy silent in the command line except for progress?

A workaround, if you want it to be absolutely silent, is to redirect the output to a file (and optionally delete it later).

Robocopy src dest > output.log
del output.log

Simplest way to read json from a URL in java

It's very easy, using jersey-client, just include this maven dependency:

<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-client</artifactId>
  <version>2.25.1</version>
</dependency>

Then invoke it using this example:

String json = ClientBuilder.newClient().target("http://api.coindesk.com/v1/bpi/currentprice.json").request().accept(MediaType.APPLICATION_JSON).get(String.class);

Then use Google's Gson to parse the JSON:

Gson gson = new Gson();
Type gm = new TypeToken<CoinDeskMessage>() {}.getType();
CoinDeskMessage cdm = gson.fromJson(json, gm);

How can I use a batch file to write to a text file?

You can use echo, and redirect the output to a text file (see notes below):

rem Saved in D:\Temp\WriteText.bat
@echo off
echo This is a test> test.txt
echo 123>> test.txt
echo 245.67>> test.txt

Output:

D:\Temp>WriteText

D:\Temp>type test.txt
This is a test
123
245.67

D:\Temp>

Notes:

  • @echo off turns off printing of each command to the console
  • Unless you give it a specific path name, redirection with > or >> will write to the current directory (the directory the code is being run in).
  • The echo This is a test > test.txt uses one > to overwrite any file that already exists with new content.
  • The remaining echo statements use two >> characters to append to the text file (add to), instead of overwriting it.
  • The type test.txt simply types the file output to the command window.

How to manually send HTTP POST requests from Firefox or Chrome browser?

I think that @Benny Neugebauer comment on the OP question about the Fetch API should be presented here as an answer since the OP was looking for a functionality in Chrome to manually create HTTP POST requests and that exactly what the fetch command do.

There is a nice simple example of the Fetch API here

// Make sure you run it from the domain 'https://jsonplaceholder.typicode.com/'. (cross-origin-policy)
fetch('https://jsonplaceholder.typicode.com/posts',{method: 'POST', headers: {'test': 'TestPost'} })
  .then(response => response.json())
  .then(json => console.log(json))

Some of the advantages of the fetch command are really precious: Its simple, short, fast, available and even as a console command it stored on your chrome console and can be used later.

The simplicity of pressing F12, write the command in the console tab (or press the up key if you used it before) then press enter, see it pending and returning the response is what making it really useful for simple post requests tests.

Of course, The main disadvantage here is that unlike Postman, This wont pass the cross-origin-policy but still I find it very useful for testing in local environment or other environments where I can enable CORS manually.

How to correctly link php-fpm and Nginx Docker containers?

As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).

Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from.

Using compose (1.6.2 in my machine), the docker-compose.yml file would read:

version: "2"
services:
  nginx:
    build:
      context: .
      dockerfile: nginx/Dockerfile
    ports:
      - "80:80"
    links:
      - fpm
    volumes_from:
      - data
  fpm:
    image: php:fpm
    volumes_from:
      - data
  data:
    build:
      context: .
      dockerfile: data/Dockerfile
    volumes:
      - /var/www/html

Note that data publishes a volume that is linked to the nginx and fpm services. Then the Dockerfile for the data service, that contains your source code:

FROM busybox

# content
ADD path/to/source /var/www/html

And the Dockerfile for nginx, that just replaces the default config:

FROM nginx

# config
ADD config/default.conf /etc/nginx/conf.d

For the sake of completion, here's the config file required for the example to work:

server {
    listen 0.0.0.0:80;

    root /var/www/html;

    location / {
        index index.php index.html;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass fpm:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
    }
}

which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT, which is fpm:9000 thanks to the hostnames defined by compose, and the SCRIPT_FILENAME).

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

How to take backup of a single table in a MySQL database?

Dump and restore a single table from .sql

Dump

mysqldump db_name table_name > table_name.sql

Dumping from a remote database

mysqldump -u <db_username> -h <db_host> -p db_name table_name > table_name.sql

For further reference:

http://www.abbeyworkshop.com/howto/lamp/MySQL_Export_Backup/index.html

Restore

mysql -u <user_name> -p db_name
mysql> source <full_path>/table_name.sql

or in one line

mysql -u username -p db_name < /path/to/table_name.sql


Dump and restore a single table from a compressed (.sql.gz) format

Credit: John McGrath

Dump

mysqldump db_name table_name | gzip > table_name.sql.gz

Restore

gunzip < table_name.sql.gz | mysql -u username -p db_name

how to auto select an input field and the text in it on page load

when using jquery...

html:

<input type='text' value='hello world' id='hello-world-input'>

jquery:

$(function() {
  $('#hello-world-input').focus().select();
});

example: https://jsfiddle.net/seanmcmills/xmh4e0d4/

ASP.net using a form to insert data into an sql server table

Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

Material effect on button with background color

If you're ok with using a third party library, check out traex/RippleEffect. It allows you to add a Ripple effect to ANY view with just a few lines of code. You just need to wrap, in your xml layout file, the element you want to have a ripple effect with a com.andexert.library.RippleView container.

As an added bonus it requires Min SDK 9 so you can have design consistency across OS versions.

Here's an example taken from the libraries' GitHub repo:

<com.andexert.library.RippleView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:rv_centered="true">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@android:drawable/ic_menu_edit"
        android:background="@android:color/holo_blue_dark"/> 

</com.andexert.library.RippleView>

You can change the ripple colour by adding this attribute the the RippleView element: app:rv_color="@color/my_fancy_ripple_color

What is PAGEIOLATCH_SH wait type in SQL Server?

From Microsoft documentation:

PAGEIOLATCH_SH

Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.

In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.

If your query is like this:

Select * from <table> where <col1> = <value> order by <PrimaryKey>

, check that you have a composite index on (col1, col_primary_key).

If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen.

Both of them are very disk I/O consuming operations on large tables.

How do I send a POST request with PHP?

There's another CURL method if you are going that way.

This is pretty straightforward once you get your head around the way the PHP curl extension works, combining various flags with setopt() calls. In this example I've got a variable $xml which holds the XML I have prepared to send - I'm going to post the contents of that to example's test method.

$url = 'http://api.example.com/services/xmlrpc/';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);
//process $response

First we initialised the connection, then we set some options using setopt(). These tell PHP that we are making a post request, and that we are sending some data with it, supplying the data. The CURLOPT_RETURNTRANSFER flag tells curl to give us the output as the return value of curl_exec rather than outputting it. Then we make the call and close the connection - the result is in $response.

How to place a file on classpath in Eclipse?

Copy the file into your src folder. Go to the Project Explorer in Eclipse, Right-click on your project, and click on "Refresh". The file should appear on the Project Explorer pane as well.

How to select first child with jQuery?

Hi we can use default method "first" in jQuery

Here some examples:

When you want to add class for first div

  $('.alldivs div').first().addClass('active');

When you want to change the remove the "onediv" class and add only to first child

   $('.alldivs div').removeClass('onediv').first().addClass('onediv');

Jenkins/Hudson - accessing the current build number?

BUILD_NUMBER is the current build number. You can use it in the command you execute for the job, or just use it in the script your job executes.

See the Jenkins documentation for the full list of available environment variables. The list is also available from within your Jenkins instance at http://hostname/jenkins/env-vars.html.

Stop jQuery .load response from being cached

Here is an example of how to control caching on a per-request basis

$.ajax({
    url: "/YourController",
    cache: false,
    dataType: "html",
    success: function(data) {
        $("#content").html(data);
    }
});

Python: how to capture image from webcam on click using OpenCV

i'm not too experienced with open cv but if you want the code in the for loop to be called when a key is pressed, you can use a while loop and an raw_input and a condition to prevent the loop from executing forever

import cv2

camera = cv2.VideoCapture(0)
i = 0
while i < 10:
    raw_input('Press Enter to capture')
    return_value, image = camera.read()
    cv2.imwrite('opencv'+str(i)+'.png', image)
    i += 1
del(camera)

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

Windows 10 Defender Firewall was blocking it. I turned it off, ran the mvc core 2.0 application, and it worked. I then turned windows firewall on again and it remained working. All the other solutions although well intended didn't work for me. Hope this helps someone out there.

How to properly and completely close/reset a TcpClient connection?

Except for some internal logging, Close == Dispose.

Dispose calls tcpClient.Client.Shutdown( SocketShutdown.Both ), but its eats any errors. Maybe if you call it directly, you can get some useful exception information.

How to use environment variables in docker compose

I have a simple bash script I created for this it just means running it on your file before use: https://github.com/antonosmond/subber

Basically just create your compose file using double curly braces to denote environment variables e.g:

app:
    build: "{{APP_PATH}}"
ports:
    - "{{APP_PORT_MAP}}"

Anything in double curly braces will be replaced with the environment variable of the same name so if I had the following environment variables set:

APP_PATH=~/my_app/build
APP_PORT_MAP=5000:5000

on running subber docker-compose.yml the resulting file would look like:

app:
    build: "~/my_app/build"
ports:
    - "5000:5000"

How to define a variable in a Dockerfile?

If the variable is re-used within the same RUN instruction, one could simply set a shell variable. I really like how they approached this with the official Ruby Dockerfile.

How to change button text or link text in JavaScript?

You can simply use:

document.getElementById(button_id).innerText = 'Your text here';

If you want to use HTML formatting, use the innerHTML property instead.

TextView bold via xml file?

Use android:textStyle="bold"

4 ways to make Android TextView Bold

like this

<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="12dip"
android:textStyle="bold"
/>

There are many ways to make Android TextView bold.

How can I add the sqlite3 module to Python?

For Python version 3:

pip install pysqlite3 

Genymotion Android emulator - adb access?

Connect didn't work for me, The problem was that Genymotion uses its own dk-tools and you need to change it to custom SDK tools.

More info: https://stackoverflow.com/a/26630862/4154438