Programs & Examples On #Makefile

A makefile is usually an input file for the build control language/tool make.

How to set the LDFLAGS in CMakeLists.txt?

It depends a bit on what you want:

A) If you want to specify which libraries to link to, you can use find_library to find libs and then use link_directories and target_link_libraries to.

Of course, it is often worth the effort to write a good find_package script, which nicely adds "imported" libraries with add_library( YourLib IMPORTED ) with correct locations, and platform/build specific pre- and suffixes. You can then simply refer to 'YourLib' and use target_link_libraries.

B) If you wish to specify particular linker-flags, e.g. '-mthreads' or '-Wl,--export-all-symbols' with MinGW-GCC, you can use CMAKE_EXE_LINKER_FLAGS. There are also two similar but undocumented flags for modules, shared or static libraries:

CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

Cygwin Make bash command not found

I faced the same problem. Follow these steps:

  1. Goto the installer once again.
  2. Do the initial setup.
  3. Select all the libraries by clicking and selecting install (the one already installed will show reinstall, so don't install them).
  4. Click next.
  5. The installation will take some time.

Passing additional variables from command line to make

From the manual:

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment.

So you can do (from bash):

FOOBAR=1 make

resulting in a variable FOOBAR in your Makefile.

How can I print message in Makefile?

It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:

ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************  TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif

What is makeinfo, and how do I get it?

Another option is to use apt-file (i.e. apt-file search makeinfo). It may or may not be installed in your distro by default, but it is a great tool for determining what package a file belongs to.

Makefile If-Then Else and Loops

Have you tried the GNU make documentation? It has a whole section about conditionals with examples.

How to generate a Makefile with source in sub-directories using just one makefile

Usually, you create a Makefile in each subdirectory, and write in the top-level Makefile to call make in the subdirectories.

This page may help: http://www.gnu.org/software/make/

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

I was getting the error “gcc: error: x86_64-linux-gnu-gcc: No such file or directory” as I was trying to build a simple c-extension module to run in Python. I tried all the things above to no avail, and finally realized that I had an error in my module.c code! So I thought it would be helpful to add that, if you are getting this error message but you have python-dev and everything correctly installed, you should look for issues in your code.

make *** no targets specified and no makefile found. stop

Delete your source tree that was gunzipped or gzipped and extracted to folder and reextract again. Supply your options again

./configure --with-option=/path/etc ...

Then if all libs are present, your make should succeed.

Define make variable at rule execution time

In your example, the TMP variable is set (and the temporary directory created) whenever the rules for out.tar are evaluated. In order to create the directory only when out.tar is actually fired, you need to move the directory creation down into the steps:

out.tar : 
    $(eval TMP := $(shell mktemp -d))
    @echo hi $(TMP)/hi.txt
    tar -C $(TMP) cf $@ .
    rm -rf $(TMP)

The eval function evaluates a string as if it had been typed into the makefile manually. In this case, it sets the TMP variable to the result of the shell function call.

edit (in response to comments):

To create a unique variable, you could do the following:

out.tar : 
    $(eval $@_TMP := $(shell mktemp -d))
    @echo hi $($@_TMP)/hi.txt
    tar -C $($@_TMP) cf $@ .
    rm -rf $($@_TMP)

This would prepend the name of the target (out.tar, in this case) to the variable, producing a variable with the name out.tar_TMP. Hopefully, that is enough to prevent conflicts.

Multi-line bash commands in makefile

Of course, the proper way to write a Makefile is to actually document which targets depend on which sources. In the trivial case, the proposed solution will make foo depend on itself, but of course, make is smart enough to drop a circular dependency. But if you add a temporary file to your directory, it will "magically" become part of the dependency chain. Better to create an explicit list of dependencies once and for all, perhaps via a script.

GNU make knows how to run gcc to produce an executable out of a set of .c and .h files, so maybe all you really need amounts to

foo: $(wildcard *.h) $(wildcard *.c)

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

How do I force make/GCC to show me the commands?

Build system independent method

make SHELL='sh -x'

is another option. Sample Makefile:

a:
    @echo a

Output:

+ echo a
a

This sets the special SHELL variable for make, and -x tells sh to print the expanded line before executing it.

One advantage over -n is that is actually runs the commands. I have found that for some projects (e.g. Linux kernel) that -n may stop running much earlier than usual probably because of dependency problems.

One downside of this method is that you have to ensure that the shell that will be used is sh, which is the default one used by Make as they are POSIX, but could be changed with the SHELL make variable.

Doing sh -v would be cool as well, but Dash 0.5.7 (Ubuntu 14.04 sh) ignores for -c commands (which seems to be how make uses it) so it doesn't do anything.

make -p will also interest you, which prints the values of set variables.

CMake generated Makefiles always support VERBOSE=1

As in:

mkdir build
cd build
cmake ..
make VERBOSE=1

Dedicated question at: Using CMake with GNU Make: How can I see the exact commands?

How to include clean target in Makefile?

By the way it is written, clean rule is invoked only if it is explicitly called:

make clean

I think it is better, than make clean every time. If you want to do this by your way, try this:

CXX = g++ -O2 -Wall

all: clean code1 code2

code1: code1.cc utilities.cc
   $(CXX) $^ -o $@

code2: code2.cc utilities.cc
   $(CXX) $^ -o $@

clean: 
    rm ...
    echo Clean done

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

CMAKE_MAKE_PROGRAM not found

Previous answers suggested (re)installing or configuring CMake, they all did not help.

Previously MinGW's compilation of Make used the filename mingw32-make.exe and now it is make.exe. Most suggested ways to configure CMake to use the other file dont work.

Just copy make.exe and rename the copy mingw32-make.exe.

Program "make" not found in PATH

Make sure you have installed 'make' tool through Cygwin's installer.

Using G++ to compile multiple .cpp and .h files

To compile separately without linking you need to add -c option:

g++ -c myclass.cpp
g++ -c main.cpp
g++ myclass.o main.o
./a.out

What does "make oldconfig" do exactly in the Linux kernel makefile?

Updates an old config with new/changed/removed options.

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

How to uninstall after "make install"

Method #1 (make uninstall)

Step 1: You only need to follow this step if you've deleted/altered the build directory in any way: Download and make/make install using the exact same procedure as you did before.

Step 2: try make uninstall.

cd $SOURCE_DIR 
sudo make uninstall

If this succeeds you are done. If you're paranoid you may also try the steps of "Method #3" to make sure make uninstall didn't miss any files.

Method #2 (checkinstall -- only for debian based systems)

Overview of the process

In debian based systems (e.g. Ubuntu) you can create a .deb package very easily by using a tool named checkinstall. You then install the .deb package (this will make your debian system realize that the all parts of your package have been indeed installed) and finally uninstall it to let your package manager properly cleanup your system.

Step by step

sudo apt-get -y install checkinstall
cd $SOURCE_DIR 
sudo checkinstall

At this point checkinstall will prompt for a package name. Enter something a bit descriptive and note it because you'll use it in a minute. It will also prompt for a few more data that you can ignore. If it complains about the version not been acceptable just enter something reasonable like 1.0. When it completes you can install and finally uninstall:

sudo dpkg -i $PACKAGE_NAME_YOU_ENTERED 
sudo dpkg -r $PACKAGE_NAME_YOU_ENTERED

Method #3 (install_manifest.txt)

If a file install_manifest.txt exists in your source dir it should contain the filenames of every single file that the installation created.

So first check the list of files and their mod-time:

cd $SOURCE_DIR 
sudo xargs -I{} stat -c "%z %n" "{}" < install_manifest.txt

You should get zero errors and the mod-times of the listed files should be on or after the installation time. If all is OK you can delete them in one go:

cd $SOURCE_DIR 
mkdir deleted-by-uninstall
sudo xargs -I{} mv -t deleted-by-uninstall "{}" < install_manifest.txt

User Merlyn Morgan-Graham however has a serious notice regarding this method that you should keep in mind (copied here verbatim): "Watch out for files that might also have been installed by other packages. Simply deleting these files [...] could break the other packages.". That's the reason that we've created the deleted-by-uninstall dir and moved files there instead of deleting them.


99% of this post existed in other answers. I just collected everything useful in a (hopefully) easy to follow how-to and tried to give extra attention to important details (like quoting xarg arguments and keeping backups of deleted files).

How to add include and lib paths to configure/make cycle?

This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf

Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.

After successfully running autogen.sh/configure, compile with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make

The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.

I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.

How to abort makefile if variable not set?

TL;DR: Use the error function:

ifndef MY_FLAG
$(error MY_FLAG is not set)
endif

Note that the lines must not be indented. More precisely, no tabs must precede these lines.


Generic solution

In case you're going to test many variables, it's worth defining an auxiliary function for that:

# Check that given variables are set and all have non-empty values,
# die with an error otherwise.
#
# Params:
#   1. Variable name(s) to test.
#   2. (optional) Error message to print.
check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
      $(error Undefined $1$(if $2, ($2))))

And here is how to use it:

$(call check_defined, MY_FLAG)

$(call check_defined, OUT_DIR, build directory)
$(call check_defined, BIN_DIR, where to put binary artifacts)
$(call check_defined, \
            LIB_INCLUDE_DIR \
            LIB_SOURCE_DIR, \
        library path)


This would output an error like this:

Makefile:17: *** Undefined OUT_DIR (build directory).  Stop.

Notes:

The real check is done here:

$(if $(value $1),,$(error ...))

This reflects the behavior of the ifndef conditional, so that a variable defined to an empty value is also considered "undefined". But this is only true for simple variables and explicitly empty recursive variables:

# ifndef and check_defined consider these UNDEFINED:
explicitly_empty =
simple_empty := $(explicitly_empty)

# ifndef and check_defined consider it OK (defined):
recursive_empty = $(explicitly_empty)

As suggested by @VictorSergienko in the comments, a slightly different behavior may be desired:

$(if $(value $1) tests if the value is non-empty. It's sometimes OK if the variable is defined with an empty value. I'd use $(if $(filter undefined,$(origin $1)) ...

And:

Moreover, if it's a directory and it must exist when the check is run, I'd use $(if $(wildcard $1)). But would be another function.

Target-specific check

It is also possible to extend the solution so that one can require a variable only if a certain target is invoked.

$(call check_defined, ...) from inside the recipe

Just move the check into the recipe:

foo :
    @:$(call check_defined, BAR, baz value)

The leading @ sign turns off command echoing and : is the actual command, a shell no-op stub.

Showing target name

The check_defined function can be improved to also output the target name (provided through the $@ variable):

check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
        $(error Undefined $1$(if $2, ($2))$(if $(value @), \
                required by target `$@')))

So that, now a failed check produces a nicely formatted output:

Makefile:7: *** Undefined BAR (baz value) required by target `foo'.  Stop.

check-defined-MY_FLAG special target

Personally I would use the simple and straightforward solution above. However, for example, this answer suggests using a special target to perform the actual check. One could try to generalize that and define the target as an implicit pattern rule:

# Check that a variable specified through the stem is defined and has
# a non-empty value, die with an error otherwise.
#
#   %: The name of the variable to test.
#   
check-defined-% : __check_defined_FORCE
    @:$(call check_defined, $*, target-specific)

# Since pattern rules can't be listed as prerequisites of .PHONY,
# we use the old-school and hackish FORCE workaround.
# You could go without this, but otherwise a check can be missed
# in case a file named like `check-defined-...` exists in the root 
# directory, e.g. left by an accidental `make -t` invocation.
.PHONY : __check_defined_FORCE
__check_defined_FORCE :

Usage:

foo :|check-defined-BAR

Notice that the check-defined-BAR is listed as the order-only (|...) prerequisite.

Pros:

  • (arguably) a more clean syntax

Cons:

I believe, these limitations can be overcome using some eval magic and secondary expansion hacks, although I'm not sure it's worth it.

Hunk #1 FAILED at 1. What's that mean?

Follow the instructions here, it solved my problem.

you have to run the command like as follow; patch -p0 --dry-run < path/to/your/patchFile/yourPatch.patch

Compiling C++ on remote Linux machine - "clock skew detected" warning

type in the terminal and it will solve the issue:

find . -type f | xargs -n 5 touch

make clean

clean

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

Create directories using make file

All solutions including the accepted one have some issues as stated in their respective comments. The accepted answer by @jonathan-leffler is already quite good but does not take into effect that prerequisites are not necessarily to be built in order (during make -j for example). However simply moving the directories prerequisite from all to program provokes rebuilds on every run AFAICT. The following solution does not have that problem and AFAICS works as intended.

MKDIR_P := mkdir -p
OUT_DIR := build

.PHONY: directories all clean

all: $(OUT_DIR)/program

directories: $(OUT_DIR)

$(OUT_DIR):
    ${MKDIR_P} $(OUT_DIR)

$(OUT_DIR)/program: | directories
    touch $(OUT_DIR)/program

clean:
    rm -rf $(OUT_DIR)

How to write loop in a Makefile?

For cross-platform support, make the command separator (for executing multiple commands on the same line) configurable.

If you're using MinGW on a Windows platform for example, the command separator is &:

NUMBERS = 1 2 3 4
CMDSEP = &
doit:
    $(foreach number,$(NUMBERS),./a.out $(number) $(CMDSEP))

This executes the concatenated commands in one line:

./a.out 1 & ./a.out 2 & ./a.out 3 & ./a.out 4 &

As mentioned elsewhere, on a *nix platform use CMDSEP = ;.

How do you get the list of targets in a makefile?

To expand on the answer given by @jsp, you can even evaluate variables in your help text with the $(eval) function.

The proposed version below has these enhanced properties:

  • Will scan any makefiles (even included)
  • Will expand live variables referenced in the help comment
  • Adds documentation anchor for real targets (prefixed with # TARGETDOC:)
  • Adds column headers

So to document, use this form:

RANDOM_VARIABLE := this will be expanded in help text

.PHONY: target1 # Target 1 help with $(RANDOM_VARIABLE)
target1: deps
    [... target 1 build commands]

# TARGETDOC: $(BUILDDIR)/real-file.txt # real-file.txt help text
$(BUILDDIR)/real-file.txt:
    [... $(BUILDDIR)/real-file.txt build commands]

Then, somewhere in your makefile:

.PHONY: help # Generate list of targets with descriptions
help:
    @# find all help in targets and .PHONY and evaluate the embedded variables
    $(eval doc_expanded := $(shell grep -E -h '^(.PHONY:|# TARGETDOC:) .* #' $(MAKEFILE_LIST) | sed -E -n 's/(\.PHONY|# TARGETDOC): (.*) # (.*)/\2  \3\\n/'p | expand -t40))
    @echo
    @echo ' TARGET   HELP' | expand -t40
    @echo ' ------   ----' | expand -t40
    @echo -e ' $(doc_expanded)'

How to get current relative directory of your Makefile?

The shell function.

You can use shell function: current_dir = $(shell pwd). Or shell in combination with notdir, if you need not absolute path: current_dir = $(notdir $(shell pwd)).

Update.

Given solution only works when you are running make from the Makefile's current directory.
As @Flimm noted:

Note that this returns the current working directory, not the parent directory of the Makefile.
For example, if you run cd /; make -f /home/username/project/Makefile, the current_dir variable will be /, not /home/username/project/.

Code below will work for Makefiles invoked from any directory:

mkfile_path := $(abspath $(lastword $(MAKEFILE_LIST)))
current_dir := $(notdir $(patsubst %/,%,$(dir $(mkfile_path))))

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

Your problem is most likely that the shell does not know where to find your make program. If you want to use it from "anywhere", then you must do this, or else you will need to add the full path each time you want to call it, which is quite cumbersome. For instance:

"c:\program files\gnuwin32\bin\make.exe" option1=thisvalue option2=thatvalue

This is to be taken as an example, it used to look like something like this on XP, I can't say on W7. But gnuwin32 used to provide useful "linux-world" packages for Windows. Check details on your provider for make.

So to avoid entering the path, you can add the path to your PATH environment variable. You will find this easily. To make sure it is registered by the OS, open a console (run cmd.exe) and entering $PATH should give you a list of default pathes. Check that the location of your make program is there.

Where can I set path to make.exe on Windows?

I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly.

For anyone else finding this issue, I fixed it by moving the environment variable higher than others!

How to pass argument to Makefile from command line?

Much easier aproach. Consider a task:

provision:
        ansible-playbook -vvvv \
        -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory \
        --private-key=.vagrant/machines/default/virtualbox/private_key \
        --start-at-task="$(AT)" \
        -u vagrant playbook.yml

Now when I want to call it I just run something like:

AT="build assets" make provision

or just:

make provision in this case AT is an empty string

Why does make think the target is up to date?

It happens when you have a file with the same name as Makefile target name in the directory where the Makefile is present.

enter image description here

How to get a shell environment variable in a makefile?

all:
    echo ${PATH}

Or change PATH just for one command:

all:
    PATH=/my/path:${PATH} cmd

Make file echo displaying "$PATH" string

In the manual for GNU make, they talk about this specific example when describing the value function:

The value function provides a way for you to use the value of a variable without having it expanded. Please note that this does not undo expansions which have already occurred; for example if you create a simply expanded variable its value is expanded during the definition; in that case the value function will return the same result as using the variable directly.

The syntax of the value function is:

 $(value variable)

Note that variable is the name of a variable; not a reference to that variable. Therefore you would not normally use a ‘$’ or parentheses when writing it. (You can, however, use a variable reference in the name if you want the name not to be a constant.)

The result of this function is a string containing the value of variable, without any expansion occurring. For example, in this makefile:

 FOO = $PATH

 all:
         @echo $(FOO)
         @echo $(value FOO)

The first output line would be ATH, since the “$P” would be expanded as a make variable, while the second output line would be the current value of your $PATH environment variable, since the value function avoided the expansion.

Using local makefile for CLion instead of CMake

Currently, only CMake is supported by CLion. Others build systems will be added in the future, but currently, you can only use CMake.

An importer tool has been implemented to help you to use CMake.

Edit:

Source : http://blog.jetbrains.com/clion/2014/09/clion-answers-frequently-asked-questions/

What does "all" stand for in a makefile?

Not sure it stands for anything special. It's just a convention that you supply an 'all' rule, and generally it's used to list all the sub-targets needed to build the entire project, hence the name 'all'. The only thing special about it is that often times people will put it in as the first target in the makefile, which means that just typing 'make' alone will do the same thing as 'make all'.

How I could add dir to $PATH in Makefile?

By design make parser executes lines in a separate shell invocations, that's why changing variable (e.g. PATH) in one line, the change may not be applied for the next lines (see this post).

One way to workaround this problem, is to convert multiple commands into a single line (separated by ;), or use One Shell special target (.ONESHELL, as of GNU Make 3.82).

Alternatively you can provide PATH variable at the time when shell is invoked. For example:

PATH  := $(PATH):$(PWD)/bin:/my/other/path
SHELL := env PATH=$(PATH) /bin/bash

ldconfig error: is not a symbolic link

I ran into this issue with the Oracle 11R2 client. Not sure if the Oracle installer did this or someone did it here before i arrived. It was not 64-bit vs 32-bit, all was 64-bit.

The error was that libexpat.so.1 was not a symbolic link.

It turned out that there were two identical files, libexpat.so.1.5.2 and libexpat.so.1. Removing the offending file and making it a symlink to the 1.5.2 version caused the error to go away.

Makes sense that you'd want the well-known name to be a symlink to the current version. If you do this, it's less likely that you'll end up with a stale library.

Make: how to continue after a command fails?

Change clean to

rm -f .lambda .lambda_t .activity .activity_t_lambda

I.e. don't prompt for remove; don't complain if file doesn't exist.

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

"make clean" results in "No rule to make target `clean'"

It seems your makefile's name is not 'Makefile' or 'makefile'. In case it is different say 'abc' try running 'make -f abc clean'

CMake output/build directory

You should not rely on a hard coded build dir name in your script, so the line with ../Compile must be changed.

It's because it should be up to user where to compile.

Instead of that use one of predefined variables: http://www.cmake.org/Wiki/CMake_Useful_Variables (look for CMAKE_BINARY_DIR and CMAKE_CURRENT_BINARY_DIR)

Makefile to compile multiple C programs?

all: program1 program2

program1:
    gcc -Wall -o prog1 program1.c

program2:
    gcc -Wall -o prog2 program2.c

Make install, but not to default directories?

If the package provides a Makefile.PL - one can use:

perl Makefile.PL PREFIX=/home/my/local/lib LIB=/home/my/local/lib
make
make test
make install

* further explanation: https://www.perlmonks.org/?node_id=564720

How to install and use "make" in Windows?

  1. Install Msys2 http://www.msys2.org
  2. Follow installation instructions
  3. Install make with $ pacman -S make gettext base-devel
  4. Add C:\msys64\usr\bin\ to your path

How do I capture all of my compiler's output to a file?

In a bourne shell:

make > my.log 2>&1

I.e. > redirects stdout, 2>&1 redirects stderr to the same place as stdout

What is the purpose of .PHONY in a Makefile?

NOTE: The make tool reads the makefile and checks the modification time-stamps of the files at both the side of ':' symbol in a rule.

Example

In a directory 'test' following files are present:

prerit@vvdn105:~/test$ ls
hello  hello.c  makefile

In makefile a rule is defined as follows:

hello:hello.c
    cc hello.c -o hello

Now assume that file 'hello' is a text file containing some data, which was created after 'hello.c' file. So the modification (or creation) time-stamp of 'hello' will be newer than that of the 'hello.c'. So when we will invoke 'make hello' from command line, it will print as:

make: `hello' is up to date.

Now access the 'hello.c' file and put some white spaces in it, which doesn't affect the code syntax or logic then save and quit. Now the modification time-stamp of hello.c is newer than that of the 'hello'. Now if you invoke 'make hello', it will execute the commands as:

cc hello.c -o hello

And the file 'hello' (text file) will be overwritten with a new binary file 'hello' (result of above compilation command).

If we use .PHONY in makefile as follow:

.PHONY:hello

hello:hello.c
    cc hello.c -o hello

and then invoke 'make hello', it will ignore any file present in the pwd 'test' and execute the command every time.

Now suppose, that 'hello' target has no dependencies declared:

hello:
    cc hello.c -o hello

and 'hello' file is already present in the pwd 'test', then 'make hello' will always show as:

make: `hello' is up to date.

Makefile ifeq logical or

Here more flexible variant: it uses external shell, but allows to check for arbitrary conditions:

ifeq ($(shell test ".$(GCC_MINOR)" = .4  -o  \
                   ".$(GCC_MINOR)" = .5  -o  \
                   ".$(TODAY)"     = .Friday  &&  printf "true"), true)
    CFLAGS += -fno-strict-overflow
endif

How do I check if file exists in Makefile so I can delete it?

I was trying:

[ -f $(PROGRAM) ] && cp -f $(PROGRAM) $(INSTALLDIR)

And the positive case worked but my ubuntu bash shell calls this TRUE and breaks on the copy:

[ -f  ] && cp -f  /home/user/proto/../bin/
cp: missing destination file operand after '/home/user/proto/../bin/'

After getting this error, I google how to check if a file exists in make, and this is the answer...

Makefiles with source files in different directories

You can add rules to your root Makefile in order to compile the necessary cpp files in other directories. The Makefile example below should be a good start in getting you to where you want to be.

CC=g++
TARGET=cppTest
OTHERDIR=../../someotherpath/in/project/src

SOURCE = cppTest.cpp
SOURCE = $(OTHERDIR)/file.cpp

## End sources definition
INCLUDE = -I./ $(AN_INCLUDE_DIR)  
INCLUDE = -I.$(OTHERDIR)/../inc
## end more includes

VPATH=$(OTHERDIR)
OBJ=$(join $(addsuffix ../obj/, $(dir $(SOURCE))), $(notdir $(SOURCE:.cpp=.o))) 

## Fix dependency destination to be ../.dep relative to the src dir
DEPENDS=$(join $(addsuffix ../.dep/, $(dir $(SOURCE))), $(notdir $(SOURCE:.cpp=.d)))

## Default rule executed
all: $(TARGET)
        @true

## Clean Rule
clean:
        @-rm -f $(TARGET) $(OBJ) $(DEPENDS)


## Rule for making the actual target
$(TARGET): $(OBJ)
        @echo "============="
        @echo "Linking the target $@"
        @echo "============="
        @$(CC) $(CFLAGS) -o $@ $^ $(LIBS)
        @echo -- Link finished --

## Generic compilation rule
%.o : %.cpp
        @mkdir -p $(dir $@)
        @echo "============="
        @echo "Compiling $<"
        @$(CC) $(CFLAGS) -c $< -o $@


## Rules for object files from cpp files
## Object file for each file is put in obj directory
## one level up from the actual source directory.
../obj/%.o : %.cpp
        @mkdir -p $(dir $@)
        @echo "============="
        @echo "Compiling $<"
        @$(CC) $(CFLAGS) -c $< -o $@

# Rule for "other directory"  You will need one per "other" dir
$(OTHERDIR)/../obj/%.o : %.cpp
        @mkdir -p $(dir $@)
        @echo "============="
        @echo "Compiling $<"
        @$(CC) $(CFLAGS) -c $< -o $@

## Make dependancy rules
../.dep/%.d: %.cpp
        @mkdir -p $(dir $@)
        @echo "============="
        @echo Building dependencies file for $*.o
        @$(SHELL) -ec '$(CC) -M $(CFLAGS) $< | sed "s^$*.o^../obj/$*.o^" > $@'

## Dependency rule for "other" directory
$(OTHERDIR)/../.dep/%.d: %.cpp
        @mkdir -p $(dir $@)
        @echo "============="
        @echo Building dependencies file for $*.o
        @$(SHELL) -ec '$(CC) -M $(CFLAGS) $< | sed "s^$*.o^$(OTHERDIR)/../obj/$*.o^" > $@'

## Include the dependency files
-include $(DEPENDS)

Makefile, header dependencies

Martin's solution above works great, but does not handle .o files that reside in subdirectories. Godric points out that the -MT flag takes care of that problem, but it simultaneously prevents the .o file from being written correctly. The following will take care of both of those problems:

DEPS := $(OBJS:.o=.d)

-include $(DEPS)

%.o: %.c
    $(CC) $(CFLAGS) -MM -MT $@ -MF $(patsubst %.o,%.d,$@) $<
    $(CC) $(CFLAGS) -o $@ $<

How to set child process' environment variable in Makefile

I only needed the environment variables locally to invoke my test command, here's an example setting multiple environment vars in a bash shell, and escaping the dollar sign in make.

SHELL := /bin/bash

.PHONY: test tests
test tests:
    PATH=./node_modules/.bin/:$$PATH \
    JSCOVERAGE=1 \
    nodeunit tests/

How to use GNU Make on Windows?

user1594322 gave a correct answer but when I tried it I ran into admin/permission problems. I was able to copy 'mingw32-make.exe' and paste it, over-ruling/by-passing admin issues and then editing the copy to 'make.exe'. On VirtualBox in a Win7 guest.

How does "make" app know default target to build if no target is specified?

GNU Make also allows you to specify the default make target using a special variable called .DEFAULT_GOAL. You can even unset this variable in the middle of the Makefile, causing the next target in the file to become the default target.

Ref: The Gnu Make manual - Special Variables

What do the makefile symbols $@ and $< mean?

in exemple if you want to compile sources but have objects in an different directory :

You need to do :

gcc -c -o <obj/1.o> <srcs/1.c> <obj/2.o> <srcs/2.c> ...

but with most of macros the result will be all objects followed by all sources, like :

gcc -c -o <all OBJ path> <all SRC path>

so this will not compile anything ^^ and you will not be able to put your objects files in a different dir :(

the solution is to use these special macros

$@ $<

this will generate a .o file (obj/file.o) for each .c file in SRC (src/file.c)

$(OBJ):$(SRC)
   gcc -c -o $@ $< $(HEADERS) $(FLAGS)

it means :

    $@ = $(OBJ)
    $< = $(SRC)

but lines by lines INSTEAD of all lines of OBJ followed by all lines of SRC

Why do I get permission denied when I try use "make" to install something?

On many source packages (e.g. for most GNU software), the building system may know about the DESTDIR make variable, so you can often do:

 make install DESTDIR=/tmp/myinst/
 sudo cp -va /tmp/myinst/ /

The advantage of this approach is that make install don't need to run as root, so you cannot end up with files compiled as root (or root-owned files in your build tree).

How to solve error: "Clock skew detected"?

please try to do

make clean

(instead of make), then

make

again.

Compiling with g++ using multiple cores

People have mentioned make but bjam also supports a similar concept. Using bjam -jx instructs bjam to build up to x concurrent commands.

We use the same build scripts on Windows and Linux and using this option halves our build times on both platforms. Nice.

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

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

is enough. the rest is implicit

OS detecting makefile

Here's a simple solution that checks if you are in a Windows or posix-like (Linux/Unix/Cygwin/Mac) environment:

ifeq ($(shell echo "check_quotes"),"check_quotes")
   WINDOWS := yes
else
   WINDOWS := no
endif

It takes advantage of the fact that echo exists on both posix-like and Windows environments, and that in Windows the shell does not filter the quotes.

How to call Makefile from another Makefile?

http://www.gnu.org/software/make/manual/make.html#Recursion

 subsystem:
         cd subdir && $(MAKE)

or, equivalently, this :

 subsystem:
         $(MAKE) -C subdir

"commence before first target. Stop." error

This means that there is a line which starts with a space, tab, or some other whitespace without having a target in front of it.

"multiple target patterns" Makefile error

My IDE left a mix of spaces and tabs in my Makefile.

Setting my Makefile to use only tabs fixed this error for me.

How to run a makefile in Windows?

I use MinGW tool set which provides mingw32-make build tool, if you have it in your PATH system variables, in Windows Command Prompt just go into the directory containing the files and type this command:

mingw32-make -f Makefile.win

and it's done.

What are Makefile.am and Makefile.in?

reference :

Makefile.am -- a user input file to automake

configure.in -- a user input file to autoconf


autoconf generates configure from configure.in

automake gererates Makefile.in from Makefile.am

configure generates Makefile from Makefile.in

For ex:

$]
configure.in Makefile.in
$] sudo autoconf
configure configure.in Makefile.in ... 
$] sudo ./configure
Makefile Makefile.in

Makefile: How to correctly include header file and its directory?

Try INC_DIR=../ ../StdCUtil.

Then, set CCFLAGS=-c -Wall $(addprefix -I,$(INC_DIR))

EDIT: Also, modify your #include to be #include <StdCUtil/split.h> so that the compiler knows to use -I rather than local path of the .cpp using the #include.

how to "execute" make file

You don't tend to execute the make file itself, rather you execute make, giving it the make file as an argument:

make -f pax.mk

If your make file is actually one of the standard names (like makefile or Makefile), you don't even need to specify it. It'll be picked up by default (if you have more than one of these standard names in your build directory, you better look up the make man page to see which takes precedence).

gcc makefile error: "No rule to make target ..."

In my case the path is not set in VPATH, after added the error gone.

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

How to assign the output of a command to a Makefile variable

With GNU Make, you can use shell and eval to store, run, and assign output from arbitrary command line invocations. The difference between the example below and those which use := is the := assignment happens once (when it is encountered) and for all. Recursively expanded variables set with = are a bit more "lazy"; references to other variables remain until the variable itself is referenced, and the subsequent recursive expansion takes place each time the variable is referenced, which is desirable for making "consistent, callable, snippets". See the manual on setting variables for more info.

# Generate a random number.
# This is not run initially.
GENERATE_ID = $(shell od -vAn -N2 -tu2 < /dev/urandom)

# Generate a random number, and assign it to MY_ID
# This is not run initially.
SET_ID = $(eval MY_ID=$(GENERATE_ID))

# You can use .PHONY to tell make that we aren't building a target output file
.PHONY: mytarget
mytarget:
# This is empty when we begin
    @echo $(MY_ID)
# This recursively expands SET_ID, which calls the shell command and sets MY_ID
    $(SET_ID)
# This will now be a random number
    @echo $(MY_ID)
# Recursively expand SET_ID again, which calls the shell command (again) and sets MY_ID (again)
    $(SET_ID)
# This will now be a different random number
    @echo $(MY_ID)

How to discover number of *logical* cores on Mac OS X?

It wasn't specified in the original question (although I saw OP post in comments that this wasn't an option), but many developers on macOS have the Homebrew package manager installed.

For future developers who stumble upon this question, as long as the assumption (or requirement) of Homebrew being installed exists (e.g., in an engineering organization in a company), nproc is one of the common GNU binaries that is included in the coreutils package.

brew install coreutils

If you have scripts that you would prefer to write once (for Linux + macOS) instead of twice, or to avoid having if blocks where you need to detect the OS to know whether or not to call nproc vs sysctl -n hw.logicalcpu, this may be a better option.

Using 'make' on OS X

There is now another way to install the gcc toolchain on OS X through the osx-gcc-installer this includes:

  • GCC
  • LLVM
  • Clang
  • Developer CLI Tools (purge, make, etc)
  • DevSDK (headers, etc)

The download is 282MB vs 3GB for Xcode.

Passing arguments to "make run"

You can pass the variable to the Makefile like below:

run:
    @echo ./prog $$FOO

Usage:

$ make run FOO="the dog kicked the cat"
./prog the dog kicked the cat

or:

$ FOO="the dog kicked the cat" make run
./prog the dog kicked the cat

Alternatively use the solution provided by Beta:

run:
    @echo ./prog $(filter-out $@,$(MAKECMDGOALS))
%:
    @:

%: - rule which match any task name; @: - empty recipe = do nothing

Usage:

$ make run the dog kicked the cat
./prog the dog kicked the cat

"No rule to make target 'install'"... But Makefile exists

I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install. When I changed to the directory that had my makefile it worked.

So possibly you aren't in the right directory.

How to pass macro definition from "make" command line arguments (-D) to C source code?

$ cat x.mak
all:
    echo $(OPTION)
$ make -f x.mak 'OPTION=-DPASSTOC=42'
echo -DPASSTOC=42
-DPASSTOC=42

How to use LDFLAGS in makefile

Seems like the order of the linking flags was not an issue in older versions of gcc. Eg gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16) comes with Centos-6.7 happy with linker option before inputfile; but gcc with ubuntu 16.04 gcc (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413 does not allow.

Its not the gcc version alone, I has got something to with the distros

If conditions in a Makefile, inside a target

You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:

clean:
    @if [ "test" = "test" ]; then\
        echo "Hello world";\
    fi

Note that the closing ";" and "\" are necessary.

How to define several include path in Makefile

Make's substitutions feature is nice and helped me to write

%.i: src/%.c $(INCLUDE)
        gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@

You might find this useful, because it asks make to check for changes in include folders too

How to make a SIMPLE C++ Makefile

I suggest (note that the indent is a TAB):

tool: tool.o file1.o file2.o
    $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@

or

LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
tool: tool.o file1.o file2.o

The latter suggestion is slightly better since it reuses GNU Make implicit rules. However, in order to work, a source file must have the same name as the final executable (i.e.: tool.c and tool).

Notice, it is not necessary to declare sources. Intermediate object files are generated using implicit rule. Consequently, this Makefile work for C and C++ (and also for Fortran, etc...).

Also notice, by default, Makefile use $(CC) as the linker. $(CC) does not work for linking C++ object files. We modify LINK.o only because of that. If you want to compile C code, you don't have to force the LINK.o value.

Sure, you can also add your compilation flags with variable CFLAGS and add your libraries in LDLIBS. For example:

CFLAGS = -Wall
LDLIBS = -lm

One side note: if you have to use external libraries, I suggest to use pkg-config in order to correctly set CFLAGS and LDLIBS:

CFLAGS += $(shell pkg-config --cflags libssl)
LDLIBS += $(shell pkg-config --libs libssl)

The attentive reader will notice that this Makefile does not rebuild properly if one header is changed. Add these lines to fix the problem:

override CPPFLAGS += -MMD
include $(wildcard *.d)

-MMD allows to build .d files that contains Makefile fragments about headers dependencies. The second line just uses them.

For sure, a well written Makefile should also include clean and distclean rules:

clean:
    $(RM) *.o *.d

distclean: clean
    $(RM) tool

Notice, $(RM) is the equivalent of rm -f, but it is a good practice to not call rm directly.

The all rule is also appreciated. In order to work, it should be the first rule of your file:

all: tool

You may also add an install rule:

PREFIX = /usr/local
install:
    install -m 755 tool $(DESTDIR)$(PREFIX)/bin

DESTDIR is empty by default. The user can set it to install your program at an alternative system (mandatory for cross-compilation process). Package maintainers for multiple distribution may also change PREFIX in order to install your package in /usr.

One final word: Do not place source files in sub-directories. If you really want to do that, keep this Makefile in the root directory and use full paths to identify your files (i.e. subdir/file.o).

So to summarise, your full Makefile should look like:

LINK.o = $(CXX) $(LDFLAGS) $(TARGET_ARCH)
PREFIX = /usr/local
override CPPFLAGS += -MMD
include $(wildcard *.d)

all: tool
tool: tool.o file1.o file2.o
clean:
    $(RM) *.o *.d
distclean: clean
    $(RM) tool
install:
    install -m 755 tool $(DESTDIR)$(PREFIX)/bin

Where can I find "make" program for Mac OS X Lion?

You need to install Xcode from App Store.

Then start Xcode, go to Xcode->Preferences->Downloads and install component named "Command Line Tools". After that all the relevant tools will be placed in /usr/bin folder and you will be able to use it just as it was in 10.6.

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Try:

cl /v

Actually, any time I give cl an argument, it prints out the version number on the first line.

You could just feed it a garbage argument and then parse the first line of the output, which contains the verison number.

How do I write the 'cd' command in a makefile?

To change dir

foo: 
    $(MAKE) -C mydir

multi:
    $(MAKE) -C / -C my-custom-dir   ## Equivalent to /my-custom-dir

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

In the above answers, it is important to understand what is meant by "values are expanded at declaration/use time". Giving a value like *.c does not entail any expansion. It is only when this string is used by a command that it will maybe trigger some globbing. Similarly, a value like $(wildcard *.c) or $(shell ls *.c) does not entail any expansion and is completely evaluated at definition time even if we used := in the variable definition.

Try the following Makefile in directory where you have some C files:

VAR1 = *.c
VAR2 := *.c
VAR3 = $(wildcard *.c)
VAR4 := $(wildcard *.c)
VAR5 = $(shell ls *.c)
VAR6 := $(shell ls *.c)

all :
    touch foo.c
    @echo "now VAR1 = \"$(VAR1)\"" ; ls $(VAR1)
    @echo "now VAR2 = \"$(VAR2)\"" ; ls $(VAR2)
    @echo "now VAR3 = \"$(VAR3)\"" ; ls $(VAR3)
    @echo "now VAR4 = \"$(VAR4)\"" ; ls $(VAR4)
    @echo "now VAR5 = \"$(VAR5)\"" ; ls $(VAR5)
    @echo "now VAR6 = \"$(VAR6)\"" ; ls $(VAR6)
    rm -v foo.c

Running make will trigger a rule that creates an extra (empty) C file, called foo.c but none of the 6 variables has foo.c in its value.

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

Make error: missing separator

I had the missing separator file in Makefiles generated by qmake. I was porting Qt code to a different platform. I didn't have QMAKESPEC nor MAKE set. Here's the link I found the answer:

https://forum.qt.io/topic/3783/missing-separator-error-in-makefile/5

How can I configure my makefile for debug and release builds?

You can use Target-specific Variable Values. Example:

CXXFLAGS = -g3 -gdwarf2
CCFLAGS = -g3 -gdwarf2

all: executable

debug: CXXFLAGS += -DDEBUG -g
debug: CCFLAGS += -DDEBUG -g
debug: executable

executable: CommandParser.tab.o CommandParser.yy.o Command.o
    $(CXX) -o output CommandParser.yy.o CommandParser.tab.o Command.o -lfl

CommandParser.yy.o: CommandParser.l 
    flex -o CommandParser.yy.c CommandParser.l
    $(CC) -c CommandParser.yy.c

Remember to use $(CXX) or $(CC) in all your compile commands.

Then, 'make debug' will have extra flags like -DDEBUG and -g where as 'make' will not.

On a side note, you can make your Makefile a lot more concise like other posts had suggested.

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

According to the GNU make manual:

CFLAGS: Extra flags to give to the C compiler.
CXXFLAGS: Extra flags to give to the C++ compiler.
CPPFLAGS: Extra flags to give to the C preprocessor and programs that use it (the C and Fortran compilers).

src: https://www.gnu.org/software/make/manual/make.html#index-CFLAGS
note: PP stands for PreProcessor (and not Plus Plus), i.e.

CPP: Program for running the C preprocessor, with results to standard output; default ‘$(CC) -E’.

These variables are used by the implicit rules of make

Compiling C programs
n.o is made automatically from n.c with a recipe of the form
‘$(CC) $(CPPFLAGS) $(CFLAGS) -c’.

Compiling C++ programs
n.o is made automatically from n.cc, n.cpp, or n.C with a recipe of the form
‘$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c’.
We encourage you to use the suffix ‘.cc’ for C++ source files instead of ‘.C’.

src: https://www.gnu.org/software/make/manual/make.html#Catalogue-of-Rules

tar: file changed as we read it

Here is a one-liner for ignoring the tar exit status if it is 1. There is no need to set +e as in sandeep's script. If the tar exit status is 0 or 1, this one-liner will return with exit status 0. Otherwise it will return with exit status 1. This is different from sandeep's script where the original exit status value is preserved if it is different from 1.

tar -czf sample.tar.gz dir1 dir2 || [[ $? -eq 1 ]]

How to use makefiles in Visual Studio?

The VS equivalent of a makefile is a "Solution" (over-simplified, I know).

gcc error: wrong ELF class: ELFCLASS64

I think that coreset.o was compiled for 64-bit, and you are linking it with a 32-bit computation.o.

You can try to recompile computation.c with the '-m64' flag of gcc(1)

How can I use Bash syntax in Makefile targets?

One way that also works is putting it this way in the first line of the your target:

your-target: $(eval SHELL:=/bin/bash)
    @echo "here shell is $$0"

makefile execute another target

Actually you are right: it runs another instance of make. A possible solution would be:

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : clean clearscr all

clearscr:
    clear

By calling make fresh you get first the clean target, then the clearscreen which runs clear and finally all which does the job.

EDIT Aug 4

What happens in the case of parallel builds with make’s -j option? There's a way of fixing the order. From the make manual, section 4.2:

Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites

The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).

Hence the makefile becomes

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : | clean clearscr all

clearscr:
    clear

EDIT Dec 5

It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.

log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)

install:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  command1  # this line will be a subshell
  command2  # this line will be another subshell
  @command3  # Use `@` to hide the command line
  $(call log_error, "It works, yey!")

uninstall:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  ....
  $(call log_error, "Nuked!")

How to compile makefile using MinGW?

I found a very good example here: https://bigcode.wordpress.com/2016/12/20/compiling-a-very-basic-mingw-windows-hello-world-executable-in-c-with-a-makefile/

It is a simple Hello.c (you can use c++ with g++ instead of gcc) using the MinGW on windows.

The Makefile looking like:

EXECUTABLE = src/Main.cpp

CC = "C:\MinGW\bin\g++.exe"
LDFLAGS = -lgdi32

src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)

all: myprog

myprog: $(obj)
    $(CC) -o $(EXECUTABLE) $^ $(LDFLAGS)

.PHONY: clean
clean:
    del $(obj) $(EXECUTABLE)

make: *** [ ] Error 1 error

Sometimes you will get lots of compiler outputs with many warnings and no line of output that says "error: you did something wrong here" but there was still an error. An example of this is a missing header file - the compiler says something like "no such file" but not "error: no such file", then it exits with non-zero exit code some time later (perhaps after many more warnings). Make will bomb out with an error message in these cases!

Makefile - missing separator

You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

PROG = semsearch
all: $(PROG)
%: %.c
        gcc -o $@ $< -lpthread

clean:
        rm $(PROG)

Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread

clean: ; rm $(PROG)

CFLAGS vs CPPFLAGS

The implicit make rule for compiling a C program is

%.o:%.c
    $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

where the $() syntax expands the variables. As both CPPFLAGS and CFLAGS are used in the compiler call, which you use to define include paths is a matter of personal taste. For instance if foo.c is a file in the current directory

make foo.o CPPFLAGS="-I/usr/include"
make foo.o CFLAGS="-I/usr/include"

will both call your compiler in exactly the same way, namely

gcc -I/usr/include -c -o foo.o foo.c

The difference between the two comes into play when you have multiple languages which need the same include path, for instance if you have bar.cpp then try

make bar.o CPPFLAGS="-I/usr/include"
make bar.o CFLAGS="-I/usr/include"

then the compilations will be

g++ -I/usr/include -c -o bar.o bar.cpp
g++ -c -o bar.o bar.cpp

as the C++ implicit rule also uses the CPPFLAGS variable.

This difference gives you a good guide for which to use - if you want the flag to be used for all languages put it in CPPFLAGS, if it's for a specific language put it in CFLAGS, CXXFLAGS etc. Examples of the latter type include standard compliance or warning flags - you wouldn't want to pass -std=c99 to your C++ compiler!

You might then end up with something like this in your makefile

CPPFLAGS=-I/usr/include
CFLAGS=-std=c99
CXXFLAGS=-Weffc++

How do you force a makefile to rebuild a target

make clean deletes all the already compiled object files.

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

How to install a Notepad++ plugin offline?

Here are my steps tried with NPP 7.8.2:

(1)Download the plugins zip (refer plugin-full-list json):

https://github.com/notepad-plus-plus/nppPluginList/blob/master/src/pl.x64.json

(2)Extract the files (normally .dll lib files) from zip to npp's plugins sub-folder

E.g., extract NppFTP-x64.zip into C:\Program Files\Notepad++\plugins\NppFTP

Keep in mind:

  (i)Must create sub-folder for each plugin
 (ii)The sub-folder's name must be EXACTLY SAME as the main .dll filename (e.g., NppFTP.dll)

(3)Restart npp, those plugin will be automatically loaded.

[Note-1]: I didn't do setting->import->plugin, it seems this is not required [Note-2]: You may need start npp with "run as administrator" option if you want to do import plugin.

Async/Await Class Constructor

Because async functions are promises, you can create a static function on your class which executes an async function which returns the instance of the class:

class Yql {
  constructor () {
    // Set up your class
  }

  static init () {
    return (async function () {
      let yql = new Yql()
      // Do async stuff
      await yql.build()
      // Return instance
      return yql
    }())
  }  

  async build () {
    // Do stuff with await if needed
  }
}

async function yql () {
  // Do this instead of "new Yql()"
  let yql = await Yql.init()
  // Do stuff with yql instance
}

yql()

Call with let yql = await Yql.init() from an async function.

How do I dump the data of some SQLite3 tables?

The answer by retracile should be the closest one, yet it does not work for my case. One insert query just broke in the middle and the export just stopped. Not sure what is the reason. However It works fine during .dump.

Finally I wrote a tool for the split up the SQL generated from .dump:

https://github.com/motherapp/sqlite_sql_parser/

Efficient way to update all rows in a table

What is the database version? Check out virtual columns in 11g:

Adding Columns with a Default Value http://www.oracle.com/technology/pub/articles/oracle-database-11g-top-features/11g-schemamanagement.html

How to set the thumbnail image on HTML5 video?

_x000D_
_x000D_
<video width="400" controls="controls" preload="metadata">_x000D_
  <source src="https://www.youtube.com/watch?v=Ulp1Kimblg0">_x000D_
</video>
_x000D_
_x000D_
_x000D_

How do I jump to a closing bracket in Visual Studio Code?

You can learn commands from the command palette Ctrl/Cmd + Shift + P). Look for "Go to Bracket". The keybinding is also shown there.

How do I determine the size of my array in C?

sizeof(array) / sizeof(array[0])

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

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

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

How to get a Docker container's IP address from the host

My answer:

docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} %tab% {{.Name}}' $(docker ps -aq
) | sed 's#%tab%#\t#g' | sed 's#/##g' | sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n

Also as a bash alias:

docker-ips() {   docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}} %tab% {{.Name}}' $(docker ps -aq) | sed 's#%tab%#\t#g' | sed 's#/##g' | sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n }

Output is sorted by IP address, and tab delimited:

# docker-ips
172.18.0.2       memcached
172.18.0.3       nginx
172.18.0.4       fpm-backup
172.18.0.5       dns
172.18.0.6       fpm-beta
172.18.0.7       exim
172.18.0.8       fpm-delta
172.18.0.9       mariadb
172.18.0.10      fpm-alpha
172.19.0.2       nextcloud-redis
172.19.0.3       nextcloud-db
172.19.0.4       nextcloud

What does "wrong number of arguments (1 for 0)" mean in Ruby?

I assume you called a function with an argument which was defined without taking any.

def f()
  puts "hello world"
end

f(1)   # <= wrong number of arguments (1 for 0)

How to insert table values from one database to another database?

If both the tables have the same schema then use this query: insert into database_name.table_name select * from new_database_name.new_table_name where='condition'

Replace database_name with the name of your 1st database and table_name with the name of table you want to copy from also replace new_database_name with the name of your other database where you wanna copy and new_table_name is the name of the table.

Sending HTTP POST with System.Net.WebClient

Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:

Using client As New Net.WebClient
    Dim reqparm As New Specialized.NameValueCollection
    reqparm.Add("param1", "somevalue")
    reqparm.Add("param2", "othervalue")
    Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
    Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

The key part is this:

client.UploadValues(someurl, "POST", reqparm)

It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.

How do I get the "id" after INSERT into MySQL database with Python?

Also, cursor.lastrowid (a dbapi/PEP249 extension supported by MySQLdb):

>>> import MySQLdb
>>> connection = MySQLdb.connect(user='root')
>>> cursor = connection.cursor()
>>> cursor.execute('INSERT INTO sometable VALUES (...)')
1L
>>> connection.insert_id()
3L
>>> cursor.lastrowid
3L
>>> cursor.execute('SELECT last_insert_id()')
1L
>>> cursor.fetchone()
(3L,)
>>> cursor.execute('select @@identity')
1L
>>> cursor.fetchone()
(3L,)

cursor.lastrowid is somewhat cheaper than connection.insert_id() and much cheaper than another round trip to MySQL.

Where does Jenkins store configuration files for the jobs it runs?

Am adding few things related to jenkins configuration files storage.

As per my understanding all config file stores in the machine or OS that you have installed jenkins.

The jobs you are going to create in jenkins will be stored in jenkins server and you can find the config.xml etc., here.

After jenkins installation you will find jenkins workspace in server.

*cd>jenkins/jobs/`
cd>jenkins/jobs/$ls
   job1 job2 job3 config.xml ....*

"SDK Platform Tools component is missing!"

OK, here is what I did to fix the problem:

Open Eclipse. Then:
  Window > Android SDK and AVD Manager
   > Available Packages: 
     > Android Repository:
       + Android SDK Tools, revision 8
       + Android SDK Platform-tools, revision 1

[Install Selected]

Customize Bootstrap checkboxes

As others have said, the style you're after is actually just the Mac OS checkbox style, so it will look radically different on other devices.

In fact both screenshots you linked show what checkboxes look like on Mac OS in Chrome, the grey one is shown at non-100% zoom levels.

How to log request and response body with Retrofit-Android?

Retrofit 2.0 :

UPDATE: @by Marcus Pöhls

Logging In Retrofit 2

Retrofit 2 completely relies on OkHttp for any network operation. Since OkHttp is a peer dependency of Retrofit 2, you won’t need to add an additional dependency once Retrofit 2 is released as a stable release.

OkHttp 2.6.0 ships with a logging interceptor as an internal dependency and you can directly use it for your Retrofit client. Retrofit 2.0.0-beta2 still uses OkHttp 2.5.0. Future releases will bump the dependency to higher OkHttp versions. That’s why you need to manually import the logging interceptor. Add the following line to your gradle imports within your build.gradle file to fetch the logging interceptor dependency.

compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'

You can also visit Square's GitHub page about this interceptor

Add Logging to Retrofit 2

While developing your app and for debugging purposes it’s nice to have a log feature integrated to show request and response information. Since logging isn’t integrated by default anymore in Retrofit 2, we need to add a logging interceptor for OkHttp. Luckily OkHttp already ships with this interceptor and you only need to activate it for your OkHttpClient.

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();  
// set your desired log level
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();   
// add your other interceptors …
// add logging as last interceptor
httpClient.addInterceptor(logging);  // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder()  
        .baseUrl(API_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(httpClient.build())
        .build();

We recommend to add logging as the last interceptor, because this will also log the information which you added with previous interceptors to your request.

Log Levels

Logging too much information will blow up your Android monitor, that’s why OkHttp’s logging interceptor has four log levels: NONE, BASIC, HEADERS, BODY. We’ll walk you through each of the log levels and describe their output.

further information please visit : Retrofit 2 — Log Requests and Responses

OLD ANSWER:

no logging in Retrofit 2 anymore. The development team removed the logging feature. To be honest, the logging feature wasn’t that reliable anyway. Jake Wharton explicitly stated that the logged messages or objects are the assumed values and they couldn’t be proofed to be true. The actual request which arrives at the server may have a changed request body or something else.

Even though there is no integrated logging by default, you can leverage any Java logger and use it within a customized OkHttp interceptor.

further information about Retrofit 2 please refer : Retrofit — Getting Started and Create an Android Client

Finding the average of an array using JS

var total = 0
grades.forEach(function (grade) {
    total += grade        
});
console.log(total / grades.length)

Why is list initialization (using curly braces) better than the alternatives?

There are MANY reasons to use brace initialization, but you should be aware that the initializer_list<> constructor is preferred to the other constructors, the exception being the default-constructor. This leads to problems with constructors and templates where the type T constructor can be either an initializer list or a plain old ctor.

struct Foo {
    Foo() {}

    Foo(std::initializer_list<Foo>) {
        std::cout << "initializer list" << std::endl;
    }

    Foo(const Foo&) {
        std::cout << "copy ctor" << std::endl;
    }
};

int main() {
    Foo a;
    Foo b(a); // copy ctor
    Foo c{a}; // copy ctor (init. list element) + initializer list!!!
}

Assuming you don't encounter such classes there is little reason not to use the intializer list.

List of enum values in java

Yes it is definitely possible, but you will have to do

List<MyEnum> al = new ArrayList<MyEnum>();

You can then add elements to al: al.add(ONE) or al.add(TWO).

Java: how to initialize String[]?

String[] args = new String[]{"firstarg", "secondarg", "thirdarg"};

Opposite of append in jquery

What you also should consider, is keeping a reference to the created element, then you can easily remove it specificly:

   var newUL = $('<ul><li>test</li></ul>');
   $(this).append(newUL);

   // Later ...

   newUL.remove();

Integration Testing POSTing an entire object to Spring MVC controller

I had the same question and it turned out the solution was fairly simple, by using JSON marshaller.
Having your controller just change the signature by changing @ModelAttribute("newObject") to @RequestBody. Like this:

@Controller
@RequestMapping(value = "/somewhere/new")
public class SomewhereController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(@RequestBody NewObject newObject) {
        // ...
    }
}

Then in your tests you can simply say:

NewObject newObjectInstance = new NewObject();
// setting fields for the NewObject  

mockMvc.perform(MockMvcRequestBuilders.post(uri)
  .content(asJsonString(newObjectInstance))
  .contentType(MediaType.APPLICATION_JSON)
  .accept(MediaType.APPLICATION_JSON));

Where the asJsonString method is just:

public static String asJsonString(final Object obj) {
    try {
        final ObjectMapper mapper = new ObjectMapper();
        final String jsonContent = mapper.writeValueAsString(obj);
        return jsonContent;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}  

Displaying standard DataTables in MVC

Here is the answer in Razor syntax

 <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach(System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>

How to style components using makeStyles and still have lifecycle methods in Material UI?

Another one solution can be used for class components - just override default MUI Theme properties with MuiThemeProvider. This will give more flexibility in comparison with other methods - you can use more than one MuiThemeProvider inside your parent component.

simple steps:

  1. import MuiThemeProvider to your class component
  2. import createMuiTheme to your class component
  3. create new theme
  4. wrap target MUI component you want to style with MuiThemeProvider and your custom theme

please, check this doc for more details: https://material-ui.com/customization/theming/

_x000D_
_x000D_
import React from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';

import { MuiThemeProvider } from '@material-ui/core/styles';
import { createMuiTheme } from '@material-ui/core/styles';

const InputTheme = createMuiTheme({
    overrides: {
        root: {
            background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
            border: 0,
            borderRadius: 3,
            boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
            color: 'white',
            height: 48,
            padding: '0 30px',
        },
    }
});

class HigherOrderComponent extends React.Component {

    render(){
        const { classes } = this.props;
        return (
            <MuiThemeProvider theme={InputTheme}>
                <Button className={classes.root}>Higher-order component</Button>
            </MuiThemeProvider>
        );
    }
}

HigherOrderComponent.propTypes = {
    classes: PropTypes.object.isRequired,
};

export default HigherOrderComponent;
_x000D_
_x000D_
_x000D_

In C#, what's the difference between \n and \r\n?

Basically comes down to Windows standard: \r\n and Unix based systems using: \n

http://en.wikipedia.org/wiki/Newline

Unix command to find lines common in two files

While

grep -v -f 1.txt 2.txt > 3.txt

gives you the differences of two files (what is in 2.txt and not in 1.txt), you could easily do a

grep -f 1.txt 2.txt > 3.txt

to collect all common lines, which should provide an easy solution to your problem. If you have sorted files, you should take comm nonetheless. Regards!

Catching multiple exception types in one catch block

As of PHP 7.1,

catch( AError | BError $e )
{
    handler1( $e )
}

interestingly, you can also:

catch( AError | BError $e )
{
    handler1( $e )
} catch (CError $e){
    handler2($e);
} catch(Exception $e){
    handler3($e);
}

and in earlier versions of PHP:

catch(Exception $ex){
    if($ex instanceof AError){
        //handle a AError
    } elseif($ex instanceof BError){
        //handle a BError
    } else {
       throw $ex;//an unknown exception occured, throw it further
    }
}

Location of ini/config files in linux/unix?

  1. Generally system/global config is stored somewhere under /etc.
  2. User-specific config is stored in the user's home directory, often as a hidden file, sometimes as a hidden directory containing non-hidden files (and possibly more subdirectories).

Generally speaking, command line options will override environment variables which will override user defaults which will override system defaults.

What do 'real', 'user' and 'sys' mean in the output of time(1)?

Minimal runnable POSIX C examples

To make things more concrete, I want to exemplify a few extreme cases of time with some minimal C test programs.

All programs can be compiled and run with:

gcc -ggdb3 -o main.out -pthread -std=c99 -pedantic-errors -Wall -Wextra main.c
time ./main.out

and have been tested in Ubuntu 18.10, GCC 8.2.0, glibc 2.28, Linux kernel 4.18, ThinkPad P51 laptop, Intel Core i7-7820HQ CPU (4 cores / 8 threads), 2x Samsung M471A2K43BB1-CRC RAM (2x 16GiB).

sleep

Non-busy sleep does not count in either user or sys, only real.

For example, a program that sleeps for a second:

#define _XOPEN_SOURCE 700
#include <stdlib.h>
#include <unistd.h>

int main(void) {
    sleep(1);
    return EXIT_SUCCESS;
}

GitHub upstream.

outputs something like:

real    0m1.003s
user    0m0.001s
sys     0m0.003s

The same holds for programs blocked on IO becoming available.

For example, the following program waits for the user to enter a character and press enter:

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

int main(void) {
    printf("%c\n", getchar());
    return EXIT_SUCCESS;
}

GitHub upstream.

And if you wait for about one second, it outputs just like the sleep example something like:

real    0m1.003s
user    0m0.001s
sys     0m0.003s

For this reason time can help you distinguish between CPU and IO bound programs: What do the terms "CPU bound" and "I/O bound" mean?

Multiple threads

The following example does niters iterations of useless purely CPU-bound work on nthreads threads:

#define _XOPEN_SOURCE 700
#include <assert.h>
#include <inttypes.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

uint64_t niters;

void* my_thread(void *arg) {
    uint64_t *argument, i, result;
    argument = (uint64_t *)arg;
    result = *argument;
    for (i = 0; i < niters; ++i) {
        result = (result * result) - (3 * result) + 1;
    }
    *argument = result;
    return NULL;
}

int main(int argc, char **argv) {
    size_t nthreads;
    pthread_t *threads;
    uint64_t rc, i, *thread_args;

    /* CLI args. */
    if (argc > 1) {
        niters = strtoll(argv[1], NULL, 0);
    } else {
        niters = 1000000000;
    }
    if (argc > 2) {
        nthreads = strtoll(argv[2], NULL, 0);
    } else {
        nthreads = 1;
    }
    threads = malloc(nthreads * sizeof(*threads));
    thread_args = malloc(nthreads * sizeof(*thread_args));

    /* Create all threads */
    for (i = 0; i < nthreads; ++i) {
        thread_args[i] = i;
        rc = pthread_create(
            &threads[i],
            NULL,
            my_thread,
            (void*)&thread_args[i]
        );
        assert(rc == 0);
    }

    /* Wait for all threads to complete */
    for (i = 0; i < nthreads; ++i) {
        rc = pthread_join(threads[i], NULL);
        assert(rc == 0);
        printf("%" PRIu64 " %" PRIu64 "\n", i, thread_args[i]);
    }

    free(threads);
    free(thread_args);
    return EXIT_SUCCESS;
}

GitHub upstream + plot code.

Then we plot wall, user and sys as a function of the number of threads for a fixed 10^10 iterations on my 8 hyperthread CPU:

enter image description here

Plot data.

From the graph, we see that:

  • for a CPU intensive single core application, wall and user are about the same

  • for 2 cores, user is about 2x wall, which means that the user time is counted across all threads.

    user basically doubled, and while wall stayed the same.

  • this continues up to 8 threads, which matches my number of hyperthreads in my computer.

    After 8, wall starts to increase as well, because we don't have any extra CPUs to put more work in a given amount of time!

    The ratio plateaus at this point.

Note that this graph is only so clear and simple because the work is purely CPU-bound: if it were memory bound, then we would get a fall in performance much earlier with less cores because the memory accesses would be a bottleneck as shown at What do the terms "CPU bound" and "I/O bound" mean?

Quickly checking that wall < user is a simple way to determine that a program is multithreaded, and the closer that ratio is to the number of cores, the more effective the parallelization is, e.g.:

Sys heavy work with sendfile

The heaviest sys workload I could come up with was to use the sendfile, which does a file copy operation on kernel space: Copy a file in a sane, safe and efficient way

So I imagined that this in-kernel memcpy will be a CPU intensive operation.

First I initialize a large 10GiB random file with:

dd if=/dev/urandom of=sendfile.in.tmp bs=1K count=10M

Then run the code:

#define _GNU_SOURCE
#include <assert.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char *source_path, *dest_path;
    int source, dest;
    struct stat stat_source;
    if (argc > 1) {
        source_path = argv[1];
    } else {
        source_path = "sendfile.in.tmp";
    }
    if (argc > 2) {
        dest_path = argv[2];
    } else {
        dest_path = "sendfile.out.tmp";
    }
    source = open(source_path, O_RDONLY);
    assert(source != -1);
    dest = open(dest_path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
    assert(dest != -1);
    assert(fstat(source, &stat_source) != -1);
    assert(sendfile(dest, source, 0, stat_source.st_size) != -1);
    assert(close(source) != -1);
    assert(close(dest) != -1);
    return EXIT_SUCCESS;
}

GitHub upstream.

which gives basically mostly system time as expected:

real    0m2.175s
user    0m0.001s
sys     0m1.476s

I was also curious to see if time would distinguish between syscalls of different processes, so I tried:

time ./sendfile.out sendfile.in1.tmp sendfile.out1.tmp &
time ./sendfile.out sendfile.in2.tmp sendfile.out2.tmp &

And the result was:

real    0m3.651s
user    0m0.000s
sys     0m1.516s

real    0m4.948s
user    0m0.000s
sys     0m1.562s

The sys time is about the same for both as for a single process, but the wall time is larger because the processes are competing for disk read access likely.

So it seems that it does in fact account for which process started a given kernel work.

Bash source code

When you do just time <cmd> on Ubuntu, it use the Bash keyword as can be seen from:

type time

which outputs:

time is a shell keyword

So we grep source in the Bash 4.19 source code for the output string:

git grep '"user\b'

which leads us to execute_cmd.c function time_command, which uses:

  • gettimeofday() and getrusage() if both are available
  • times() otherwise

all of which are Linux system calls and POSIX functions.

GNU Coreutils source code

If we call it as:

/usr/bin/time

then it uses the GNU Coreutils implementation.

This one is a bit more complex, but the relevant source seems to be at resuse.c and it does:

  • a non-POSIX BSD wait3 call if that is available
  • times and gettimeofday otherwise

How to execute a stored procedure inside a select query

Thanks @twoleggedhorse.

Here is the solution.

  1. First we created a function

    CREATE FUNCTION GetAIntFromStoredProc(@parm Nvarchar(50)) RETURNS INTEGER
    
    AS
    BEGIN
       DECLARE @id INTEGER
    
       set @id= (select TOP(1) id From tbl where col=@parm)
    
       RETURN @id
    END
    
  2. then we do the select query

    Select col1, col2, col3,
    GetAIntFromStoredProc(T.col1) As col4
    From Tbl as T
    Where col2=@parm
    

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

In my experience, this message occurs when the primary file (.mdf) has no space to save the metadata of the database. This file include the system tables and they only save their data into it.

Make some space in the file and the commands works again. That's all, Enjoy

Using setattr() in python

You are setting self.name to the string "get_thing", not the function get_thing.

If you want self.name to be a function, then you should set it to one:

setattr(self, 'name', self.get_thing)

However, that's completely unnecessary for your other code, because you could just call it directly:

value_returned = self.get_thing()

Search for "does-not-contain" on a DataFrame in pandas

I was having trouble with the not (~) symbol as well, so here's another way from another StackOverflow thread:

df[df["col"].str.contains('this|that')==False]

What is the &#xA; character?

&#xA; is the HTML representation in hex of a line feed character. It represents a new line on Unix and Unix-like (for example) operating systems.

You can find a list of such characters at (for example) http://la.remifa.so/unicode/latin1.html

How do I import a specific version of a package using go get?

dep is the official experiment for dependency management for Go language. It requires Go 1.8 or newer to compile.

To start managing dependencies using dep, run the following command from your project's root directory:

dep init

After execution two files will be generated: Gopkg.toml ("manifest"), Gopkg.lock and necessary packages will be downloaded into vendor directory.

Let's assume that you have the project which uses github.com/gorilla/websocket package. dep will generate following files:

Gopkg.toml

# Gopkg.toml example
#
# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
# for detailed Gopkg.toml documentation.
#
# required = ["github.com/user/thing/cmd/thing"]
# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
#
# [[constraint]]
#   name = "github.com/user/project"
#   version = "1.0.0"
#
# [[constraint]]
#   name = "github.com/user/project2"
#   branch = "dev"
#   source = "github.com/myfork/project2"
#
# [[override]]
#  name = "github.com/x/y"
#  version = "2.4.0"


[[constraint]]
  name = "github.com/gorilla/websocket"
  version = "1.2.0"

Gopkg.lock

# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.


[[projects]]
  name = "github.com/gorilla/websocket"
  packages = ["."]
  revision = "ea4d1f681babbce9545c9c5f3d5194a789c89f5b"
  version = "v1.2.0"

[solve-meta]
  analyzer-name = "dep"
  analyzer-version = 1
  inputs-digest = "941e8dbe52e16e8a7dff4068b7ba53ae69a5748b29fbf2bcb5df3a063ac52261"
  solver-name = "gps-cdcl"
  solver-version = 1

There are commands which help you to update/delete/etc packages, please find more info on official github repo of dep (dependency management tool for Go).

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

@Drewid's answer didn't work in my Firefox 25 if the flash plugin is just disabled but installed.

@invertedSpear's comment in that answer worked in firefox but not in any IE version.

So combined both their code and got this. Tested in Google Chrome 31, Firefox 25, IE 8-10. Thanks Drewid and invertedSpear :)

var hasFlash = false;
try {
  var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
  if (fo) {
    hasFlash = true;
  }
} catch (e) {
  if (navigator.mimeTypes
        && navigator.mimeTypes['application/x-shockwave-flash'] != undefined
        && navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
    hasFlash = true;
  }
}

Android studio takes too much memory

I don't know if it is a solution but Invalidate Cache and Restart solved this problem in my case. I am currently using Android Studio 3.6

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

http://en.wikipedia.org/wiki/Visual_C++

You are using Visual C++ 2012 which is v110. v120 means Visual C++ 2013.

So either you change the project settings to use toolset v110, or you install Visual Studio 2013 on this machine and use VS2013 to compile it.

UICollectionView Set number of columns

I implemented UICollectionViewDelegateFlowLayout on my UICollectionViewController and override the method responsible for determining the size of the Cell. I then took the screen width and divided it with my column requirement. For example, I wanted to have 3 columns on each screen size. So here's what my code looks like -

- (CGSize)collectionView:(UICollectionView *)collectionView
                  layout:(UICollectionViewLayout *)collectionViewLayout
  sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    float cellWidth = screenWidth / 3.0; //Replace the divisor with the column count requirement. Make sure to have it in float.
    CGSize size = CGSizeMake(cellWidth, cellWidth);

    return size;
}

With CSS, how do I make an image span the full width of the page as a background image?

Background images, ideally, are always done with CSS. All other images are done with html. This will span the whole background of your site.

body {
  background: url('../images/cat.ong');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

Print in new line, java

\n creates a new line in Java. Don't use spaces before or after \n.

Example: printing It creates\na new line outputs

It creates
a new line.

How do I integrate Ajax with Django applications?

I have tried to use AjaxableResponseMixin in my project, but had ended up with the following error message:

ImproperlyConfigured: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.

That is because the CreateView will return a redirect response instead of returning a HttpResponse when you to send JSON request to the browser. So I have made some changes to the AjaxableResponseMixin. If the request is an ajax request, it will not call the super.form_valid method, just call the form.save() directly.

from django.http import JsonResponse
from django import forms
from django.db import models

class AjaxableResponseMixin(object):
    success_return_code = 1
    error_return_code = 0
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            form.errors.update({'result': self.error_return_code})
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        if self.request.is_ajax():
            self.object = form.save()
            data = {
                'result': self.success_return_code
            }
            return JsonResponse(data)
        else:
            response = super(AjaxableResponseMixin, self).form_valid(form)
            return response

class Product(models.Model):
    name = models.CharField('product name', max_length=255)

class ProductAddForm(forms.ModelForm):
    '''
    Product add form
    '''
    class Meta:
        model = Product
        exclude = ['id']


class PriceUnitAddView(AjaxableResponseMixin, CreateView):
    '''
    Product add view
    '''
    model = Product
    form_class = ProductAddForm

Reading from a text file and storing in a String

How can we read data from a text file and store in a String Variable?

Err, read data from the file and store it in a String variable. It's just code. Not a real question so far.

Is it possible to pass the filename in a method and it would return the String which is the text from the file.

Yes it's possible. It's also a very bad idea. You should deal with the file a part at a time, for example a line at a time. Reading the entire file into memory before you process any of it adds latency; wastes memory; and assumes that the entire file will fit into memory. One day it won't. You don't want to do it this way.

Using JQuery hover with HTML image map

I found this wonderful mapping script (mapper.js) that I have used in the past. What's different about it is you can hover over the map or a link on your page to make the map area highlight. Sadly it's written in javascript and requires a lot of in-line coding in the HTML - I would love to see this script ported over to jQuery :P

Also, check out all the demos! I think this example could almost be made into a simple online game (without using flash) - make sure you click on the different camera angles.

Why does "npm install" rewrite package-lock.json?

Use the newly introduced

npm ci

npm ci promises the most benefit to large teams. Giving developers the ability to “sign off” on a package lock promotes more efficient collaboration across large teams, and the ability to install exactly what is in a lockfile has the potential to save tens if not hundreds of developer hours a month, freeing teams up to spend more time building and shipping amazing things.

Introducing npm ci for faster, more reliable builds

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

For me, I tried all the solutions but I was thinking to set height for UITableView section and it's working for me.(Using swift)

 func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }

Spring Boot + JPA : Column name annotation ignored

By default Spring uses org.springframework.boot.orm.jpa.SpringNamingStrategy to generate table names. This is a very thin extension of org.hibernate.cfg.ImprovedNamingStrategy. The tableName method in that class is passed a source String value but it is unaware if it comes from a @Column.name attribute or if it has been implicitly generated from the field name.

The ImprovedNamingStrategy will convert CamelCase to SNAKE_CASE where as the EJB3NamingStrategy just uses the table name unchanged.

If you don't want to change the naming strategy you could always just specify your column name in lowercase:

@Column(name="testname")

Left align and right align within div in Bootstrap

Instead of using pull-right class, it is better to use text-right class in the column, because pull-right creates problems sometimes while resizing the page.

How to configure welcome file list in web.xml

Its based on from which file you are trying to access those files.

If it is in the same folder where your working project file is, then you can use just the file name. no need of path.

If it is in the another folder which is under the same parent folder of your working project file then you can use location like in the following /javascript/sample.js

In your example if you are trying to access your js file from your html file you can use the following location

../javascript/sample.js

the prefix../ will go to the parent folder of the file(Folder upward journey)

set gvim font in .vimrc file

Although this is an old thread I thought that I would add a comment as I have come across it whilst trying to solve a similar issue; this might help anyone else who may find themselves here:

The backslash character is used to ignore the next character; once added to the font name in my gvimrc it worked; I am on a GNU/Linux machine which does not like spaces. I suspect that the initial post was an error due to the back slash being used on a windows machine.

In example:

:set guifont?  ## From gvim command, would give the following:

set guifont=DejaVu Sans Mono for Powerline 11

Where as I needed to add this line to the gvimrc file for it to be read:

set guifont=DejaVu\ Sans\ Mono\ for\ Powerline\ 11

How to check if a function exists on a SQL database

This is what SSMS uses when you script using the DROP and CREATE option

IF EXISTS (SELECT *
           FROM   sys.objects
           WHERE  object_id = OBJECT_ID(N'[dbo].[foo]')
                  AND type IN ( N'FN', N'IF', N'TF', N'FS', N'FT' ))
  DROP FUNCTION [dbo].[foo]

GO 

This approach to deploying changes means that you need to recreate all permissions on the object so you might consider ALTER-ing if Exists instead.

A warning - comparison between signed and unsigned integer expressions

At the extreme ranges, an unsigned int can become larger than an int.
Therefore, the compiler generates a warning. If you are sure that this is not a problem, feel free to cast the types to the same type so the warning disappears (use C++ cast so that they are easy to spot).

Alternatively, make the variables the same type to stop the compiler from complaining.
I mean, is it possible to have a negative padding? If so then keep it as an int. Otherwise you should probably use unsigned int and let the stream catch the situations where the user types in a negative number.

Python - IOError: [Errno 13] Permission denied:

It looks like you're trying to replace the extension with the following code:

if (myFile[-4:] == ".asm"):
    newFile = myFile[:4]+".hack"

However, you appear to have the array indexes mixed up. Try the following:

if (myFile[-4:] == ".asm"):
    newFile = myFile[:-4]+".hack"

Note the use of -4 instead of just 4 in the second line of code. This explains why your program is trying to create /Use.hack, which is the first four characters of your file name (/Use), with .hack appended to it.

How to get object length

Can be done easily with $.map():

var len = $.map(a, function(n, i) { return i; }).length;

Fast query runs slow in SSRS

I had the same problem, here is my description of the problem

"I created a store procedure which would generate 2200 Rows and would get executed in almost 2 seconds however after calling the store procedure from SSRS 2008 and run the report it actually never ran and ultimately I have to kill the BIDS (Business Intelligence development Studio) from task manager".

What I Tried: I tried running the SP from reportuser Login but SP was running normal for that user as well, I checked Profiler but nothing worked out.

Solution:

Actually the problem is that even though SP is generating the result but SSRS engine is taking time to read these many rows and render it back. So I added WITH RECOMPILE option in SP and ran the report .. this is when miracle happened and my problem got resolve.

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

Make sure of that you have installed ruby with --disable-binary option, if not, uninstall it and reinstall it with the option.

more info here

Difference between except: and except Exception as e: in Python

There are differences with some exceptions, e.g. KeyboardInterrupt.

Reading PEP8:

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

PHP foreach loop key value

As Pekka stated above

foreach ($array as $key => $value)

Also you might want to try a recursive function

displayRecursiveResults($site);

function displayRecursiveResults($arrayObject) {
    foreach($arrayObject as $key=>$data) {
        if(is_array($data)) {
            displayRecursiveResults($data);
        } elseif(is_object($data)) {
            displayRecursiveResults($data);
        } else {
            echo "Key: ".$key." Data: ".$data."<br />";
        }
    }
}

Programmatically stop execution of python script?

sys.exit() will do exactly what you want.

import sys
sys.exit("Error message")

How to open URL in Microsoft Edge from the command line?

The following method should work via Command Prompt (cmd):

start microsoft-edge:http://www.cnn.com

CSS3 equivalent to jQuery slideUp and slideDown?

You could do something like this:

#youritem .fade.in {
    animation-name: fadeIn;
}

#youritem .fade.out {
    animation-name: fadeOut;
}

@keyframes fadeIn {
    0% {
        opacity: 0;
        transform: translateY(startYposition);
    } 
    100% {
        opacity: 1;
        transform: translateY(endYposition);
    }
}

@keyframes fadeOut {
    0% {
        opacity: 1;
        transform: translateY(startYposition);
    } 
    100% {
        opacity: 0;
        transform: translateY(endYposition);
    }
}

Example - Slide and Fade:

This slides and animates the opacity - not based on height of the container, but on the top/coordinate. View example

Example - Auto-height/No Javascript: Here is a live sample, not needing height - dealing with automatic height and no javascript.
View example

$(window).scrollTop() vs. $(document).scrollTop()

First, you need to understand the difference between window and document. The window object is a top level client side object. There is nothing above the window object. JavaScript is an object orientated language. You start with an object and apply methods to its properties or the properties of its object groups. For example, the document object is an object of the window object. To change the document's background color, you'd set the document's bgcolor property.

window.document.bgcolor = "red" 

To answer your question, There is no difference in the end result between window and document scrollTop. Both will give the same output.

Check working example at http://jsfiddle.net/7VRvj/6/

In general use document mainly to register events and use window to do things like scroll, scrollTop, and resize.

How to Detect if I'm Compiling Code with a particular Visual Studio version?

In visual studio, go to help | about and look at the version of Visual Studio that you're using to compile your app.

Convert a CERT/PEM certificate to a PFX certificate

openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx

Search for executable files using find command

It is SO ridiculous that this is not super-easy... let alone next to impossible. Hands up, I defer to Apple/Spotlight...

mdfind 'kMDItemContentType=public.unix-executable'

At least it works!

How to find the location of the Scheduled Tasks folder

I want to extend @Jan answer:

It's seems, that Task Scheduler 1.0 API uses C:\Windows\Tasks folder for create and enumerate tasks (this example), while Task Scheduler 2.0 API uses C:\Windows\System32\Tasks to create and enumerate tasks (this example).

It's also seems, that windows console utility schtasks and GUI utility taskschd.msc uses Task Scheduler 2.0 API.

P.S. I found, that if task placed in C:\Windows\Tasks and have not set AccountInformation, then task won't be displayed in windows console and GUI schedulers. If you set AccountInformation (even "" for SYSTEM account) and set flag TASK_FLAG_RUN_ONLY_IF_LOGGED_ON - task will be displayed in all standard applications.

Solution found here

Set a persistent environment variable from cmd.exe

:: Sets environment variables for both the current `cmd` window 
::   and/or other applications going forward.
:: I call this file keyz.cmd to be able to just type `keyz` at the prompt 
::   after changes because the word `keys` is already taken in Windows.

@echo off

:: set for the current window
set APCA_API_KEY_ID=key_id
set APCA_API_SECRET_KEY=secret_key
set APCA_API_BASE_URL=https://paper-api.alpaca.markets

:: setx also for other windows and processes going forward
setx APCA_API_KEY_ID     %APCA_API_KEY_ID%
setx APCA_API_SECRET_KEY %APCA_API_SECRET_KEY%
setx APCA_API_BASE_URL   %APCA_API_BASE_URL%

:: Displaying what was just set.
set apca

:: Or for copy/paste manually ...
:: setx APCA_API_KEY_ID     'key_id'
:: setx APCA_API_SECRET_KEY 'secret_key'
:: setx APCA_API_BASE_URL   'https://paper-api.alpaca.markets'

Entity Framework : How do you refresh the model when the db changes?

Are you looking at the designer or code view? You can force the designer to open by right clicking on your EDMX file and selecting Open With -> ADO.NET Entity Data Model Designer

Right click on the designer surface of the EDMX designer and click Update Model From Database...

All entities are refreshed by default, new entities are only added if you select them.


EDIT: If it is not refreshing well.

  • Select all the tables and view-s in the EDMX designer.
  • Delete them.
  • Then, update model from database

How do I generate a random number between two variables that I have stored?

To generate a random number between min and max, use:

int randNum = rand()%(max-min + 1) + min;

(Includes max and min)

c# - How to get sum of the values from List?

How about this?

List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();

How can I know which radio button is selected via jQuery?

To retrieve all radio buttons values in JavaScript array use following jQuery code :

var values = jQuery('input:checkbox:checked.group1').map(function () {
    return this.value;
}).get();

How to find where gem files are installed

This works and gives you the installed at path for each gem. This super helpful when trying to do multi-stage docker builds.. You can copy in the specific directory post-bundle install.

bash-4.4# gem list -d

Output::

aasm (5.0.6)
    Authors: Thorsten Boettger, Anil Maurya
    Homepage: https://github.com/aasm/aasm
    License: MIT
    Installed at: /usr/local/bundle

  State machine mixin for Ruby objects

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

You can do something like this :

<asp:Button ID="Button1" runat="server" Text="Button"
    onclick="Button1_Click" OnClientClick="document.forms[0].target = '_blank';" />

Correct way to load a Nib for a UIView subclass

In Swift:

For example, name of your custom class is InfoView

At first, you create files InfoView.xib and InfoView.swiftlike this:

import Foundation
import UIKit

class InfoView: UIView {
    class func instanceFromNib() -> UIView {
    return UINib(nibName: "InfoView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
}

Then set File's Owner to UIViewController like this:

enter image description here

Rename your View to InfoView:

enter image description here

Right-click to File's Owner and connect your view field with your InfoView:

enter image description here

Make sure that class name is InfoView:

enter image description here

And after this you can add the action to button in your custom class without any problem:

enter image description here

And usage of this custom class in your MainViewController:

func someMethod() {
    var v = InfoView.instanceFromNib()
    v.frame = self.view.bounds
    self.view.addSubview(v)
}

Converting datetime.date to UTC timestamp in Python

I defined my own two functions

  • utc_time2datetime(utc_time, tz=None)
  • datetime2utc_time(datetime)

here:

import time
import datetime
from pytz import timezone
import calendar
import pytz


def utc_time2datetime(utc_time, tz=None):
    # convert utc time to utc datetime
    utc_datetime = datetime.datetime.fromtimestamp(utc_time)

    # add time zone to utc datetime
    if tz is None:
        tz_datetime = utc_datetime.astimezone(timezone('utc'))
    else:
        tz_datetime = utc_datetime.astimezone(tz)

    return tz_datetime


def datetime2utc_time(datetime):
    # add utc time zone if no time zone is set
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=timezone('utc'))

    # convert to utc time zone from whatever time zone the datetime is set to
    utc_datetime = datetime.astimezone(timezone('utc')).replace(tzinfo=None)

    # create a time tuple from datetime
    utc_timetuple = utc_datetime.timetuple()

    # create a time element from the tuple an add microseconds
    utc_time = calendar.timegm(utc_timetuple) + datetime.microsecond / 1E6

    return utc_time

Using ChildActionOnly in MVC

A little late to the party, but...

The other answers do a good job of explaining what effect the [ChildActionOnly] attribute has. However, in most examples, I kept asking myself why I'd create a new action method just to render a partial view, within another view, when you could simply render @Html.Partial("_MyParialView") directly in the view. It seemed like an unnecessary layer. However, as I investigated, I found that one benefit is that the child action can create a different model and pass that to the partial view. The model needed for the partial might not be available in the model of the view in which the partial view is being rendered. Instead of modifying the model structure to get the necessary objects/properties there just to render the partial view, you can call the child action and have the action method take care of creating the model needed for the partial view.

This can come in handy, for example, in _Layout.cshtml. If you have a few properties common to all pages, one way to accomplish this is use a base view model and have all other view models inherit from it. Then, the _Layout can use the base view model and the common properties. The downside (which is subjective) is that all view models must inherit from the base view model to guarantee that those common properties are always available. The alternative is to render @Html.Action in those common places. The action method would create a separate model needed for the partial view common to all pages, which would not impact the model for the "main" view. In this alternative, the _Layout page need not have a model. It follows that all other view models need not inherit from any base view model.

I'm sure there are other reasons to use the [ChildActionOnly] attribute, but this seems like a good one to me, so I thought I'd share.

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

System.MissingMethodException: Method not found?

Just in case it helps anyone, although it's an old issue, my problem was a bit odd.

I had this error while using Jenkins.

Eventually found out that the system date was manually set to a future date, which caused dll to be compiled with that future date. When the date was set back to normal, MSBuild interpreted that the file was newer and didn't require recompile of the project.

Open two instances of a file in a single Visual Studio session

Luke's answer didn't work for me. The 'New Window' command was already listed in the customize settings, but not showing up in the .js tabs context menu, despite deleting the registry setting.

So I used:

Tools

Customize...

Keyboard...

Scroll down to select Window.NewWindow

And I pressed and assigned the shortcut keys, Ctrl + Shift + W.

That worked for me.

==== EDIT ====

Well, 'worked' was too strong. My keyboard shortcut does indeed open another tab on the same JavaScript file, but rather unhelpfully it does not render the contents; it is just an empty white window! You may have better luck.

How to leave space in HTML

After, or in-between your text, use the &nbsp; (non-breaking space) extended HTML character.

  • EG 1 :

    This is an example paragraph. &nbsp;&nbsp; This is the next line.

How to substring in jquery

Standard javascript will do that using the following syntax:

string.substring(from, to)

var name = "nameGorge";
var output = name.substring(4);

Read more here: http://www.w3schools.com/jsref/jsref_substring.asp

Flutter: how to make a TextField with HintText but no Underline?

change the focused border to none

TextField(
      decoration: new InputDecoration(
          border: InputBorder.none,
          focusedBorder: InputBorder.none,
          contentPadding: EdgeInsets.only(left: 15, bottom: 11, top: 11, right: 15),
          hintText: 'Subject'
      ),
    ),

How to override and extend basic Django admin templates?

As for Django 1.8 being the current release, there is no need to symlink, copy the admin/templates to your project folder, or install middlewares as suggested by the answers above. Here is what to do:

  1. create the following tree structure(recommended by the official documentation)

    your_project
         |-- your_project/
         |-- myapp/
         |-- templates/
              |-- admin/
                  |-- myapp/
                      |-- change_form.html  <- do not misspell this
    

Note: The location of this file is not important. You can put it inside your app and it will still work. As long as its location can be discovered by django. What's more important is the name of the HTML file has to be the same as the original HTML file name provided by django.

  1. Add this template path to your settings.py:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')], # <- add this line
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
  2. Identify the name and block you want to override. This is done by looking into django's admin/templates directory. I am using virtualenv, so for me, the path is here:

    ~/.virtualenvs/edge/lib/python2.7/site-packages/django/contrib/admin/templates/admin
    

In this example, I want to modify the add new user form. The template responsiblve for this view is change_form.html. Open up the change_form.html and find the {% block %} that you want to extend.

  1. In your change_form.html, write somethings like this:

    {% extends "admin/change_form.html" %}
    {% block field_sets %}
         {# your modification here #}
    {% endblock %}
    
  2. Load up your page and you should see the changes

jQuery animated number counter from zero to value

This worked for me

HTML CODE

<span class="number-count">841</span>

jQuery Code

$('.number-count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });

How to solve Permission denied (publickey) error when using Git?

On Windows, make sure all your apps agree on HOME. Msys will surprisingly NOT do it for you. I had to set an environment variable because ssh and git couldn't seem to agree on where my .ssh directory was.

DataGridView changing cell background color

Simply create a new DataGridViewCellStyle object, set its back color and then assign the cell's style to it:

    DataGridViewCellStyle style = new DataGridViewCellStyle();
    style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor);
    style.ForeColor = Color.Black;
    row.Cells[color.Index].Style = style;

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

You have two records in your json file, and json.loads() is not able to decode more than one. You need to do it record by record.

See Python json.loads shows ValueError: Extra data

OR you need to reformat your json to contain an array:

{
    "foo" : [
       {"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
       {"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
    ]
}

would be acceptable again. But there cannot be several top level objects.

Computing cross-correlation function?

To cross-correlate 1d arrays use numpy.correlate.

For 2d arrays, use scipy.signal.correlate2d.

There is also scipy.stsci.convolve.correlate2d.

There is also matplotlib.pyplot.xcorr which is based on numpy.correlate.

See this post on the SciPy mailing list for some links to different implementations.

Edit: @user333700 added a link to the SciPy ticket for this issue in a comment.

javac not working in windows command prompt

Windows OS searches the current directory and the directories listed in the PATH environment variable for executable programs. JDK's programs (such as Java compiler javac.exe and Java runtime java.exe) reside in directory "\bin" (where denotes the JDK installed directory, e.g., C:\Program Files\Java\jdk1.8.0_xx). You need to include the "\bin" directory in the PATH.

To edit the PATH environment variable in Windows XP/Vista/7/8:

  1. Control Panel ? System ? Advanced system settings

  2. Switch to "Advanced" tab ? Environment Variables

  3. In "System Variables", scroll down to select "PATH" ? Edit

(( now read the following 3 times before proceeding, THERE IS NO UNDO ))

In "Variable value" field, INSERT "c:\Program Files\Java\jdk1.8.0_xx\bin" (Replace xx with the upgrade number and VERIFY that this is your JDK's binary directory!!!) IN FRONT of all the existing directories, followed by a semi-colon (;) which separates the JDK's binary directory from the rest of the existing directories. DO NOT DELETE any existing entries; otherwise, some existing applications may not run.

Variable name  : PATH
Variable value : c:\Program Files\Java\jdk1.8.0_xx\bin;[existing entries...]

Screenshot

Is it correct to use alt tag for an anchor link?

For anchors, you should use title instead. alt is not valid atribute of a. See http://w3schools.com/tags/tag_a.asp

How to use ConfigurationManager

I found some answers, but I don't know if it is the right way.This is my solution for now. Fortunatelly it didn´t broke my design mode.

    `
    /// <summary>
    /// set config, if key is not in file, create
    /// </summary>
    /// <param name="key">Nome do parâmetro</param>
    /// <param name="value">Valor do parâmetro</param>
    public static void SetConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// Get key value, if not found, return null
    /// </summary>
    /// <param name="key"></param>
    /// <returns>null if key is not found, else string with value</returns>
    public static string GetConfig(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }`

How do you performance test JavaScript code?

Here is a reusable class for time performance. Example is included in code:

/*
     Help track time lapse - tells you the time difference between each "check()" and since the "start()"

 */
var TimeCapture = function () {
    var start = new Date().getTime();
    var last = start;
    var now = start;
    this.start = function () {
        start = new Date().getTime();
    };
    this.check = function (message) {
        now = (new Date().getTime());
        console.log(message, 'START:', now - start, 'LAST:', now - last);
        last = now;
    };
};

//Example:
var time = new TimeCapture();
//begin tracking time
time.start();
//...do stuff
time.check('say something here')//look at your console for output
//..do more stuff
time.check('say something else')//look at your console for output
//..do more stuff
time.check('say something else one more time')//look at your console for output

Return multiple values in JavaScript?

Just return an object literal

function newCodes(){
    var dCodes = fg.codecsCodes.rs; // Linked ICDs  
    var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs       
    return {
        dCodes: dCodes, 
        dCodes2: dCodes2
    };  
}


var result = newCodes();
alert(result.dCodes);
alert(result.dCodes2);

How do I create executable Java program?

Jexecutable can create Windows exe for Java programs. It embeds the jars into exe file and you can run it like a Windows program.

Multiple simultaneous downloads using Wget?

wget cant download in multiple connections, instead you can try to user other program like aria2.

NULL or BLANK fields (ORACLE)

SELECT COUNT (COL_NAME) 
FROM TABLE 
WHERE TRIM (COL_NAME) IS NULL 
or COL_NAME='NULL'

Display exact matches only with grep

This worked for me:

grep  "\bsearch_word\b"  text_file > output.txt  ## \b indicates boundaries. This is much faster.

or,

grep -w "search_word" text_file > output.txt

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I was readying this solutions and this example may help.

My database have two tables (email and credit_card) with primary keys for their IDs. Another table (client) refers to this tables IDs as foreign keys. I have a reason to have the email apart from the client data.

First I insert the row data for the referenced tables (email, credit_card) then you get the ID for each, those IDs are needed in the third table (client).

If you don't insert first the rows in the referenced tables, MySQL wont be able to make the correspondences when you insert a new row in the third table that reference the foreign keys.

If you first insert the referenced rows for the referenced tables, then the row that refers to foreign keys, no error occurs.

Hope this helps.

Convert java.time.LocalDate into java.util.Date type

Kotlin Solution:

1) Paste this extension function somewhere.

fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())

2) Use it, and never google this again.

val myDate = myLocalDate.toDate()

Eloquent Collection: Counting and Detect Empty

When using ->get() you cannot simply use any of the below:

if (empty($result)) { }
if (!$result) { }
if ($result) { }

Because if you dd($result); you'll notice an instance of Illuminate\Support\Collection is always returned, even when there are no results. Essentially what you're checking is $a = new stdClass; if ($a) { ... } which will always return true.

To determine if there are any results you can do any of the following:

if ($result->first()) { } 
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }

You could also use ->first() instead of ->get() on the query builder which will return an instance of the first found model, or null otherwise. This is useful if you need or are expecting only one result from the database.

$result = Model::where(...)->first();
if ($result) { ... }

Notes / References

Bonus Information

The Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason it can be confusing to know what one you’re working on. The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like ->all() ->first() ->lists() and others). Those methods also exist on the Collection object, which can get returned from the Query Builder if there are multiple results. If you're not sure what class you're actually working with, try doing var_dump(User::all()) and experimenting to see what classes it's actually returning (with help of get_class(...)). I highly recommend you check out the source code for the Collection class, it's pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.

How to grey out a button?

You have to provide 3 or 4 states in your btn_defaut.xml as a selector.

  1. Pressed state
  2. Default state
  3. Focus state
  4. Enabled state (Disable state with false indication; see comments)

You will provide effect and background for the states accordingly.

Here is a detailed discussion: Standard Android Button with a different color

Convert bytes to bits in python

Use ord when reading reading bytes:

byte_binary = bin(ord(f.read(1))) # Add [2:] to remove the "0b" prefix

Or

Using str.format():

'{:08b}'.format(ord(f.read(1)))

hash function for string

There are a number of existing hashtable implementations for C, from the C standard library hcreate/hdestroy/hsearch, to those in the APR and glib, which also provide prebuilt hash functions. I'd highly recommend using those rather than inventing your own hashtable or hash function; they've been optimized heavily for common use-cases.

If your dataset is static, however, your best solution is probably to use a perfect hash. gperf will generate a perfect hash for you for a given dataset.

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

Search and replace a particular string in a file using Perl

You could also do this:

#!/usr/bin/perl

use strict;
use warnings;

$^I = '.bak'; # create a backup copy 

while (<>) {
   s/<PREF>/ABCD/g; # do the replacement
   print; # print to the modified file
}

Invoke the script with by

./script.pl input_file

You will get a file named input_file, containing your changes, and a file named input_file.bak, which is simply a copy of the original file.

WordPress path url in js script file

If the javascript file is loaded from the admin dashboard, this javascript function will give you the root of your WordPress installation. I use this a lot when I'm building plugins that need to make ajax requests from the admin dashboard.

function getHomeUrl() {
  var href = window.location.href;
  var index = href.indexOf('/wp-admin');
  var homeUrl = href.substring(0, index);
  return homeUrl;
}

Return a `struct` from a function in C

When making a call such as a = foo();, the compiler might push the address of the result structure on the stack and passes it as a "hidden" pointer to the foo() function. Effectively, it could become something like:

void foo(MyObj *r) {
    struct MyObj a;
    // ...
    *r = a;
}

foo(&a);

However, the exact implementation of this is dependent on the compiler and/or platform. As Carl Norum notes, if the structure is small enough, it might even be passed back completely in a register.

How can I pass a parameter to a setTimeout() callback?

I recently came across the unique situation of needing to use a setTimeout in a loop. Understanding this can help you understand how to pass parameters to setTimeout.

Method 1

Use forEach and Object.keys, as per Sukima's suggestion:

var testObject = {
    prop1: 'test1',
    prop2: 'test2',
    prop3: 'test3'
};

Object.keys(testObject).forEach(function(propertyName, i) {
    setTimeout(function() {
        console.log(testObject[propertyName]);
    }, i * 1000);
});

I recommend this method.

Method 2

Use bind:

var i = 0;
for (var propertyName in testObject) {
    setTimeout(function(propertyName) {
        console.log(testObject[propertyName]);
    }.bind(this, propertyName), i++ * 1000);
}

JSFiddle: http://jsfiddle.net/MsBkW/

Method 3

Or if you can't use forEach or bind, use an IIFE:

var i = 0;
for (var propertyName in testObject) {
    setTimeout((function(propertyName) {
        return function() {
            console.log(testObject[propertyName]);
        };
    })(propertyName), i++ * 1000);
}

Method 4

But if you don't care about IE < 10, then you could use Fabio's suggestion:

var i = 0;
for (var propertyName in testObject) {
    setTimeout(function(propertyName) {
        console.log(testObject[propertyName]);
    }, i++ * 1000, propertyName);
}

Method 5 (ES6)

Use a block scoped variable:

let i = 0;
for (let propertyName in testObject) {
    setTimeout(() => console.log(testObject[propertyName]), i++ * 1000);
}

Though I would still recommend using Object.keys with forEach in ES6.

Display number with leading zeros

In Python 2 (and Python 3) you can do:

print "%02d" % (1,)

Basically % is like printf or sprintf (see docs).


For Python 3.+, the same behavior can also be achieved with format:

print("{:02d}".format(1))

For Python 3.6+ the same behavior can be achieved with f-strings:

print(f"{1:02d}")

How to install SQL Server 2005 Express in Windows 8

install "SQL Express 2005 service pack 4" version "directly".

it contains sql Express 2005 inside . dont let the name fool you

runs succesfuly. from my experince

enter image description here

How to convert a string to number in TypeScript?

if you are talking about just types, as other people said, parseInt() etc will return the correct type. Also, if for any reason the value could be both a number or a string and you don't want to call parseInt(), typeof expressions will also cast to the correct type:

function f(value:number|string){
  if(typeof value==='number'){
   // value : number
  }else {
   // value : string
  }
}

Android - Get value from HashMap

Here's a simple example to demonstrate Map usage:

Map<String, String> map = new HashMap<String, String>();
map.put("Color1","Red");
map.put("Color2","Blue");
map.put("Color3","Green");
map.put("Color4","White");

System.out.println(map);
// {Color4=White, Color3=Green, Color1=Red, Color2=Blue}        

System.out.println(map.get("Color2")); // Blue

System.out.println(map.keySet());
// [Color4, Color3, Color1, Color2]

for (Map.Entry<String,String> entry : map.entrySet()) {
    System.out.printf("%s -> %s%n", entry.getKey(), entry.getValue());
}
// Color4 -> White
// Color3 -> Green
// Color1 -> Red
// Color2 -> Blue

Note that the entries are iterated in arbitrary order. If you need a specific order, then you may consider e.g. LinkedHashMap

See also

Related questions

On iterating over entries:

On different Map characteristics:


On enum

You may want to consider using an enum and EnumMap instead of Map<String,String>.

See also

Related questions

How do I fix "Expected to return a value at the end of arrow function" warning?

The warning indicates that you're not returning something at the end of your map arrow function in every case.

A better approach to what you're trying to accomplish is first using a .filter and then a .map, like this:

this.props.comments
  .filter(commentReply => commentReply.replyTo === comment.id)
  .map((commentReply, idx) => <CommentItem key={idx} className="SubComment"/>);

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

See the link below for information about how to use PreparedStatement. I have also quoted from the link.

http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

You must supply values in place of the question mark placeholders (if there are any) before you can execute a PreparedStatement object. Do this by calling one of the setter methods defined in the PreparedStatement class. The following statements supply the two question mark placeholders in the PreparedStatement named updateSales:

updateSales.setInt(1, e.getValue().intValue()); updateSales.setString(2, e.getKey());

How to remove foreign key constraint in sql server?

To be on the safer side, just name all your constraints and take note of them in the comment section.

ALTER TABLE[table_name]
DROP CONSTRAINT Constraint_name

How to verify a Text present in the loaded page through WebDriver

Below code is most suitable way to verify a text on page. You can use any one out of 8 locators as per your convenience.

String Verifytext= driver.findElement(By.tagName("body")).getText().trim(); Assert.assertEquals(Verifytext, "Paste the text here which needs to be verified");

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:

>>> u'ñ'
u'\xf1'
>>> u'ñ'.encode('utf8')
'\xc3\xb1'
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.

You can use str.join() (or, rather, unicode.join()) here to concatenate the three values with dashes in between:

nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')

but even encoding here might be too early.

Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).

Version vs build in Xcode

The Build number is an internal number that indicates the current state of the app. It differs from the Version number in that it's typically not user facing and doesn't denote any difference/features/upgrades like a version number typically would.

Think of it like this:

  • Build (CFBundleVersion): The number of the build. Usually you start this at 1 and increase by 1 with each build of the app. It quickly allows for comparisons of which build is more recent and it denotes the sense of progress of the codebase. These can be overwhelmingly valuable when working with QA and needing to be sure bugs are logged against the right builds.
  • Marketing Version (CFBundleShortVersionString): The user-facing number you are using to denote this version of your app. Usually this follows a Major.minor version scheme (e.g. MyAwesomeApp 1.2) to let users know which releases are smaller maintenance updates and which are big deal new features.

To use this effectively in your projects, Apple provides a great tool called agvtool. I highly recommend using this as it is MUCH more simple than scripting up plist changes. It allows you to easily set both the build number and the marketing version. It is particularly useful when scripting (for instance, easily updating the build number on each build or even querying what the current build number is). It can even do more exotic things like tag your SVN for you when you update the build number.

To use it:

  • Set your project in Xcode, under Versioning, to use "Apple Generic".
  • In terminal
    • agvtool new-version 1 (set the Build number to 1)
    • agvtool new-marketing-version 1.0 (set the Marketing version to 1.0)

See the man page of agvtool for a ton of good info

How can I compare two dates in PHP?

Here's a way on how to get the difference between two dates in minutes.

// set dates
$date_compare1= date("d-m-Y h:i:s a", strtotime($date1));
// date now
$date_compare2= date("d-m-Y h:i:s a", strtotime($date2));

// calculate the difference
$difference = strtotime($date_compare1) - strtotime($date_compare2);
$difference_in_minutes = $difference / 60;

echo $difference_in_minutes;

How to install a previous exact version of a NPM package?

If you have to install an older version of a package, just specify it

npm install <package>@<version>

For example: npm install [email protected]

You can also add the --save flag to that command to add it to your package.json dependencies, or --save --save-exact flags if you want that exact version specified in your package.json dependencies.

The install command is documented here: https://docs.npmjs.com/cli/install

If you're not sure what versions of a package are available, you can use:

npm view <package> versions

And npm view can be used for viewing other things about a package too. https://docs.npmjs.com/cli/view

Get Hard disk serial Number

I have used the following method in a project and it's working successfully.

private string identifier(string wmiClass, string wmiProperty)
//Return a hardware identifier
{
    string result = "";
    System.Management.ManagementClass mc = new System.Management.ManagementClass(wmiClass);
    System.Management.ManagementObjectCollection moc = mc.GetInstances();
    foreach (System.Management.ManagementObject mo in moc)
    {
        //Only get the first one
        if (result == "")
        {
            try
            {
                result = mo[wmiProperty].ToString();
                break;
            }
            catch
            {
            }
        }
    }
    return result;
}

you can call the above method as mentioned below,

string modelNo = identifier("Win32_DiskDrive", "Model");
string manufatureID = identifier("Win32_DiskDrive", "Manufacturer");
string signature = identifier("Win32_DiskDrive", "Signature");
string totalHeads = identifier("Win32_DiskDrive", "TotalHeads");

If you need a unique identifier, use a combination of these IDs.

Force flushing of output to a file while bash script is still running

I found a solution to this here. Using the OP's example you basically run

stdbuf -oL /homedir/MyScript &> some_log.log

and then the buffer gets flushed after each line of output. I often combine this with nohup to run long jobs on a remote machine.

stdbuf -oL nohup /homedir/MyScript &> some_log.log

This way your process doesn't get cancelled when you log out.

Numeric for loop in Django templates

This shows 1 to 20 numbers:

{% for i in "x"|rjust:"20"|make_list %}
 {{ forloop.counter }}
{% endfor %}

also this can help you: (count_all_slider_objects come from views)

{% for i in "x"|rjust:count_all_slider_objects %}
  {{ forloop.counter }}
{% endfor %}

or

  {% with counter=count_all_slider_objects %}
    {% if list_all_slider_objects %}
      {%  for slide in list_all_slider_objects %}
        {{forloop.counter|add:"-1"}}
        {% endfor%}
      {% endif %}
    {% endwith %}

Git: How to remove file from index without deleting files from any repository

To remove the file from the index, use:

git reset myfile

This should not affect your local copy or anyone else's.

Eclipse error: "The import XXX cannot be resolved"

I had the same problem because I added a jar I created, where I had set the packaging base directory other than the base directory of the classes. As a result the class e.g. java.util.List had to be imported as util.List although the suggested import was the first one.

Check the imported jars under referenced libraries to see that they are imported correctly

jQuery - Detecting if a file has been selected in the file input

I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has

.bind("change", function(){ ... });

Or

.change(function(){ ... }); 

which are equivalents.

http://api.jquery.com/change/

for a unique selector change your name attribute to id and then jQuery("#imafile") or a general jQuery('input[type="file"]') for all the file inputs

Pass Javascript Array -> PHP

Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:

function obj2url(prefix, obj) {
        var args=new Array();
        if(typeof(obj) == 'object'){
            for(var i in obj)
                args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
        }
        else
            args[args.length]=prefix+'='+encodeURIComponent(obj);
        return args.join('&');
    }

prefix is a parameter name.

EDIT:

var a = {
    one: two,
    three: four
};

alert('/script.php?'+obj2url('a', a)); 

Will produce

/script.php?a[one]=two&a[three]=four

which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.

failed to load ad : 3

There is one option which helped in our case. As @blizzard mentioned in your application settings in Google Developer Console there is a section which called "Pricing and Distribution". In this section there is a checkbox "CONTAINS ADS". In our case it was disabled. After enabling we successfully received ads.

enter image description here

Canvas width and height in HTML5

A canvas has 2 sizes, the dimension of the pixels in the canvas (it's backingstore or drawingBuffer) and the display size. The number of pixels is set using the the canvas attributes. In HTML

<canvas width="400" height="300"></canvas>

Or in JavaScript

someCanvasElement.width = 400;
someCanvasElement.height = 300;

Separate from that are the canvas's CSS style width and height

In CSS

canvas {  /* or some other selector */
   width: 500px;
   height: 400px;
}

Or in JavaScript

canvas.style.width = "500px";
canvas.style.height = "400px";

The arguably best way to make a canvas 1x1 pixels is to ALWAYS USE CSS to choose the size then write a tiny bit of JavaScript to make the number of pixels match that size.

function resizeCanvasToDisplaySize(canvas) {
   // look up the size the canvas is being displayed
   const width = canvas.clientWidth;
   const height = canvas.clientHeight;

   // If it's resolution does not match change it
   if (canvas.width !== width || canvas.height !== height) {
     canvas.width = width;
     canvas.height = height;
     return true;
   }

   return false;
}

Why is this the best way? Because it works in most cases without having to change any code.

Here's a full window canvas:

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
body { margin: 0; }_x000D_
canvas { display: block; width: 100vw; height: 100vh; }
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

And Here's a canvas as a float in a paragraph

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width  / spacing + 1;_x000D_
  const down   = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y <= down; ++y) {_x000D_
    for (let x = 0; x <= across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
span { _x000D_
   width: 250px; _x000D_
   height: 100px; _x000D_
   float: left; _x000D_
   padding: 1em 1em 1em 0;_x000D_
   display: inline-block;_x000D_
}_x000D_
canvas {_x000D_
   width: 100%;_x000D_
   height: 100%;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim <span class="diagram"><canvas id="c"></canvas></span>_x000D_
vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
<br/><br/>_x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_
</p>
_x000D_
_x000D_
_x000D_

Here's a canvas in a sizable control panel

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}_x000D_
_x000D_
// ----- the code above related to the canvas does not change ----_x000D_
// ---- the code below is related to the slider ----_x000D_
const $ = document.querySelector.bind(document);_x000D_
const left = $(".left");_x000D_
const slider = $(".slider");_x000D_
let dragging;_x000D_
let lastX;_x000D_
let startWidth;_x000D_
_x000D_
slider.addEventListener('mousedown', e => {_x000D_
 lastX = e.pageX;_x000D_
 dragging = true;_x000D_
});_x000D_
_x000D_
window.addEventListener('mouseup', e => {_x000D_
 dragging = false;_x000D_
});_x000D_
_x000D_
window.addEventListener('mousemove', e => {_x000D_
  if (dragging) {_x000D_
    const deltaX = e.pageX - lastX;_x000D_
    left.style.width = left.clientWidth + deltaX + "px";_x000D_
    lastX = e.pageX;_x000D_
  }_x000D_
});
_x000D_
body { _x000D_
  margin: 0;_x000D_
}_x000D_
.frame {_x000D_
  display: flex;_x000D_
  align-items: space-between;_x000D_
  height: 100vh;_x000D_
}_x000D_
.left {_x000D_
  width: 70%;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
}  _x000D_
canvas {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
pre {_x000D_
  padding: 1em;_x000D_
}_x000D_
.slider {_x000D_
  width: 10px;_x000D_
  background: #000;_x000D_
}_x000D_
.right {_x000D_
  flex 1 1 auto;_x000D_
}
_x000D_
<div class="frame">_x000D_
  <div class="left">_x000D_
     <canvas id="c"></canvas>_x000D_
  </div>_x000D_
  <div class="slider">_x000D_
  _x000D_
  </div>_x000D_
  <div class="right">_x000D_
     <pre>_x000D_
* controls_x000D_
* go _x000D_
* here_x000D_
_x000D_
&lt;- drag this_x000D_
     </pre>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

here's a canvas as a background

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
body { margin: 0; }_x000D_
canvas { _x000D_
  display: block; _x000D_
  width: 100vw; _x000D_
  height: 100vh;  _x000D_
  position: fixed;_x000D_
}_x000D_
#content {_x000D_
  position: absolute;_x000D_
  margin: 0 1em;_x000D_
  font-size: xx-large;_x000D_
  font-family: sans-serif;_x000D_
  font-weight: bold;_x000D_
  text-shadow: 2px  2px 0 #FFF, _x000D_
              -2px -2px 0 #FFF,_x000D_
              -2px  2px 0 #FFF,_x000D_
               2px -2px 0 #FFF;_x000D_
}
_x000D_
<canvas id="c"></canvas>_x000D_
<div id="content">_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
</p>_x000D_
<p>_x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_
</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Because I didn't set the attributes the only thing that changed in each sample is the CSS (as far as the canvas is concerned)

Notes:

  • Don't put borders or padding on a canvas element. Computing the size to subtract from the number of dimensions of the element is troublesome

is there a css hack for safari only NOT chrome?

This works:

@media not all and (min-resolution:.001dpcm) { 
  @media {
    /* your code for Safari Desktop & Mobile */
    body {
      background-color: red;
      color: blue;
    }
    /* end */
  }
}

Append data frames together in a for loop

For me, it worked very simply. At first, I made an empty data.frame, then in each iteration I added one column to it. Here is my code:

df <- data.frame(modelForOneIteration)
for(i in 1:10){
  model <- # some processing
  df[,i] = model
}

Generating CSV file for Excel, how to have a newline inside a value

UTF files that contain a BOM will cause Excel to treat new lines literally even in that field is surrounded by quotes. (Tested Excel 2008 Mac)

The solution is to make any new lines a carriage return (CHR 13) rather than a line feed.

Get current time in seconds since the Epoch on Linux, Bash

With most Awk implementations:

awk 'BEGIN {srand(); print srand()}'

how to change php version in htaccess in server

You can't change PHP version by .htaccess.

you need to get your server updated, for PHP 5.3 or you can find another host, which serves PHP 5.3 on shared hosting.

Error renaming a column in MySQL

Lone Ranger is very close... in fact, you also need to specify the datatype of the renamed column. For example:

ALTER TABLE `xyz` CHANGE `manufacurerid` `manufacturerid` INT;

Remember :

  • Replace INT with whatever your column data type is (REQUIRED)
  • Tilde/ Backtick (`) is optional

How can I use jQuery in Greasemonkey?

the @require meta does not work when you want to unbind events on a webpage using jQuery, you have to use a jQuery library included in the webpage and then get it in Greasemonkey with var $ = unsafeWindow.jQuery; How do I unbind jquery event handlers in greasemonkey?

How do you run a .bat file from PHP?

When you use the exec() function, it is as though you have a cmd terminal open and are typing commands straight to it.

Use single quotes like this $str = exec('start /B Path\to\batch.bat');
The /B means the bat will be executed in the background so the rest of the php will continue after running that line, as opposed to $str = exec('start /B /C command', $result); where command is executed and then result is stored for later use.

PS: It works for both Windows and Linux.
More details are here http://www.php.net/manual/en/function.exec.php :)

What does '<?=' mean in PHP?

It's a shortcut for <?php echo $a; ?> if short_open_tags are enabled. Ref: http://php.net/manual/en/ini.core.php

Java: How to get input from System.console()

Scanner in = new Scanner(System.in);

int i = in.nextInt();
String s = in.next();

How to get body of a POST in php?

If you have the pecl/http extension installed, you can also use this:

$request = new http\Env\Request();
$request->getBody();

Create boolean column in MySQL with false as default value?

You have to specify 0 (meaning false) or 1 (meaning true) as the default. Here is an example:

create table mytable (
     mybool boolean not null default 0
);

FYI: boolean is an alias for tinyint(1).

Here is the proof:

mysql> create table mytable (
    ->          mybool boolean not null default 0
    ->     );
Query OK, 0 rows affected (0.35 sec)

mysql> insert into mytable () values ();
Query OK, 1 row affected (0.00 sec)

mysql> select * from mytable;
+--------+
| mybool |
+--------+
|      0 |
+--------+
1 row in set (0.00 sec)

FYI: My test was done on the following version of MySQL:

mysql> select version();
+----------------+
| version()      |
+----------------+
| 5.0.18-max-log |
+----------------+
1 row in set (0.00 sec)

CSS background-image - What is the correct usage?

You don't need to use quotes and you can use any path you like!

PHP error: "The zip extension and unzip command are both missing, skipping."

The shortest command to fix it on Debian and Ubuntu (dependencies will be installed automatically):

sudo apt install php-zip

Install Visual Studio 2013 on Windows 7

your log files shows it is stopping on error "0x8004C000"

From MS Website (http://social.technet.microsoft.com/wiki/contents/articles/15716.visual-studio-2012-and-the-error-code-2147205120.aspx):

Setup Status
Block

Restart not required
0x80044000 [-2147205120]

Restart required
0x8004C000 [-2147172352]

Description
If the only block to be reported is “Reboot Pending,” the returned value is the Incomplete-Reboot Required value (0x80048bc7).

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

In regards to JavaScript:

The === operator works the same as the == operator, but it requires that its operands have not only the same value, but also the same data type.

For example, the sample below will display 'x and y are equal', but not 'x and y are identical'.

var x = 4;
var y = '4';
if (x == y) {
    alert('x and y are equal');
}
if (x === y) {
    alert('x and y are identical');
}

'NOT LIKE' in an SQL query

After "AND" and after "OR" the QUERY has forgotten what it is all about.

I would also not know that it is about in any SQL / programming language.

if(SOMETHING equals "X" or SOMETHING equals "Y")

COLUMN NOT LIKE "A%" AND COLUMN NOT LIKE "B%"

How to force garbage collection in Java?

The jlibs library has a good utility class for garbage collection. You can force garbage collection using a nifty little trick with WeakReference objects.

RuntimeUtil.gc() from the jlibs:

   /**
    * This method guarantees that garbage collection is
    * done unlike <code>{@link System#gc()}</code>
    */
   public static void gc() {
     Object obj = new Object();
     WeakReference ref = new WeakReference<Object>(obj);
     obj = null;
     while(ref.get() != null) {
       System.gc();
     }
   }

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

For me, I tried to check out a SVN-project with TortoiseGit. It worked fine if I used TortoiseSVN though. (May seem obvious, but newcomers may stumble on this one)

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player);     // I get the error here.

void showInventory(player& obj) {   // By Johnny :D

this means that player is an datatype and showInventory expect an referance to an variable of type player.

so the correct code will be

  void showInventory(player& obj) {   // By Johnny :D
    for(int i = 0; i < 20; i++) {
        std::cout << "\nINVENTORY:\n" + obj.getItem(i);
        i++;
        std::cout << "\t\t\t" + obj.getItem(i) + "\n";
        i++;
    }
    }

players myPlayers[10];

    std::string toDo() //BY KEATON
    {
    std::string commands[5] =   // This is the valid list of commands.
        {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return NULL;
    }
    else if(ans == commands[1]) {
        showInventory(myPlayers[0]);     // or any other index,also is not necessary to have an array
        return NULL;
    }

}

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

In my case I had in one report many different datasets to DB and Analysis Services Cube. Looks like that datasets blocked each other and generated such error. For me helped option "Use single transaction when processing the queries" in the CUBE datasource properties

Do you (really) write exception safe code?

Writing exception-safe code in C++ is not so much about using lots of try { } catch { } blocks. It's about documenting what kind of guarantees your code provides.

I recommend reading Herb Sutter's Guru Of The Week series, in particular installments 59, 60 and 61.

To summarize, there are three levels of exception safety you can provide:

  • Basic: When your code throws an exception, your code does not leak resources, and objects remain destructible.
  • Strong: When your code throws an exception, it leaves the state of the application unchanged.
  • No throw: Your code never throws exceptions.

Personally, I discovered these articles quite late, so much of my C++ code is definitely not exception-safe.

How to run multiple SQL commands in a single SQL connection?

No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:

using (SqlConnection conn = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand())
        {
                comm.Connection = conn;
                comm.CommandText = @"update table ... where myparam=@myparam1 ; " +
                                    "update table ... where myparam=@myparam2 ";
                comm.Parameters.AddWithValue("@myparam1", myparam1);
                comm.Parameters.AddWithValue("@myparam2", myparam2);
                conn.Open();
                comm.ExecuteNonQuery();

        }
    }

Remove duplicated rows

The data.table package also has unique and duplicated methods of it's own with some additional features.

Both the unique.data.table and the duplicated.data.table methods have an additional by argument which allows you to pass a character or integer vector of column names or their locations respectively

library(data.table)
DT <- data.table(id = c(1,1,1,2,2,2),
                 val = c(10,20,30,10,20,30))

unique(DT, by = "id")
#    id val
# 1:  1  10
# 2:  2  10

duplicated(DT, by = "id")
# [1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE

Another important feature of these methods is a huge performance gain for larger data sets

library(microbenchmark)
library(data.table)
set.seed(123)
DF <- as.data.frame(matrix(sample(1e8, 1e5, replace = TRUE), ncol = 10))
DT <- copy(DF)
setDT(DT)

microbenchmark(unique(DF), unique(DT))
# Unit: microseconds
#       expr       min         lq      mean    median        uq       max neval cld
# unique(DF) 44708.230 48981.8445 53062.536 51573.276 52844.591 107032.18   100   b
# unique(DT)   746.855   776.6145  2201.657   864.932   919.489  55986.88   100  a 


microbenchmark(duplicated(DF), duplicated(DT))
# Unit: microseconds
#           expr       min         lq       mean     median        uq        max neval cld
# duplicated(DF) 43786.662 44418.8005 46684.0602 44925.0230 46802.398 109550.170   100   b
# duplicated(DT)   551.982   558.2215   851.0246   639.9795   663.658   5805.243   100  a 

How do you load custom UITableViewCells from Xib files?

Check this - http://eppz.eu/blog/custom-uitableview-cell/ - really convenient way using a tiny class that ends up one line in controller implementation:

-(UITableViewCell*)tableView:(UITableView*) tableView cellForRowAtIndexPath:(NSIndexPath*) indexPath
{
    return [TCItemCell cellForTableView:tableView
                          atIndexPath:indexPath
                      withModelSource:self];
}

enter image description here

Confirm button before running deleting routine from website

You could use JavaScript. Either put the code inline, into a function or use jQuery.

  1. Inline:

    <a href="deletelink" onclick="return confirm('Are you sure?')">Delete</a>
    
  2. In a function:

    <a href="deletelink" onclick="return checkDelete()">Delete</a>
    

    and then put this in <head>:

    <script language="JavaScript" type="text/javascript">
    function checkDelete(){
        return confirm('Are you sure?');
    }
    </script>
    

    This one has more work, but less file size if the list is long.

  3. With jQuery:

    <a href="deletelink" class="delete">Delete</a>
    

    And put this in <head>:

    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script language="JavaScript" type="text/javascript">
    $(document).ready(function(){
        $("a.delete").click(function(e){
            if(!confirm('Are you sure?')){
                e.preventDefault();
                return false;
            }
            return true;
        });
    });
    </script>
    

Timer Interval 1000 != 1 second?

The proper interval to get one second is 1000. The Interval property is the time between ticks in milliseconds:

MSDN: Timer.Interval Property

So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tick event multiple times.

Java AES encryption and decryption

Try this, a simpler solution.

byte[] salt = "ThisIsASecretKey".getBytes();
Key key = new SecretKeySpec(salt, 0, 16, "AES");

Cipher cipher = Cipher.getInstance("AES");

Check if string contains \n Java

I'd rather trust JDK over System property. Following is a working snippet.

    private boolean checkIfStringContainsNewLineCharacters(String str){
        if(!StringUtils.isEmpty(str)){
            Scanner scanner = new Scanner(str);
            scanner.nextLine();
            boolean hasNextLine =  scanner.hasNextLine();
            scanner.close();
            return hasNextLine;
        }
        return false;
    }

(Deep) copying an array using jQuery

I realize you're looking for a "deep" copy of an array, but if you just have a single level array you can use this:

Copying a native JS Array is easy. Use the Array.slice() method which creates a copy of part/all of the array.

var foo = ['a','b','c','d','e'];
var bar = foo.slice();

now foo and bar are 5 member arrays of 'a','b','c','d','e'

of course bar is a copy, not a reference... so if you did this next...

bar.push('f');
alert('foo:' + foo.join(', '));
alert('bar:' + bar.join(', '));

you would now get:

foo:a, b, c, d, e
bar:a, b, c, d, e, f

How to implement static class member functions in *.cpp file?

In your header file say foo.h

class Foo{
    public:
        static void someFunction(params..);
    // other stuff
}

In your implementation file say foo.cpp

#include "foo.h"

void Foo::someFunction(params..){
    // Implementation of someFunction
}

Very Important

Just make sure you don't use the static keyword in your method signature when you are implementing the static function in your implementation file.

Good Luck

Is there such a thing as min-font-size and max-font-size?

I am coming a bit late here, I don't get that much credit for it, I am just doing a mix of the answers below because I was forced to do that for a project.

So to answer the question : There is no such thing as this CSS property. I don't know why, but I think it's because they are afraid of a misused of this property, but I don't find any use case where it can be a serious problem.

Whatever, what are the solutions ?

Two tools will allow us to do that : media queries ans vw property

1) There is a "fool" solution consisting in making a media query for every step we eant in our css, changing font from a fixed amount to another fixed amount. It works, but it is very boring to do, and you don't have a smooth linear aspect.

2) As AlmostPitt explained, there is a brillant solution for the minima :

font-size: calc(7px + .5vw);

Minimum here would be 7px in addition to 0.5% of the view width. That is already really cool and working in most of cases. It does not require any media query, you just have to spend some time finding the right parameters.

As you noticed it is a linear function, basic maths learn you that two points already find you the parameters. Then just fix the font-size in px you want for very large screens and for mobile version, then calculate if you want to do a scientific method. Thought, it is absolutely not necessary and you can just go by trying.

3) Let's suppose you have a very boring client (like me) who absolutely wants a title to be one line and no more. If you used AlmostPitt solution, then you are in trouble because your font will keep growing, and if you have a fixed width container (like bootstrap stoping at 1140px or something in large windows). Here I suggest you to use also a media query. In fact you can just find the amout of px size maximum you can handle in your container before the aspect become unwanted (pxMax). This will be your maximum. Then you just have to find the exact screen width you must stop (wMax). (I let you inverse a linear function on your own).

After that just do

@media (min-width: [wMax]px) {
    h2{
        font-size: [pxMax]px;
    }
}

Then it is perfectly linear and your font-size stop growing ! Notice that you don't need to put your previous css property (calc...) in a media query under wMax because media query are considered as more imnportant and it will overwrite the previous property.

I don't think it is useful to make a snippet for this, as you would have trouble to make it to whole screen and it is not rocket science afterall.

Hope this could help others, and don't forget to thank AlmostPitt for his solution.

Text to speech(TTS)-Android

Try this, its simple : **speakout.xml : **

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3498db"
android:weightSum="1"
android:orientation="vertical" >
<TextView
android:id="@+id/txtheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight=".1"
android:gravity="center"
android:padding="3dp"
android:text="Speak Out!!!"
android:textColor="#fff"
android:textSize="25sp"
android:textStyle="bold" />
<EditText
android:id="@+id/edtTexttoSpeak"
android:layout_width="match_parent"
android:layout_weight=".5"
android:background="#fff"
android:textColor="#2c3e50"
android:text="Hi there!!!"
android:padding="5dp"
android:gravity="top|left"
android:layout_height="0dp"/>
<Button
android:id="@+id/btnspeakout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".1"
android:background="#e74c3c"
android:textColor="#fff"
android:text="SPEAK OUT"/>
</LinearLayout>

And Your SpeakOut.java :

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SpeakOut extends Activity implements OnInitListener {
private TextToSpeech repeatTTS;
Button btnspeakout;
EditText edtTexttoSpeak;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.speakout);
    btnspeakout = (Button) findViewById(R.id.btnspeakout);
    edtTexttoSpeak = (EditText) findViewById(R.id.edtTexttoSpeak);
    repeatTTS = new TextToSpeech(this, this);
    btnspeakout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            repeatTTS.speak(edtTexttoSpeak.getText().toString(),
            TextToSpeech.QUEUE_FLUSH, null);
        }
    });
}

@Override
    public void onInit(int arg0) {
        // TODO Auto-generated method stub
    }
}

SOURCE Parallelcodes.com's Post

How many socket connections can a web server handle?

In short: You should be able to achieve in the order of millions of simultaneous active TCP connections and by extension HTTP request(s). This tells you the maximum performance you can expect with the right platform with the right configuration.

Today, I was worried whether IIS with ASP.NET would support in the order of 100 concurrent connections (look at my update, expect ~10k responses per second on older ASP.Net Mono versions). When I saw this question/answers, I couldn't resist answering myself, many answers to the question here are completely incorrect.

Best Case

The answer to this question must only concern itself with the simplest server configuration to decouple from the countless variables and configurations possible downstream.

So consider the following scenario for my answer:

  1. No traffic on the TCP sessions, except for keep-alive packets (otherwise you would obviously need a corresponding amount of network bandwidth and other computer resources)
  2. Software designed to use asynchronous sockets and programming, rather than a hardware thread per request from a pool. (ie. IIS, Node.js, Nginx... webserver [but not Apache] with async designed application software)
  3. Good performance/dollar CPU / Ram. Today, arbitrarily, let's say i7 (4 core) with 8GB of RAM.
  4. A good firewall/router to match.
  5. No virtual limit/governor - ie. Linux somaxconn, IIS web.config...
  6. No dependency on other slower hardware - no reading from harddisk, because it would be the lowest common denominator and bottleneck, not network IO.

Detailed Answer

Synchronous thread-bound designs tend to be the worst performing relative to Asynchronous IO implementations.

WhatsApp can handle a million WITH traffic on a single Unix flavoured OS machine - https://blog.whatsapp.com/index.php/2012/01/1-million-is-so-2011/.

And finally, this one, http://highscalability.com/blog/2013/5/13/the-secret-to-10-million-concurrent-connections-the-kernel-i.html, goes into a lot of detail, exploring how even 10 million could be achieved. Servers often have hardware TCP offload engines, ASICs designed for this specific role more efficiently than a general purpose CPU.

Good software design choices

Asynchronous IO design will differ across Operating Systems and Programming platforms. Node.js was designed with asynchronous in mind. You should use Promises at least, and when ECMAScript 7 comes along, async/await. C#/.Net already has full asynchronous support like node.js. Whatever the OS and platform, asynchronous should be expected to perform very well. And whatever language you choose, look for the keyword "asynchronous", most modern languages will have some support, even if it's an add-on of some sort.

To WebFarm?

Whatever the limit is for your particular situation, yes a web-farm is one good solution to scaling. There are many architectures for achieving this. One is using a load balancer (hosting providers can offer these, but even these have a limit, along with bandwidth ceiling), but I don't favour this option. For Single Page Applications with long-running connections, I prefer to instead have an open list of servers which the client application will choose from randomly at startup and reuse over the lifetime of the application. This removes the single point of failure (load balancer) and enables scaling through multiple data centres and therefore much more bandwidth.

Busting a myth - 64K ports

To address the question component regarding "64,000", this is a misconception. A server can connect to many more than 65535 clients. See https://networkengineering.stackexchange.com/questions/48283/is-a-tcp-server-limited-to-65535-clients/48284

By the way, Http.sys on Windows permits multiple applications to share the same server port under the HTTP URL schema. They each register a separate domain binding, but there is ultimately a single server application proxying the requests to the correct applications.

Update 2019-05-30

Here is an up to date comparison of the fastest HTTP libraries - https://www.techempower.com/benchmarks/#section=data-r16&hw=ph&test=plaintext

  • Test date: 2018-06-06
  • Hardware used: Dell R440 Xeon Gold + 10 GbE
  • The leader has ~7M plaintext reponses per second (responses not connections)
  • The second one Fasthttp for golang advertises 1.5M concurrent connections - see https://github.com/valyala/fasthttp
  • The leading languages are Rust, Go, C++, Java, C, and even C# ranks at 11 (6.9M per second). Scala and Clojure rank further down. Python ranks at 29th at 2.7M per second.
  • At the bottom of the list, I note laravel and cakephp, rails, aspnet-mono-ngx, symfony, zend. All below 10k per second. Note, most of these frameworks are build for dynamic pages and quite old, there may be newer variants that feature higher up in the list.
  • Remember this is HTTP plaintext, not for the Websocket specialty: many people coming here will likely be interested in concurrent connections for websocket.

How is the java memory pool divided?

With Java8, non heap region no more contains PermGen but Metaspace, which is a major change in Java8, supposed to get rid of out of memory errors with java as metaspace size can be increased depending on the space required by jvm for class data.

Notification bar icon turns white in Android 5 Lollipop

According to the documentation, notification icon must be white since Android 3.0 (API Level 11) :

https://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar

"Status bar icons are composed simply of white pixels on a transparent backdrop, with alpha blending used for smooth edges and internal texture where appropriate."

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Sample database for exercise

This is an online database but you can try with the stackoverflow database: https://data.stackexchange.com/stackoverflow/query/new

You also can download its dumps here:

https://archive.org/download/stackexchange

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

def dict_merge(a, b):
  c = a.copy()
  c.update(b)
  return c

new = dict_merge(old, extras)

Among such shady and dubious answers, this shining example is the one and only good way to merge dicts in Python, endorsed by dictator for life Guido van Rossum himself! Someone else suggested half of this, but did not put it in a function.

print dict_merge(
      {'color':'red', 'model':'Mini'},
      {'model':'Ferrari', 'owner':'Carl'})

gives:

{'color': 'red', 'owner': 'Carl', 'model': 'Ferrari'}

Garbage collector in Android

There is no need to call the garbage collector after an OutOfMemoryError.

It's Javadoc clearly states:

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

So, the garbage collector already tried to free up memory before generating the error but was unsuccessful.

run a python script in terminal without the python command

Add the following line to the beginning script1.py

#!/usr/bin/env python

and then make the script executable:

$ chmod +x script1.py

If the script resides in a directory that appears in your PATH variable, you can simply type

$ script1.py

Otherwise, you'll need to provide the full path (either absolute or relative). This includes the current working directory, which should not be in your PATH.

$ ./script1.py

CSS background image to fit width, height should auto-scale in proportion

Based on tips from https://developer.mozilla.org/en-US/docs/CSS/background-size I end up with the following recipe that worked for me

body {
        overflow-y: hidden ! important;
        overflow-x: hidden ! important;
        background-color: #f8f8f8;
        background-image: url('index.png');
        /*background-size: cover;*/
        background-size: contain;
        background-repeat: no-repeat;
        background-position: right;
}

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

Send multiple checkbox data to PHP via jQuery ajax()

    $.post("test.php", { 'choices[]': ["Jon", "Susan"] });

So I would just iterate over the checked boxes and build the array. Something like.

       var data = { 'user_ids[]' : []};
        $(":checked").each(function() {
       data['user_ids[]'].push($(this).val());
       });
        $.post("ajax.php", data);

'float' vs. 'double' precision

A float has 23 bits of precision, and a double has 52.

SQL Server Linked Server Example Query

I have done to find out the data type in the table at link_server using openquery and the results were successful.

SELECT * FROM OPENQUERY (LINKSERVERNAME, '
SELECT DATA_TYPE, COLUMN_NAME
FROM [DATABASENAME].INFORMATION_SCHEMA.COLUMNS
WHERE 
     TABLE_NAME  =''TABLENAME''
')

Its work for me

How to set focus to a button widget programmatically?

Try this:

btn.requestFocusFromTouch();

Remove Blank option from Select Option with AngularJS

There are multiple ways like -

<select ng-init="feed.config = options[0]" ng-model="feed.config"
        ng-options="template.value as template.name for template in feed.configs">
</select>

Or

$scope.feed.config = $scope.configs[0].name;

How to loop an object in React?

you could also just have a return div like the one below and use the built in template literals of Javascript :

const tifs = {1: 'Joe', 2: 'Jane'};

return(

        <div>
            {Object.keys(tifOptions).map((key)=>(
                <p>{paragraphs[`${key}`]}</p>
            ))}
        </div>
    )

"Non-static method cannot be referenced from a static context" error

Instance methods need to be called from an instance. Your setLoanItem method is an instance method (it doesn't have the modifier static), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this)).

You need to create an instance of the class before you can call the method on it:

Media media = new Media();
media.setLoanItem("Yes");

(Btw it would be better to use a boolean instead of a string containing "Yes".)

Format numbers in django templates

Well I couldn't find a Django way, but I did find a python way from inside my model:

def format_price(self):
    import locale
    locale.setlocale(locale.LC_ALL, '')
    return locale.format('%d', self.price, True)

What is the best open-source java charting library? (other than jfreechart)

For dynamic 2D charts, I have been using JChart2D. It's fast, simple, and being updated regularly. The author has been quick to respond to my one bug report and few feature requests. We, at our company, prefer it over JFreeChart because it was designed for dynamic use, unlike JFreeChart.

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • There is no argument given that corresponds to the required formal parameter - .NET Error

    I got this error when one of my properties that was required for the constructor was not public. Make sure all the parameters in the constructor go to properties that are public if this is the case:

    using statements namespace someNamespace

    public class ExampleClass {
    
      //Properties - one is not visible to the class calling the constructor
      public string Property1 { get; set; }
      string Property2 { get; set; }
    
       //Constructor
       public ExampleClass(string property1, string property2)
      {
         this.Property1 = property1;
         this.Property2 = property2;  //this caused that error for me
      }
    }
    

    #ifdef replacement in the Swift language

    As stated in Apple Docs

    The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, build configurations, and language features to accomplish the same functionality. For this reason, preprocessor directives are not imported in Swift.

    I've managed to achieve what I wanted by using custom Build Configurations:

    1. Go to your project / select your target / Build Settings / search for Custom Flags
    2. For your chosen target set your custom flag using -D prefix (without white spaces), for both Debug and Release
    3. Do above steps for every target you have

    Here's how you check for target:

    #if BANANA
        print("We have a banana")
    #elseif MELONA
        print("Melona")
    #else
        print("Kiwi")
    #endif
    

    enter image description here

    Tested using Swift 2.2

    cannot import name patterns

    Seems you are using outdated version of django.. Simply update django and try again.. Following command will update your django version..

    pip install --upgrade django

    How to make a launcher

    Just develop a normal app and then add a couple of lines to the app's manifest file.

    First you need to add the following attribute to your activity:

                android:launchMode="singleTask"
    

    Then add two categories to the intent filter :

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.HOME" />
    

    The result could look something like this:

        <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.dummy.app"
            android:versionCode="1"
            android:versionName="1.0" >
    
            <uses-sdk
                android:minSdkVersion="11"
                android:targetSdkVersion="19" />
    
            <application
                android:allowBackup="true"
                android:icon="@drawable/ic_launcher"
                android:label="@string/app_name"
                android:theme="@style/AppTheme" >
                <activity
                    android:name="com.dummy.app.MainActivity"
                    android:launchMode="singleTask"
                    android:label="@string/app_name" >
                    <intent-filter>
                        <action android:name="android.intent.action.MAIN" />
                        <category android:name="android.intent.category.LAUNCHER" />
                        <category android:name="android.intent.category.DEFAULT" />
                        <category android:name="android.intent.category.HOME" />
                    </intent-filter>
                </activity>
            </application>
    
        </manifest>
    

    It's that simple!

    How to convert map to url query string?

    For multivalue map you can do like below (using java 8 stream api's)

    Url encoding has been taken cared in this.

    MultiValueMap<String, String> params =  new LinkedMultiValueMap<>();
    String urlQueryString = params.entrySet()
                .stream()
                .flatMap(stringListEntry -> stringListEntry.getValue()
                        .stream()
                        .map(s -> UriUtils.encode(stringListEntry.getKey(), StandardCharsets.UTF_8.toString()) + "=" +
                                UriUtils.encode(s, StandardCharsets.UTF_8.toString())))
                .collect(Collectors.joining("&"));
    

    Getting command-line password input in Python

    Updating on the answer of @Ahmed ALaa

    # import msvcrt
    import getch
    
    def getPass():
        passwor = ''
        while True:
            x = getch.getch()
            # x = msvcrt.getch().decode("utf-8")
            if x == '\r' or x == '\n':
                break
            print('*', end='', flush=True)
            passwor +=x
        return passwor
    
    print("\nout=", getPass())
    

    msvcrt us only for windows, but getch from PyPI should work for both (I only tested with linux). You can also comment/uncomment the two lines to make it work for windows.

    Flatten an irregular list of lists

    Python-3

    from collections import Iterable
    
    L = [[[1, 2, 3], [4, 5]], 6,[7,[8,9,[10]]]]
    
    def flatten(thing):
        result = []
    
        if isinstance(thing, Iterable):
            for item in thing:
                result.extend(flatten(item))
        else:
            result.append(thing)
    
        return result
    
    
    flat = flatten(L)
    print(flat)
    

    PowerShell Script to Find and Replace for all Files with a Specific Extension

    Here a first attempt at the top of my head.

    $configFiles = Get-ChildItem . *.config -rec
    foreach ($file in $configFiles)
    {
        (Get-Content $file.PSPath) |
        Foreach-Object { $_ -replace "Dev", "Demo" } |
        Set-Content $file.PSPath
    }
    

    Fixing the order of facets in ggplot

    Make your size a factor in your dataframe by:

    temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))
    

    Then change the facet_grid(.~size) to facet_grid(.~size_f)

    Then plot: enter image description here

    The graphs are now in the correct order.