问:
How to compile caffe_rtpose on OSX?
I've recently bumped spotted caffe_rtpose and I tried to compile and run the example. Unfortunately I'm super experienced with c++ so I ran into a lot of issues compiling and linking.

I've tried tweaking the Makefile config (modified from the existing Ubuntu config). (I'm using a system running OSX 10.11.5 with an nVidia GeForce 750M and I have installed CUDA 7.5 and libcudnn):

```<code>## Refer to http://caffe.berkeleyvision.org/installation.html
# Contributions simplifying and improving our build system are welcome!

# cuDNN acceleration switch (uncomment to build with cuDNN).
USE_CUDNN := 1

# CPU-only switch (uncomment to build without GPU support).
# CPU_ONLY := 1

# uncomment to disable IO dependencies and corresponding data layers
# USE_OPENCV := 0
# USE_LEVELDB := 0
# USE_LMDB := 0

# uncomment to allow MDB_NOLOCK when reading LMDB files (only if necessary)
#   You should not set this flag if you will be reading LMDBs with any
#   possibility of simultaneous read and write
# ALLOW_LMDB_NOLOCK := 1

# Uncomment if you're using OpenCV 3
# OPENCV_VERSION := 3

# To customize your choice of compiler, uncomment and set the following.
# N.B. the default for Linux is g++ and the default for OSX is clang++
# CUSTOM_CXX := g++

# CUDA directory contains bin/ and lib/ directories that we need.
CUDA_DIR := /usr/local/cuda
# On Ubuntu 14.04, if cuda tools are installed via
# "sudo apt-get install nvidia-cuda-toolkit" then use this instead:
# CUDA_DIR := /usr

# CUDA architecture setting: going with all of them.
# For CUDA < 6.0, comment the *_50 lines for compatibility.
CUDA_ARCH := -gencode arch=compute_30,code=sm_30 \
        -gencode arch=compute_35,code=sm_35 \
        -gencode arch=compute_50,code=sm_50 \
        -gencode arch=compute_50,code=compute_50 \
        -gencode arch=compute_52,code=sm_52 \
        # -gencode arch=compute_60,code=sm_60 \
        # -gencode arch=compute_61,code=sm_61
# Deprecated
#CUDA_ARCH := -gencode arch=compute_20,code=sm_20 \
#       -gencode arch=compute_20,code=sm_21 \
#       -gencode arch=compute_30,code=sm_30 \
#       -gencode arch=compute_35,code=sm_35 \
#       -gencode arch=compute_50,code=sm_50 \
#       -gencode arch=compute_50,code=compute_50

# BLAS choice:
# atlas for ATLAS (default)
# mkl for MKL
# open for OpenBlas
BLAS := atlas
# Custom (MKL/ATLAS/OpenBLAS) include and lib directories.
# Leave commented to accept the defaults for your choice of BLAS
# (which should work)!
# BLAS_INCLUDE := /path/to/your/blas
# BLAS_LIB := /path/to/your/blas

# Homebrew puts openblas in a directory that is not on the standard search path
# BLAS_INCLUDE := $(shell brew --prefix openblas)/include
# BLAS_LIB := $(shell brew --prefix openblas)/lib
BLAS_INCLUDE := /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/Headers/
BLAS_LIB := /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A

# This is required only if you will compile the matlab interface.
# MATLAB directory should contain the mex binary in /bin.
# MATLAB_DIR := /usr/local
# MATLAB_DIR := /Applications/MATLAB_R2012b.app

# NOTE: this is required only if you will compile the python interface.
# We need to be able to find Python.h and numpy/arrayobject.h.
PYTHON_INCLUDE := /usr/include/python2.7 \
        /usr/lib/python2.7/dist-packages/numpy/core/include
# Anaconda Python distribution is quite popular. Include path:
# Verify anaconda location, sometimes it's in root.
# ANACONDA_HOME := $(HOME)/anaconda
# PYTHON_INCLUDE := $(ANACONDA_HOME)/include \
        # $(ANACONDA_HOME)/include/python2.7 \
        # $(ANACONDA_HOME)/lib/python2.7/site-packages/numpy/core/include \

# We need to be able to find libpythonX.X.so or .dylib.
PYTHON_LIB := /usr/lib
# PYTHON_LIB := $(ANACONDA_HOME)/lib

# Homebrew installs numpy in a non standard path (keg only)
# PYTHON_INCLUDE += $(dir $(shell python -c 'import numpy.core; print(numpy.core.__file__)'))/include
# PYTHON_LIB += $(shell brew --prefix numpy)/lib

# Uncomment to support layers written in Python (will link against Python libs)
# WITH_PYTHON_LAYER := 1

# Whatever else you find you need goes here.
# INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include /usr/include/hdf5/serial
# LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib /usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/hdf5/serial

INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include
LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib

# If Homebrew is installed at a non standard location (for example your home directory) and you use it for general dependencies
# INCLUDE_DIRS += $(shell brew --prefix)/include
# LIBRARY_DIRS += $(shell brew --prefix)/lib

# Uncomment to use `pkg-config` to specify OpenCV library paths.
# (Usually not necessary -- OpenCV libraries are normally installed in one of the above $LIBRARY_DIRS.)
# USE_PKG_CONFIG := 1

BUILD_DIR := build
DISTRIBUTE_DIR := distribute

# Uncomment for debugging. Does not work on OSX due to https://github.com/BVLC/caffe/issues/171
# DEBUG := 1

# The ID of the GPU that 'make runtest' will use to run unit tests.
TEST_GPUID := 0

# enable pretty build (comment to see full commands)
# Q ?= @
</code>```

And this is the modified version of the install_caffe_and_cpm_osx.sh script:

```<code>#!/bin/bash

echo "------------------------- INSTALLING CAFFE AND CPM -------------------------"
echo "NOTE: This script assumes that CUDA and cuDNN are already installed on your machine. Otherwise, it might fail."

function exitIfError {
    if [[ $? -ne 0 ]] ; then
        echo ""
        echo "------------------------- -------------------------"
        echo "Errors detected. Exiting script. The software might have not been successfully installed."
        echo "------------------------- -------------------------"
        exit 1
    fi
}

# echo "------------------------- Checking Ubuntu Version -------------------------"
# ubuntu_version="$(lsb_release -r)"
# echo "Ubuntu $ubuntu_version"
# if [[ $ubuntu_version == *"14."* ]]; then
#     ubuntu_le_14=true
# elif [[ $ubuntu_version == *"16."* || $ubuntu_version == *"15."* || $ubuntu_version == *"17."* || $ubuntu_version == *"18."* ]]; then
#     ubuntu_le_14=false
# else
#     echo "Ubuntu release older than version 14. This installation script might fail."
#     ubuntu_le_14=true
# fi
# exitIfError
# echo "------------------------- Ubuntu Version Checked -------------------------"
# echo ""

echo "------------------------- Checking Number of Processors -------------------------"
NUM_CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)
echo "$NUM_CORES cores"
exitIfError
echo "------------------------- Number of Processors Checked -------------------------"
echo ""

echo "------------------------- Installing some Caffe Dependencies -------------------------"
# Basic
# sudo apt-get --assume-yes update
# sudo apt-get --assume-yes install build-essential
#General dependencies
brew install protobuf leveldb snappy hdf5
# with Python pycaffe needs dependencies built from source - from http://caffe.berkeleyvision.org/install_osx.html
# brew install --build-from-source --with-python -vd protobuf
# brew install --build-from-source -vd boost boost-python
# without Python the usual installation suffices
brew install boost
# sudo apt-get --assume-yes install libprotobuf-dev libleveldb-dev libsnappy-dev libhdf5-serial-dev protobuf-compiler
# sudo apt-get --assume-yes install --no-install-recommends libboost-all-dev
# Remaining dependencies, 14.04
brew install gflags glog lmdb
# if [[ $ubuntu_le_14 == true ]]; then
#     sudo apt-get --assume-yes install libgflags-dev libgoogle-glog-dev liblmdb-dev
# fi
# OpenCV 2.4
# sudo apt-get --assume-yes install libopencv-dev
exitIfError
echo "------------------------- Some Caffe Dependencies Installed -------------------------"
echo ""

echo "------------------------- Compiling Caffe & CPM -------------------------"
cp Makefile.config.OSX.10.11.5.example Makefile.config
make all -j$NUM_CORES
# make test -j$NUM_CORES
# make runtest -j$NUM_CORES
exitIfError
echo "------------------------- Caffe & CPM Compiled -------------------------"
echo ""

# echo "------------------------- Installing CPM -------------------------"
# echo "Compiled"
# exitIfError
# echo "------------------------- CPM Installed -------------------------"
# echo ""

echo "------------------------- Downloading CPM Models -------------------------"
models_folder="./model/"
# COCO
coco_folder="$models_folder"coco/""
coco_model="$coco_folder"pose_iter_440000.caffemodel""
if [ ! -f $coco_model ]; then
    wget http://posefs1.perception.cs.cmu.edu/Users/tsimon/Projects/coco/data/models/coco/pose_iter_440000.caffemodel -P $coco_folder
fi
exitIfError
# MPI
mpi_folder="$models_folder"mpi/""
mpi_model="$mpi_folder"pose_iter_160000.caffemodel""
if [ ! -f $mpi_model ]; then
    wget http://posefs1.perception.cs.cmu.edu/Users/tsimon/Projects/coco/data/models/mpi/pose_iter_160000.caffemodel -P $mpi_folder
fi
exitIfError
echo "Models downloaded"
echo "------------------------- CPM Models Downloaded -------------------------"
echo ""

echo "------------------------- CAFFE AND CPM INSTALLED -------------------------"
echo ""
</code>```

But I get this error:

```<code>examples/rtpose/rtpose.cpp:1088:22: error: variable length array of non-POD element type 'Frame'
    Frame frame_batch[BATCH_SIZE];
</code>```

I've tried swapping the array for a vector:

```<code>std::vector<Frame> frame_batch;
    std::cout << "allocating " << BATCH_SIZE << " frames" << std::endl;
    frame_batch.reserve(BATCH_SIZE);
</code>```

That seems to take care of that compile error, but now I get a linker error:
    ld: library not found for -lgomp
    clang: error: linker command failed with exit code 1 (use -v to see invocation)

I've searched for lib lib gomp and found a few related posts on caffe and OpenMP mentioning issues with clang on OSX and OpenMP.
What I tried:

Following this post I've installed gcc 4.9 with homebrew (as the homebrew formula for gcc 5 installs 5.9 which might be too high?)

I've set -fopenmp=libomp based on Andrey Bokhanko's answer: this didn't work for me ++-4.9: error: unrecognized command line option '-fopenmp=libomp'

I could download and build Caffe separately using the official instructions, but I can't seem to figure out how to compile this awesome looking demo.
Unfortunately I'm not experienced with c++ and OpenMP so I could really use your suggestions here. Thank you

Update: I've tried Mark Setchell's helpful suggestion of installing llvm via clang. I've updated the Makefile config to use

```<code>CUSTOM_CXX := /usr/local/opt/llvm/bin/clang++
</code>```

but CUDA doesn't like it:

```<code>nvcc fatal   : The version ('30801') of the host compiler ('clang') is not supported
</code>```

I've tried compiling with CPU_ONLY but I still get CUDA errors:

```<code>examples/rtpose/rtpose.cpp:235:5: error: use of undeclared identifier 'cudaMalloc'
    cudaMalloc(&net_copies[device_id].canvas, DISPLAY_RESOLUTION_WIDTH * DISPLAY_RESOLUTION_HEIGHT * 3 * sizeof(float));
    ^
examples/rtpose/rtpose.cpp:236:5: error: use of undeclared identifier 'cudaMalloc'
    cudaMalloc(&net_copies[device_id].joints, MAX_NUM_PARTS*3*MAX_PEOPLE * sizeof(float) );
    ^
examples/rtpose/rtpose.cpp:1130:146: error: use of undeclared identifier 'cudaMemcpyHostToDevice'
                cudaMemcpy(net_copies[tid].canvas, frame.data_for_mat, DISPLAY_RESOLUTION_WIDTH * DISPLAY_RESOLUTION_HEIGHT * 3 * sizeof(float), cudaMemcpyHostToDevice);
                                                                                ^
examples/rtpose/rtpose.cpp:1136:108: error: use of undeclared identifier 'cudaMemcpyHostToDevice'
                cudaMemcpy(pointer + 0 * offset, frame_batch[0].data, BATCH_SIZE * offset * sizeof(float), cudaMemcpyHostToDevice);
                                                                                ^
examples/rtpose/rtpose.cpp:1178:13: error: use of undeclared identifier 'cudaMemcpyHostToDevice'
            cudaMemcpyHostToDevice);
            ^
examples/rtpose/rtpose.cpp:1192:155: error: use of undeclared identifier 'cudaMemcpyDeviceToHost'
                cudaMemcpy(frame_batch[n].data_for_mat, net_copies[tid].canvas, DISPLAY_RESOLUTION_HEIGHT * DISPLAY_RESOLUTION_WIDTH * 3 * sizeof(float), cudaMemcpyDeviceToHost);
                                                                                ^
examples/rtpose/rtpose.cpp:1202:155: error: use of undeclared identifier 'cudaMemcpyDeviceToHost'
                cudaMemcpy(frame_batch[n].data_for_mat, net_copies[tid].canvas, DISPLAY_RESOLUTION_HEIGHT * DISPLAY_RESOLUTION_WIDTH * 3 * sizeof(float), cudaMemcpyDeviceToHost);
</code>```

I'm no expert, but having a quick scan through the code, I don't see how the CPU_ONLY version will work with the cuda calls.

Having another look at the caffe OSX Installation guide, I may try the route >not for the faint of heart

答:
I have finally managed to compile the rtpose example.

Here's what I did:

Swapped the Frame array for a vector in examples/rtpose/rtpose.cpp, as mentioned above:

```<code>std::vector<Frame> frame_batch;
    std::cout << "allocating " << BATCH_SIZE << " frames" << std::endl;
    frame_batch.reserve(BATCH_SIZE);
</code>```

Used the default clang++ compiler, after failed attempts at using gcc++-4.9 and Homebrew installed LLVM's clang++, but removed the -fopenmp flags and the -pthread linker flag, not the compiler flag, based on this answer

After the compile finished, I tried to run it, but got a libjpeg related error:

```<code>dyld: Symbol not found: __cg_jpeg_resync_to_restart
  Referenced from: /System/Library/Frameworks/ImageIO.framework/Versions/A/ImageIO
  Expected in: /usr/local/lib/libJPEG.dylib
 in /System/Library/Frameworks/ImageIO.framework/Versions/A/ImageIO
Trace/BPT trap: 5
</code>```

The workaround was mdemirst's answer. I made a backup of the old symbolic links just in case though. I did symlink libjpeg/libpng/libtiff/libgif from ImageIO.framework.

I've commited the above config/setup script on github.

Now that the example is compiled, I still can't run it, possibly due to not enough GPU memory:

```<code>F0331 02:02:16.231935 528384 syncedmem.cpp:56] Check failed: error == cudaSuccess (2 vs. 0)  out of memory
*** Check failure stack trace: ***
    @        0x10c7a89da  google::LogMessage::Fail()
    @        0x10c7a80d5  google::LogMessage::SendToLog()
    @        0x10c7a863b  google::LogMessage::Flush()
    @        0x10c7aba17  google::LogMessageFatal::~LogMessageFatal()
    @        0x10c7a8cc7  google::LogMessageFatal::~LogMessageFatal()
    @        0x1079481db  caffe::SyncedMemory::to_gpu()
    @        0x107947c9e  caffe::SyncedMemory::mutable_gpu_data()
    @        0x1079affba  caffe::CuDNNConvolutionLayer<>::Forward_gpu()
    @        0x107861331  caffe::Layer<>::Forward()
    @        0x107918016  caffe::Net<>::ForwardFromTo()
    @        0x1077a86f1  warmup()
    @        0x1077b211d  processFrame()
    @     0x7fff8b11899d  _pthread_body
    @     0x7fff8b11891a  _pthread_start
    @     0x7fff8b116351  thread_start
Abort trap: 6
</code>```

I have tried dimming the settings down as much as possible:

```<code>./build/examples/rtpose/rtpose.bin -caffemodel ./model/coco/pose_iter_440000.caffemodel -caffeproto ./model/coco/pose_deploy_linevec.prototxt -camera_resolution "40x30" -camera 0 -resolution "40x30" -start_scale 0.1 -num_scales=0 -no_display true -net_resolution "16x16"
</code>```

But to no avail. Actually running the example may be another question in itself.

Title: How to compile caffe_rtpose on OSX?

Body:
I've recently bumped spotted caffe_rtpose and I tried to compile and run the example. Unfortunately I'm super experienced with c++ so I ran into a lot of issues compiling and linking.

I've tried tweaking the Makefile config (modified from the existing Ubuntu config). (I'm using a system running OSX 10.11.5 with an nVidia GeForce 750M and I have installed CUDA 7.5 and libcudnn):

## Refer to http://caffe.berkeleyvision.org/installation.html
# Contributions simplifying and improving our build system are welcome!

# cuDNN acceleration switch (uncomment to build with cuDNN).
USE_CUDNN := 1

# CPU-only switch (uncomment to build without GPU support).
# CPU_ONLY := 1

# uncomment to disable IO dependencies and corresponding data layers
# USE_OPENCV := 0
# USE_LEVELDB := 0
# USE_LMDB := 0

# uncomment to allow MDB_NOLOCK when reading LMDB files (only if necessary)
#   You should not set this flag if you will be reading LMDBs with any
#   possibility of simultaneous read and write
# ALLOW_LMDB_NOLOCK := 1

# Uncomment if you're using OpenCV 3
# OPENCV_VERSION := 3

# To customize your choice of compiler, uncomment and set the following.
# N.B. the default for Linux is g++ and the default for OSX is clang++
# CUSTOM_CXX := g++

# CUDA directory contains bin/ and lib/ directories that we need.
CUDA_DIR := /usr/local/cuda
# On Ubuntu 14.04, if cuda tools are installed via
# "sudo apt-get install nvidia-cuda-toolkit" then use this instead:
# CUDA_DIR := /usr

# CUDA architecture setting: going with all of them.
# For CUDA < 6.0, comment the *_50 lines for compatibility.
CUDA_ARCH := -gencode arch=compute_30,code=sm_30 \
        -gencode arch=compute_35,code=sm_35 \
        -gencode arch=compute_50,code=sm_50 \
        -gencode arch=compute_50,code=compute_50 \
        -gencode arch=compute_52,code=sm_52 \
        # -gencode arch=compute_60,code=sm_60 \
        # -gencode arch=compute_61,code=sm_61
# Deprecated
#CUDA_ARCH := -gencode arch=compute_20,code=sm_20 \
#       -gencode arch=compute_20,code=sm_21 \
#       -gencode arch=compute_30,code=sm_30 \
#       -gencode arch=compute_35,code=sm_35 \
#       -gencode arch=compute_50,code=sm_50 \
#       -gencode arch=compute_50,code=compute_50

# BLAS choice:
# atlas for ATLAS (default)
# mkl for MKL
# open for OpenBlas
BLAS := atlas
# Custom (MKL/ATLAS/OpenBLAS) include and lib directories.
# Leave commented to accept the defaults for your choice of BLAS
# (which should work)!
# BLAS_INCLUDE := /path/to/your/blas
# BLAS_LIB := /path/to/your/blas

# Homebrew puts openblas in a directory that is not on the standard search path
# BLAS_INCLUDE := $(shell brew --prefix openblas)/include
# BLAS_LIB := $(shell brew --prefix openblas)/lib
BLAS_INCLUDE := /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/Headers/
BLAS_LIB := /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A

# This is required only if you will compile the matlab interface.
# MATLAB directory should contain the mex binary in /bin.
# MATLAB_DIR := /usr/local
# MATLAB_DIR := /Applications/MATLAB_R2012b.app

# NOTE: this is required only if you will compile the python interface.
# We need to be able to find Python.h and numpy/arrayobject.h.
PYTHON_INCLUDE := /usr/include/python2.7 \
        /usr/lib/python2.7/dist-packages/numpy/core/include
# Anaconda Python distribution is quite popular. Include path:
# Verify anaconda location, sometimes it's in root.
# ANACONDA_HOME := $(HOME)/anaconda
# PYTHON_INCLUDE := $(ANACONDA_HOME)/include \
        # $(ANACONDA_HOME)/include/python2.7 \
        # $(ANACONDA_HOME)/lib/python2.7/site-packages/numpy/core/include \

# We need to be able to find libpythonX.X.so or .dylib.
PYTHON_LIB := /usr/lib
# PYTHON_LIB := $(ANACONDA_HOME)/lib

# Homebrew installs numpy in a non standard path (keg only)
# PYTHON_INCLUDE += $(dir $(shell python -c 'import numpy.core; print(numpy.core.__file__)'))/include
# PYTHON_LIB += $(shell brew --prefix numpy)/lib

# Uncomment to support layers written in Python (will link against Python libs)
# WITH_PYTHON_LAYER := 1

# Whatever else you find you need goes here.
# INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include /usr/include/hdf5/serial
# LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib /usr/lib/x86_64-linux-gnu /usr/lib/x86_64-linux-gnu/hdf5/serial

INCLUDE_DIRS := $(PYTHON_INCLUDE) /usr/local/include
LIBRARY_DIRS := $(PYTHON_LIB) /usr/local/lib /usr/lib

# If Homebrew is installed at a non standard location (for example your home directory) and you use it for general dependencies
# INCLUDE_DIRS += $(shell brew --prefix)/include
# LIBRARY_DIRS += $(shell brew --prefix)/lib

# Uncomment to use `pkg-config` to specify OpenCV library paths.
# (Usually not necessary -- OpenCV libraries are normally installed in one of the above $LIBRARY_DIRS.)
# USE_PKG_CONFIG := 1

BUILD_DIR := build
DISTRIBUTE_DIR := distribute

# Uncomment for debugging. Does not work on OSX due to https://github.com/BVLC/caffe/issues/171
# DEBUG := 1

# The ID of the GPU that 'make runtest' will use to run unit tests.
TEST_GPUID := 0

# enable pretty build (comment to see full commands)
# Q ?= @

And this is the modified version of the install_caffe_and_cpm_osx.sh script:

#!/bin/bash

echo "------------------------- INSTALLING CAFFE AND CPM -------------------------"
echo "NOTE: This script assumes that CUDA and cuDNN are already installed on your machine. Otherwise, it might fail."

function exitIfError {
    if [[ $? -ne 0 ]] ; then
        echo ""
        echo "------------------------- -------------------------"
        echo "Errors detected. Exiting script. The software might have not been successfully installed."
        echo "------------------------- -------------------------"
        exit 1
    fi
}

# echo "------------------------- Checking Ubuntu Version -------------------------"
# ubuntu_version="$(lsb_release -r)"
# echo "Ubuntu $ubuntu_version"
# if [[ $ubuntu_version == *"14."* ]]; then
#     ubuntu_le_14=true
# elif [[ $ubuntu_version == *"16."* || $ubuntu_version == *"15."* || $ubuntu_version == *"17."* || $ubuntu_version == *"18."* ]]; then
#     ubuntu_le_14=false
# else
#     echo "Ubuntu release older than version 14. This installation script might fail."
#     ubuntu_le_14=true
# fi
# exitIfError
# echo "------------------------- Ubuntu Version Checked -------------------------"
# echo ""

echo "------------------------- Checking Number of Processors -------------------------"
NUM_CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)
echo "$NUM_CORES cores"
exitIfError
echo "------------------------- Number of Processors Checked -------------------------"
echo ""

echo "------------------------- Installing some Caffe Dependencies -------------------------"
# Basic
# sudo apt-get --assume-yes update
# sudo apt-get --assume-yes install build-essential
#General dependencies
brew install protobuf leveldb snappy hdf5
# with Python pycaffe needs dependencies built from source - from http://caffe.berkeleyvision.org/install_osx.html
# brew install --build-from-source --with-python -vd protobuf
# brew install --build-from-source -vd boost boost-python
# without Python the usual installation suffices
brew install boost
# sudo apt-get --assume-yes install libprotobuf-dev libleveldb-dev libsnappy-dev libhdf5-serial-dev protobuf-compiler
# sudo apt-get --assume-yes install --no-install-recommends libboost-all-dev
# Remaining dependencies, 14.04
brew install gflags glog lmdb
# if [[ $ubuntu_le_14 == true ]]; then
#     sudo apt-get --assume-yes install libgflags-dev libgoogle-glog-dev liblmdb-dev
# fi
# OpenCV 2.4
# sudo apt-get --assume-yes install libopencv-dev
exitIfError
echo "------------------------- Some Caffe Dependencies Installed -------------------------"
echo ""

echo "------------------------- Compiling Caffe & CPM -------------------------"
cp Makefile.config.OSX.10.11.5.example Makefile.config
make all -j$NUM_CORES
# make test -j$NUM_CORES
# make runtest -j$NUM_CORES
exitIfError
echo "------------------------- Caffe & CPM Compiled -------------------------"
echo ""

# echo "------------------------- Installing CPM -------------------------"
# echo "Compiled"
# exitIfError
# echo "------------------------- CPM Installed -------------------------"
# echo ""

echo "------------------------- Downloading CPM Models -------------------------"
models_folder="./model/"
# COCO
coco_folder="$models_folder"coco/""
coco_model="$coco_folder"pose_iter_440000.caffemodel""
if [ ! -f $coco_model ]; then
    wget http://posefs1.perception.cs.cmu.edu/Users/tsimon/Projects/coco/data/models/coco/pose_iter_440000.caffemodel -P $coco_folder
fi
exitIfError
# MPI
mpi_folder="$models_folder"mpi/""
mpi_model="$mpi_folder"pose_iter_160000.caffemodel""
if [ ! -f $mpi_model ]; then
    wget http://posefs1.perception.cs.cmu.edu/Users/tsimon/Projects/coco/data/models/mpi/pose_iter_160000.caffemodel -P $mpi_folder
fi
exitIfError
echo "Models downloaded"
echo "------------------------- CPM Models Downloaded -------------------------"
echo ""

echo "------------------------- CAFFE AND CPM INSTALLED -------------------------"
echo ""

But I get this error:

examples/rtpose/rtpose.cpp:1088:22: error: variable length array of non-POD element type 'Frame'
    Frame frame_batch[BATCH_SIZE];

I've tried swapping the array for a vector:

std::vector<Frame> frame_batch;
    std::cout << "allocating " << BATCH_SIZE << " frames" << std::endl;
    frame_batch.reserve(BATCH_SIZE);

That seems to take care of that compile error, but now I get a linker error:
    ld: library not found for -lgomp
    clang: error: linker command failed with exit code 1 (use -v to see invocation)

I've searched for lib lib gomp and found a few related posts on caffe and OpenMP mentioning issues with clang on OSX and OpenMP.
What I tried:

Following this post I've installed gcc 4.9 with homebrew (as the homebrew formula for gcc 5 installs 5.9 which might be too high?)

I've set -fopenmp=libomp based on Andrey Bokhanko's answer: this didn't work for me ++-4.9: error: unrecognized command line option '-fopenmp=libomp'

I could download and build Caffe separately using the official instructions, but I can't seem to figure out how to compile this awesome looking demo.
Unfortunately I'm not experienced with c++ and OpenMP so I could really use your suggestions here. Thank you

Update: I've tried Mark Setchell's helpful suggestion of installing llvm via clang. I've updated the Makefile config to use

CUSTOM_CXX := /usr/local/opt/llvm/bin/clang++

but CUDA doesn't like it:

nvcc fatal   : The version ('30801') of the host compiler ('clang') is not supported

I've tried compiling with CPU_ONLY but I still get CUDA errors:

examples/rtpose/rtpose.cpp:235:5: error: use of undeclared identifier 'cudaMalloc'
    cudaMalloc(&net_copies[device_id].canvas, DISPLAY_RESOLUTION_WIDTH * DISPLAY_RESOLUTION_HEIGHT * 3 * sizeof(float));
    ^
examples/rtpose/rtpose.cpp:236:5: error: use of undeclared identifier 'cudaMalloc'
    cudaMalloc(&net_copies[device_id].joints, MAX_NUM_PARTS*3*MAX_PEOPLE * sizeof(float) );
    ^
examples/rtpose/rtpose.cpp:1130:146: error: use of undeclared identifier 'cudaMemcpyHostToDevice'
                cudaMemcpy(net_copies[tid].canvas, frame.data_for_mat, DISPLAY_RESOLUTION_WIDTH * DISPLAY_RESOLUTION_HEIGHT * 3 * sizeof(float), cudaMemcpyHostToDevice);
                                                                                ^
examples/rtpose/rtpose.cpp:1136:108: error: use of undeclared identifier 'cudaMemcpyHostToDevice'
                cudaMemcpy(pointer + 0 * offset, frame_batch[0].data, BATCH_SIZE * offset * sizeof(float), cudaMemcpyHostToDevice);
                                                                                ^
examples/rtpose/rtpose.cpp:1178:13: error: use of undeclared identifier 'cudaMemcpyHostToDevice'
            cudaMemcpyHostToDevice);
            ^
examples/rtpose/rtpose.cpp:1192:155: error: use of undeclared identifier 'cudaMemcpyDeviceToHost'
                cudaMemcpy(frame_batch[n].data_for_mat, net_copies[tid].canvas, DISPLAY_RESOLUTION_HEIGHT * DISPLAY_RESOLUTION_WIDTH * 3 * sizeof(float), cudaMemcpyDeviceToHost);
                                                                                ^
examples/rtpose/rtpose.cpp:1202:155: error: use of undeclared identifier 'cudaMemcpyDeviceToHost'
                cudaMemcpy(frame_batch[n].data_for_mat, net_copies[tid].canvas, DISPLAY_RESOLUTION_HEIGHT * DISPLAY_RESOLUTION_WIDTH * 3 * sizeof(float), cudaMemcpyDeviceToHost);

I'm no expert, but having a quick scan through the code, I don't see how the CPU_ONLY version will work with the cuda calls.

Having another look at the caffe OSX Installation guide, I may try the route >not for the faint of heart

Body:
I have finally managed to compile the rtpose example.

Here's what I did:

Swapped the Frame array for a vector in examples/rtpose/rtpose.cpp, as mentioned above:

std::vector<Frame> frame_batch;
    std::cout << "allocating " << BATCH_SIZE << " frames" << std::endl;
    frame_batch.reserve(BATCH_SIZE);

Used the default clang++ compiler, after failed attempts at using gcc++-4.9 and Homebrew installed LLVM's clang++, but removed the -fopenmp flags and the -pthread linker flag, not the compiler flag, based on this answer

After the compile finished, I tried to run it, but got a libjpeg related error:

dyld: Symbol not found: __cg_jpeg_resync_to_restart
  Referenced from: /System/Library/Frameworks/ImageIO.framework/Versions/A/ImageIO
  Expected in: /usr/local/lib/libJPEG.dylib
 in /System/Library/Frameworks/ImageIO.framework/Versions/A/ImageIO
Trace/BPT trap: 5

The workaround was mdemirst's answer. I made a backup of the old symbolic links just in case though. I did symlink libjpeg/libpng/libtiff/libgif from ImageIO.framework.

I've commited the above config/setup script on github.

Now that the example is compiled, I still can't run it, possibly due to not enough GPU memory:

F0331 02:02:16.231935 528384 syncedmem.cpp:56] Check failed: error == cudaSuccess (2 vs. 0)  out of memory
*** Check failure stack trace: ***
    @        0x10c7a89da  google::LogMessage::Fail()
    @        0x10c7a80d5  google::LogMessage::SendToLog()
    @        0x10c7a863b  google::LogMessage::Flush()
    @        0x10c7aba17  google::LogMessageFatal::~LogMessageFatal()
    @        0x10c7a8cc7  google::LogMessageFatal::~LogMessageFatal()
    @        0x1079481db  caffe::SyncedMemory::to_gpu()
    @        0x107947c9e  caffe::SyncedMemory::mutable_gpu_data()
    @        0x1079affba  caffe::CuDNNConvolutionLayer<>::Forward_gpu()
    @        0x107861331  caffe::Layer<>::Forward()
    @        0x107918016  caffe::Net<>::ForwardFromTo()
    @        0x1077a86f1  warmup()
    @        0x1077b211d  processFrame()
    @     0x7fff8b11899d  _pthread_body
    @     0x7fff8b11891a  _pthread_start
    @     0x7fff8b116351  thread_start
Abort trap: 6

I have tried dimming the settings down as much as possible:

./build/examples/rtpose/rtpose.bin -caffemodel ./model/coco/pose_iter_440000.caffemodel -caffeproto ./model/coco/pose_deploy_linevec.prototxt -camera_resolution "40x30" -camera 0 -resolution "40x30" -start_scale 0.1 -num_scales=0 -no_display true -net_resolution "16x16"

But to no avail. Actually running the example may be another question in itself.


来源: stackexchange

问:
Chance of hitting the same function at the same time by two Threads/Tasks
Assuming the following case:

```<code>public HashTable map = new HashTable();
public void Cache(String fileName) {
        if (!map.ContainsKey(fileName))
        {
            map.Add(fileName, new Object());
            _Cache(fileName);
        }
    }
}
private void _Cache(String fileName) {
        lock (map[fileName])
        {
            if (File Already Cached)
                return;
            else {
                cache file
            }
        }
    }
</code>```

When having the following consumers:

```<code>Task.Run(()=> {
    Cache("A");
});
Task.Run(()=> {
    Cache("A");
});
</code>```

Would it be possible in any ways that the Cache method would throw a Duplicate key exception meaning that both tasks would hit the map.add method and try to add the same key??

Edit:

Would using the following data structure solve this concurrency problem?

```<code>public class HashMap<Key, Value>
{
    private HashSet<Key> Keys = new HashSet<Key>();
    private List<Value> Values = new List<Value>();
    public int Count => Keys.Count;
    public Boolean Add(Key key, Value value) {
        int oldCount = Keys.Count;
        Keys.Add(key);
        if (oldCount != Keys.Count) {
            Values.Add(value);
            return true;
        }
        return false;
    }
}
</code>```

答:
Yes, of course it would be possible.  Consider the following fragment:

```<code>    if (!map.ContainsKey(fileName))
    {
        map.Add(fileName, new Object());
</code>```

Thread 1 may execute if (!map.ContainsKey(fileName)) and find that the map does not contain the key, so it will proceed to add it, but before it gets the chance to add it, Thread 2 may also execute if (!map.ContainsKey(fileName)), at which point it will also find that the map does not contain the key, so it will also proceed to add it.  Of course, that will fail.

EDIT (after clarifications)

So, the problem seems to be how to keep the main map locked for as little as possible, and how to prevent cached objects from being initialized twice.

This is a complex problem, so I cannot give you a ready-to-run answer that will work, (especially since I do not currently even have a C# development environment handy,) but generally speaking, I think that you should proceed as follows:

Fully guard your map with lock().

Keep your map locked as little as possible; when an object is not found to be in the map, add an empty object to the map and exit the lock immediately.  This will ensure that this map will not become a point of contention for all requests coming in to the web server.

After the check-if-present-and-add-if-not fragment, you are holding an object which is guaranteed to be in the map.  However, this object may and may not be initialized at this point.  That's fine.  We will take care of that next.

Repeat the lock-and-check idiom, this time with the cached object:  every single incoming request interested in that specific object will need to lock it, check whether it is initialized, and if not, initialize it.  Of course, only the first request will suffer the penalty of initialization. Also, any requests that arrive before the object has been fully initialized will have to wait on their lock until the object is initialized.  But that's all very fine, that's exactly what you want.

ContentLicense: CC BY-SA 3.0

Body:
Assuming the following case:

public HashTable map = new HashTable();
public void Cache(String fileName) {
        if (!map.ContainsKey(fileName))
        {
            map.Add(fileName, new Object());
            _Cache(fileName);
        }
    }
}
private void _Cache(String fileName) {
        lock (map[fileName])
        {
            if (File Already Cached)
                return;
            else {
                cache file
            }
        }
    }

When having the following consumers:

Task.Run(()=> {
    Cache("A");
});
Task.Run(()=> {
    Cache("A");
});

Would it be possible in any ways that the Cache method would throw a Duplicate key exception meaning that both tasks would hit the map.add method and try to add the same key??

Edit:

Would using the following data structure solve this concurrency problem?

public class HashMap<Key, Value>
{
    private HashSet<Key> Keys = new HashSet<Key>();
    private List<Value> Values = new List<Value>();
    public int Count => Keys.Count;
    public Boolean Add(Key key, Value value) {
        int oldCount = Keys.Count;
        Keys.Add(key);
        if (oldCount != Keys.Count) {
            Values.Add(value);
            return true;
        }
        return false;
    }
}

Body:
Yes, of course it would be possible.  Consider the following fragment:

    if (!map.ContainsKey(fileName))
    {
        map.Add(fileName, new Object());

Thread 1 may execute if (!map.ContainsKey(fileName)) and find that the map does not contain the key, so it will proceed to add it, but before it gets the chance to add it, Thread 2 may also execute if (!map.ContainsKey(fileName)), at which point it will also find that the map does not contain the key, so it will also proceed to add it.  Of course, that will fail.

EDIT (after clarifications)

So, the problem seems to be how to keep the main map locked for as little as possible, and how to prevent cached objects from being initialized twice.

This is a complex problem, so I cannot give you a ready-to-run answer that will work, (especially since I do not currently even have a C# development environment handy,) but generally speaking, I think that you should proceed as follows:

Fully guard your map with lock().

Keep your map locked as little as possible; when an object is not found to be in the map, add an empty object to the map and exit the lock immediately.  This will ensure that this map will not become a point of contention for all requests coming in to the web server.

After the check-if-present-and-add-if-not fragment, you are holding an object which is guaranteed to be in the map.  However, this object may and may not be initialized at this point.  That's fine.  We will take care of that next.

Repeat the lock-and-check idiom, this time with the cached object:  every single incoming request interested in that specific object will need to lock it, check whether it is initialized, and if not, initialize it.  Of course, only the first request will suffer the penalty of initialization. Also, any requests that arrive before the object has been fully initialized will have to wait on their lock until the object is initialized.  But that's all very fine, that's exactly what you want.


问:
Jquery in TPL file prestashop
I want call my function fullTxtFunc for to display all my text bloc. i see not the alert(fullTxt) and I a have also an error in firebug:
my file Category.tpl:

```<code>{block name='product_list_header'}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
{literal}
$(document).ready(function(){

      function fullTxtFunc()
      {
        var fullTxt = {/literal}"{$category.description nofilter}";{literal}
        alert("fullTxt");
      }
     // $('.displayFullTxt').click(function(){

      //});

});
{/literal}

</script>
    <div class="block-category card card-block hidden-sm-down">
      <h1 class="h1">{$category.name}</h1>
      {if $category.description}
        <div id="category-description" class="text-muted">{$category.description|truncate:750:" ..." nofilter}<span class="fullTxt" onclick="fullTxtFunc();">Lire la suite</span></div>
        <div class="category-cover">
          <img src="{$category.image.large.url}" alt="{$category.image.legend}">
        </div>
      {/if}
    </div>
    <div class="text-xs-center hidden-md-up">
      <h1 class="h1">{$category.name}</h1>
    </div>
{/block}
</code>```

error firebug:
enter image description here
Thank's for ur help!

答:
Try to replace this code: </p>

```<code>function fullTxtFunc()
      {
        var fullTxt = '{/literal}{$category.description nofilter}{literal}';
        alert("fullTxt");
      }
</code>```

Title: Jquery in TPL file prestashop

Body:
I want call my function fullTxtFunc for to display all my text bloc. i see not the alert(fullTxt) and I a have also an error in firebug:
my file Category.tpl:

{block name='product_list_header'}

{$category.name}

      {if $category.description}

{$category.description|truncate:750:" ..." nofilter}Lire la suite

      {/if}

{$category.name}

{/block}

error firebug:
enter image description here
Thank's for ur help!

Body:
Try to replace this code:

function fullTxtFunc()
      {
        var fullTxt = '{/literal}{$category.description nofilter}{literal}';
        alert("fullTxt");
      }


问:
php weird file_exists bug
Has anyone got any idea to why doesn't the following work ?

```<code>$file = 'images/thumbs/1%20-%20Copy.jpg';
if(!file_exists($file)){
 die('NOT THERE');
}

echo 'Yes its there.';
</code>```

The problem is with the spaces. I have checked the file exists,dbl checked n triple checked im going nuts. :(

Help

答:
file_exists works on the file system and not via HTTP. So %20 will not be recognized as space but literally as %20; use spaces instead:

```<code>$file = 'images/thumbs/1 - Copy.jpg';
</code>```

ContentLicense: CC BY-SA 2.5

Title: php weird file_exists bug

Body:
Has anyone got any idea to why doesn't the following work ?

$file = 'images/thumbs/1%20-%20Copy.jpg';
if(!file_exists($file)){
 die('NOT THERE');
}

echo 'Yes its there.';

The problem is with the spaces. I have checked the file exists,dbl checked n triple checked im going nuts. :(

Help

Body:
file_exists works on the file system and not via HTTP. So %20 will not be recognized as space but literally as %20; use spaces instead:

$file = 'images/thumbs/1 - Copy.jpg';


问:
Dagger2 scopes and RepositoryPattern in Android
I'm using Dagger 2 and the Repository pattern in Android and am getting tripped up by which scope I should be using for the repository's dependencies and the tradeoffs of using them.

Generally I create a repository per feature. So if we're talking about the registration feature then I'd create a RegistrationRepository. The RegistrationRepository would have 3 different data sources, RegistrationNetworkSource, RegistrationDiscSource and RegistrationMemorySource. When my Activity makes a request to the RegistrationRepository the repo will create an RxJava observable and return it to the activity. The activity can then subscribe to the observable and await the result. If the activity happens to undergo a configuration change before the observable returns a result then the observable can be cached in a separate class that is scoped to the application life cycle and after the activity is re-created it can grab this cached observable and resubscribe to it. And this is where my confusion starts. If my observable is being cached in a class that is scoped to the application scope does that mean that the 3 repository data sources also need to be scoped to the application scope?

My gut tells me that I should scope them to the Application scope. Doing this would allow each source to perform a long running data fetching task that could continue even if the Activity that the request came from undergoes a configuration change. There'd be one instance per app and they'd always be available for use. That sounds great, but doesn't that end up wasting resources? If registration is the first screen of my app and the user spends the rest of their time on the HomeActivity or some other place, then why should the 3 Registration data sources still be alive?

答:
This question is quite similar to your previous question but it seems like there are some unresolved doubts.

To start, I would recommend you read up about how scopes work in the answers to this question. To summarise, there is nothing magical about scopes, they are just there to help you reason about the lifecycles of the objects created from your Components. The instances of the dependencies you generate from the Components will exist where you maintain a reference to them. Normally you would maintain references to the dependencies injected from a @PerActivity Component inside a single activity. For example, if your @PerActivity CoffeeComponent has a CoffeeModule:

```<code>@Provides
@PerActivity
public CoffeeMaker coffeeMaker(HotWater hotWater, Beans beans) {
    return new DefaultCoffeeMaker(hotWater, beans);
}
</code>```

Then you'd normally expect the instances of CoffeeMaker you obtain to follow the lifecycles of a single Activity. However, if you took one of those CoffeeMaker instances and maintain a reference to it inside the Application class, that instance would exist until the Application was destroyed.

Let's try and apply this to your problem:

If my observable is being cached in a class that is scoped to the application scope does that mean that the 3 repository data sources also need to be scoped to the application scope?

No, the repository data sources can be scoped @PerActivity and you could maintain references to the Observables at the @PerApplication (@Singleton) scope. Other Dagger 2 answers here have talked about using the Holder pattern for this. In short, you would make a singleton class with the ability to store the results of the Observables at the app-scoped level. When you make the request using the RegistrationNetworkSource, you can cause the Holder to subscribe, receive, and cache results. Your Activities can obtain the pending results from the Holder rather than directly subscribing to the Observable from the RegistrationRepository.

Some other issues to consider:

How long are your long-running network requests that you require to survive configuration changes? Consider using something like DownloadManager

Are Loaders not a better fit for your use case than Dagger 2 and Rx-Java Observables? Note from the documentation for Loaders the following:

Loaders persist and cache results across configuration changes to prevent duplicate queries.

Body:
This question is quite similar to your previous question but it seems like there are some unresolved doubts.

To start, I would recommend you read up about how scopes work in the answers to this question. To summarise, there is nothing magical about scopes, they are just there to help you reason about the lifecycles of the objects created from your Components. The instances of the dependencies you generate from the Components will exist where you maintain a reference to them. Normally you would maintain references to the dependencies injected from a @PerActivity Component inside a single activity. For example, if your @PerActivity CoffeeComponent has a CoffeeModule:

@Provides
@PerActivity
public CoffeeMaker coffeeMaker(HotWater hotWater, Beans beans) {
    return new DefaultCoffeeMaker(hotWater, beans);
}

Then you'd normally expect the instances of CoffeeMaker you obtain to follow the lifecycles of a single Activity. However, if you took one of those CoffeeMaker instances and maintain a reference to it inside the Application class, that instance would exist until the Application was destroyed.

Let's try and apply this to your problem:

If my observable is being cached in a class that is scoped to the application scope does that mean that the 3 repository data sources also need to be scoped to the application scope?

No, the repository data sources can be scoped @PerActivity and you could maintain references to the Observables at the @PerApplication (@Singleton) scope. Other Dagger 2 answers here have talked about using the Holder pattern for this. In short, you would make a singleton class with the ability to store the results of the Observables at the app-scoped level. When you make the request using the RegistrationNetworkSource, you can cause the Holder to subscribe, receive, and cache results. Your Activities can obtain the pending results from the Holder rather than directly subscribing to the Observable from the RegistrationRepository.

Some other issues to consider:

How long are your long-running network requests that you require to survive configuration changes? Consider using something like DownloadManager

Are Loaders not a better fit for your use case than Dagger 2 and Rx-Java Observables? Note from the documentation for Loaders the following:

Loaders persist and cache results across configuration changes to prevent duplicate queries.


问:
How to run a macro daily using windows task scheduler
I have a macro which I want to run at a specified time daily (say 11 am) even if Excel is closed.

What I have found out is that I can do it by creating Windows Task Scheduler, but I'm new to Windows and don't know how this is created.

The following is my macro:

```<code>Sub Mail_Sheet_Outlook_Body()

    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set rng = Nothing
    Set rng = ActiveSheet.UsedRange
    'You can also use a sheet name
    'Set rng = Sheets("YourSheet").UsedRange

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = "Testing"
        .HTMLBody = RangetoHTML(rng)
        .Send   'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)

    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function
</code>```

Can anyone tell me how to create the windows task scheduler to run this macro daily?

UPDATE:

Wrote the following vbs script:

```<code>Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Set xlBook = xlApp.Workbooks.Open(“H:\excel.xlsm”, 0, True)

xlApp.Run "GetFiles"

xlbook.Save
xlBook.Close False
set xlBook = Nothing

xlApp.Quit
Set xlApp = Nothing

WScript.Echo "Finished."
WScript.Quit
</code>```

答:
Try this,,

Application.OnTime TimeValue("18:00:00"), "MyMacro"

Other if you want to run Macro without support of Excel,, U need to create Vbs file.
It's like A.Vbs, ,, then open the file,, paste your sample Macro,, & the following lines are required to be added,,

objExcel.Application.Run "'path to excel file '! module name . macro name "

If you want to save it,, add this also,
objExcel.Application.save
objExcel.Application.Quit
Then close & double click on the Vbs file.

Body:
I have a macro which I want to run at a specified time daily (say 11 am) even if Excel is closed.

What I have found out is that I can do it by creating Windows Task Scheduler, but I'm new to Windows and don't know how this is created.

The following is my macro:

Sub Mail_Sheet_Outlook_Body()

    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    Set rng = Nothing
    Set rng = ActiveSheet.UsedRange
    'You can also use a sheet name
    'Set rng = Sheets("YourSheet").UsedRange

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = ""
        .CC = ""
        .BCC = ""
        .Subject = "Testing"
        .HTMLBody = RangetoHTML(rng)
        .Send   'or use .Display
    End With
    On Error GoTo 0

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Function RangetoHTML(rng As Range)

    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

Can anyone tell me how to create the windows task scheduler to run this macro daily?

UPDATE:

Wrote the following vbs script:

Dim xlApp, xlBook

Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Set xlBook = xlApp.Workbooks.Open(“H:\excel.xlsm”, 0, True)

xlApp.Run "GetFiles"

xlbook.Save
xlBook.Close False
set xlBook = Nothing

xlApp.Quit
Set xlApp = Nothing

WScript.Echo "Finished."
WScript.Quit


问:
NodeJS NPM Proxy error when installing grunt
When I'm trying to install grunt via npm, I'm getting a following error:

```<code>C:\Program Files\nodejs\node_modules\npm>npm install -g grunt
npm ERR! network connect ETIMEDOUT
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "grunt"
npm ERR! cwd C:\Program Files\nodejs\node_modules\npm
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.28
npm ERR! syscall connect
npm ERR! code ETIMEDOUT
npm ERR! errno ETIMEDOUT
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Program Files\nodejs\node_modules\npm\npm-debug.log
npm ERR! not ok code 0
</code>```

I´m using enterprise proxy configurations, and I believe that I'm having this error because of its configurations. What do I need to change in order to install grunt successfully?

答:
you can run this in cmd

```<code>npm config set <key> <value> [-g|--global]
npm config get <key>
npm config delete <key>
npm config list
npm config edit
npm get <key>
npm set <key> <value> [-g|--global]
</code>```

npmrc.txt will run  you can change your link and port

```<code> proxy =http://proxy.company.com:8080

 https-proxy = http://proxy.company.com:8080
</code>```

reference

Body:
When I'm trying to install grunt via npm, I'm getting a following error:

C:\Program Files\nodejs\node_modules\npm>npm install -g grunt
npm ERR! network connect ETIMEDOUT
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "grunt"
npm ERR! cwd C:\Program Files\nodejs\node_modules\npm
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.28
npm ERR! syscall connect
npm ERR! code ETIMEDOUT
npm ERR! errno ETIMEDOUT
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Program Files\nodejs\node_modules\npm\npm-debug.log
npm ERR! not ok code 0

I´m using enterprise proxy configurations, and I believe that I'm having this error because of its configurations. What do I need to change in order to install grunt successfully?

Body:
you can run this in cmd

npm config set <key> <value> [-g|--global]
npm config get <key>
npm config delete <key>
npm config list
npm config edit
npm get <key>
npm set <key> <value> [-g|--global]

npmrc.txt will run  you can change your link and port

 proxy =http://proxy.company.com:8080

 https-proxy = http://proxy.company.com:8080

reference


问:
How to automate loading leiningen repl from within Emacs?
I'm using Emacs, integrated with Leiningen's swank. Each time I need to start working with .clj file I have to:

Run emacs pack/my-ns.clj from console.

Type M-x lein-swank.

Compile buffer.

In Clojure REPL change namespace, i.e. type (in-ns 'pack.my-ns).

How can I automate this process to just run from console something like emacs-clj pack/my-ns.clj and get my environment ready to use?

答:
I don't have an answer to the question you posed, but you should be able to replace your 4th step with C-c M-p while in your Clojure file and then emacs should prompt you as to what namespace you want to be in with the namespace of the file auto-detected so you can simply hit enter. C-c M-p maps to slime-repl-set-package.

Update:

Just stumbled across this. Should be able to take what is said in that answer and modify it so upon initial connection to swank files get compiled. Could also set it up to automatically switch to namespace and make the repl buffer active.


问:
Change The index of a comboBox in windows Application in c#
i have 100 objects of areas which have id and name i want to show name in combobox and their id's as index of combobox but this code is not working</p>

```<code>private void Areadropdown()//show Areadropdown
    {
        List<Area> list = Area.Dropdown();

        foreach (Area a in list)
        {

          metroComboBox1.Items.Insert(a.Id,a.Areaname);
        }
    }
</code>```

答:
Try this (using BindingList) :</p>

```<code>private void Areadropdown()
{
  List<Area> list = Area.Dropdown();
  BindingList<Area> areas = new BindingList<Area>(list);
  metroComboBox1.ValueMember = "Id";
  metroComboBox1.DisplayMember = "Areaname";
  metroComboBox1.DataSource = areas ;
}
</code>```

Body:
i have 100 objects of areas which have id and name i want to show name in combobox and their id's as index of combobox but this code is not working

private void Areadropdown()//show Areadropdown
    {
        List<Area> list = Area.Dropdown();

        foreach (Area a in list)
        {

          metroComboBox1.Items.Insert(a.Id,a.Areaname);
        }
    }

Body:
Try this (using BindingList) :

private void Areadropdown()
{
  List<Area> list = Area.Dropdown();
  BindingList<Area> areas = new BindingList<Area>(list);
  metroComboBox1.ValueMember = "Id";
  metroComboBox1.DisplayMember = "Areaname";
  metroComboBox1.DataSource = areas ;
}


问:
DirectX writing backbuffer data to file
I am trying to convert every frame of my DirectX program to YUV (for video encoding). Therefore I need the RGB(A) values of each pixel on every frame first. I need to get these from the backbuffer.

Because there is no glReadPixels in DirectX, I do the following:

Get pointer to the backbuffer's renderTargetView and get the backbuffer resource

Cast this resource to ID3D10Texture2D

Make a staging texture and CopyResource the texture2D from the previous step.

At this point I can use D3DX10SaveTextureToFile and this staging texture will correctly save the backbuffer as an image.

However, I don't want to use the disk as a detour, I want to get the RGB data right away, so I do the following:

Map the staging resource

Read the pData of the mapped texture to get the RGB(A) values

The problem: the RGB values are rubbish. This is an example for pixel (1,1)

(1, 1) = (-170141183460469230000000000000000000000.000000,
  -170141183460469230000000000000000000000.000000, -170141183460469230000000000000000000000.000000)

This is particularly strange because I use the same code to Map another staging texture (from another offscreen render target) and this code works just fine there.

This is my code:

```<code>// Get resource pointer to backbuffer
ID3D10Resource *backbufferRes;
m_D3D->GetRenderTargetView()->GetResource(&backbufferRes);

// Cast backbuffer resource to texture2D
ID3D10Texture2D* tempTexture = 0;
backbufferRes->QueryInterface(__uuidof(ID3D10Texture2D),(LPVOID*) &tempTexture);
backbufferRes->Release();

// Get the descriptor of this texture2D
D3D10_TEXTURE2D_DESC descDefault;
tempTexture->GetDesc(&descDefault);

// Create a staging texture desc based on the texture of the backbuffer
D3D10_TEXTURE2D_DESC descStaging;
descStaging = descDefault;
descStaging.Usage = D3D10_USAGE_STAGING;
descStaging.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
descStaging.BindFlags = 0;

// Create the new empty staging texture
ID3D10Texture2D *texture = 0;
m_D3D->GetDevice()->CreateTexture2D( &descStaging, NULL, &texture);

// Copy the backbuffer texture data (tempTexture) to the staging texture (texture)
m_D3D->GetDevice()->CopyResource(texture, tempTexture);

// This call works perfectly, image is correct!
// D3DX10SaveTextureToFile(texture, D3DX10_IFF_BMP, L"D:\\img.bmp");

// We want to avoid disk access, so instead let's map the texture and read its RGB data
D3D10_MAPPED_TEXTURE2D mappedTexture;
hr = texture->Map(D3D10CalcSubresource(0, 0, 1), D3D10_MAP_READ, 0, &mappedTexture);
FLOAT* m_pBits = (FLOAT*) malloc(4 * descStaging.Width * descStaging.Height * sizeof(FLOAT));
if(!FAILED(hr)) {
    memcpy(m_pBits, mappedTexture.pData, 4 * descStaging.Width * descStaging.Height);
    texture->Unmap(D3D10CalcSubresource(0, 0, 1));
}
texture->Release();
tempTexture->Release();

fp = fopen("D:\\output.txt", "a");
for( UINT row = 0; row < descStaging.Height; row++ )
{
    UINT rowStart = row * mappedTexture.RowPitch / 4;
    for( UINT col = 0; col < descStaging.Width; col++ )
    {
        r = m_pBits[rowStart + col*4 + 0]; // Red (X)
        g = m_pBits[rowStart + col*4 + 1]; // Green (Y)
        b = m_pBits[rowStart + col*4 + 2]; // Blue (Z)
        a = m_pBits[rowStart + col*4 + 3]; // Alpha (W)

        // Save pixel values to disk
        fprintf(fp, "%d %d - %f %f %f\n",  col + 1, row + 1, r, g, b);
    }
}
fclose(fp);
</code>```

Does anyone have an idea on what the problem might be?
All help is really appreciated.

答:
Old question, but I think this might be the problem:

After you map the texture with texture->Map(), you try to copy it across into m_pBits all in one go. This won't work unless the RowPitch of the mapped texture is the same as its width (see here).

Instead, you must copy across the image row-by-row:

```<code>BYTE* source = static_cast<BYTE*>(mappedTexture.pData);
BYTE& dest = m_pBits;
for (int i = 0; i < IMAGE_HEIGHT; ++i) {
    memcpy(dest, source, IMAGE_WIDTH * 4); // for 4 bytes per pixel
    source += mappedTexture.RowPitch;
    dest += IMAGE_WIDTH * 4;
}
</code>```

Title: DirectX writing backbuffer data to file

Body:
I am trying to convert every frame of my DirectX program to YUV (for video encoding). Therefore I need the RGB(A) values of each pixel on every frame first. I need to get these from the backbuffer.

Because there is no glReadPixels in DirectX, I do the following:

Get pointer to the backbuffer's renderTargetView and get the backbuffer resource

Cast this resource to ID3D10Texture2D

Make a staging texture and CopyResource the texture2D from the previous step.

At this point I can use D3DX10SaveTextureToFile and this staging texture will correctly save the backbuffer as an image.

However, I don't want to use the disk as a detour, I want to get the RGB data right away, so I do the following:

Map the staging resource

Read the pData of the mapped texture to get the RGB(A) values

The problem: the RGB values are rubbish. This is an example for pixel (1,1)

(1, 1) = (-170141183460469230000000000000000000000.000000,
  -170141183460469230000000000000000000000.000000, -170141183460469230000000000000000000000.000000)

This is particularly strange because I use the same code to Map another staging texture (from another offscreen render target) and this code works just fine there.

This is my code:

// Get resource pointer to backbuffer
ID3D10Resource *backbufferRes;
m_D3D->GetRenderTargetView()->GetResource(&backbufferRes);

// Cast backbuffer resource to texture2D
ID3D10Texture2D* tempTexture = 0;
backbufferRes->QueryInterface(__uuidof(ID3D10Texture2D),(LPVOID*) &tempTexture);
backbufferRes->Release();

// Get the descriptor of this texture2D
D3D10_TEXTURE2D_DESC descDefault;
tempTexture->GetDesc(&descDefault);

// Create a staging texture desc based on the texture of the backbuffer
D3D10_TEXTURE2D_DESC descStaging;
descStaging = descDefault;
descStaging.Usage = D3D10_USAGE_STAGING;
descStaging.CPUAccessFlags = D3D10_CPU_ACCESS_READ;
descStaging.BindFlags = 0;

// Create the new empty staging texture
ID3D10Texture2D *texture = 0;
m_D3D->GetDevice()->CreateTexture2D( &descStaging, NULL, &texture);

// Copy the backbuffer texture data (tempTexture) to the staging texture (texture)
m_D3D->GetDevice()->CopyResource(texture, tempTexture);

// This call works perfectly, image is correct!
// D3DX10SaveTextureToFile(texture, D3DX10_IFF_BMP, L"D:\\img.bmp");

// We want to avoid disk access, so instead let's map the texture and read its RGB data
D3D10_MAPPED_TEXTURE2D mappedTexture;
hr = texture->Map(D3D10CalcSubresource(0, 0, 1), D3D10_MAP_READ, 0, &mappedTexture);
FLOAT* m_pBits = (FLOAT*) malloc(4 * descStaging.Width * descStaging.Height * sizeof(FLOAT));
if(!FAILED(hr)) {
    memcpy(m_pBits, mappedTexture.pData, 4 * descStaging.Width * descStaging.Height);
    texture->Unmap(D3D10CalcSubresource(0, 0, 1));
}
texture->Release();
tempTexture->Release();

fp = fopen("D:\\output.txt", "a");
for( UINT row = 0; row < descStaging.Height; row++ )
{
    UINT rowStart = row * mappedTexture.RowPitch / 4;
    for( UINT col = 0; col < descStaging.Width; col++ )
    {
        r = m_pBits[rowStart + col*4 + 0]; // Red (X)
        g = m_pBits[rowStart + col*4 + 1]; // Green (Y)
        b = m_pBits[rowStart + col*4 + 2]; // Blue (Z)
        a = m_pBits[rowStart + col*4 + 3]; // Alpha (W)

        // Save pixel values to disk
        fprintf(fp, "%d %d - %f %f %f\n",  col + 1, row + 1, r, g, b);
    }
}
fclose(fp);

Does anyone have an idea on what the problem might be?
All help is really appreciated.

Body:
Old question, but I think this might be the problem:

After you map the texture with texture->Map(), you try to copy it across into m_pBits all in one go. This won't work unless the RowPitch of the mapped texture is the same as its width (see here).

Instead, you must copy across the image row-by-row:

BYTE* source = static_cast<BYTE*>(mappedTexture.pData);
BYTE& dest = m_pBits;
for (int i = 0; i < IMAGE_HEIGHT; ++i) {
    memcpy(dest, source, IMAGE_WIDTH * 4); // for 4 bytes per pixel
    source += mappedTexture.RowPitch;
    dest += IMAGE_WIDTH * 4;
}


问:
Use bootstrap dynamic modal for delete confirmation (laravel blade)
My goal is to use bootstrap modal as delete confirmation. But the problem is I need to transfer a dynamic variable (which contains item ID) value to bootstrap modal for submit post request to delete that specific item.

Please check Modal Part where value="foo" is set now tell me how can I make this "foo" as dynamic variable which will be coming from laravel blade template part ("Delete	")
Whats the solution? I prefer javascript solution.

Bootstrap Modal Part

```<code><div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myModalLabel">Are you sure?</h4>
                </div>
                <form method="post">
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" name="delete_dividend" value="foo">Delete</button>
                </div>
                </form>
            </div>
        </div>
    </div>
</code>```

Laravel Blade Template Part

```<code>@foreach($dividends_10 as $_dividend_data)
                    <tr>
                      <td>{{Portfolio\StockModel::select('short_name')->where('id',$_dividend_data['stock_id'])->value('short_name')}}</td>
                      <td>{{$_dividend_data['amount']}}</td>
                      <td>{{$_dividend_data['date']}}</td>
                      <td><a href="{{'dividends'}}">Edit</a></td>
                      <td><a href="{{'#'}}" data-toggle="modal" data-target="#myModal">Delete</a></td>
                    </tr>
                  @endforeach
</code>```

答:
Assuming id field as Primary key of your table.

First replace your Laravel Blade Template Part with below code::

```<code>@foreach($dividends_10 as $_dividend_data)
<tr>
  <td>{{Portfolio\StockModel::select('short_name')->where('id',$_dividend_data['stock_id'])->value('short_name')}}</td>
  <td>{{$_dividend_data['amount']}}</td>
  <td>{{$_dividend_data['date']}}</td>
  <td><a href="{{'dividends'}}">Edit</a></td>
  <td><a href="{{'#'}}" class="delete-mdoal" data-value="{{$_dividend_data['id']}}" data-toggle="modal" data-target="#myModal">Delete</a></td>
</tr>
@endforeach
</code>```

After that use below jQuery to made delete button value dynamic:

```<code>$(document).ready(function (e) {
    $(document).on("click", ".delete-mdoal", function (e) {
        var delete_id = $(this).attr('data-value');
        $('button[name="delete_dividend"]').val(delete_id);
    });
});
</code>```

Body:
My goal is to use bootstrap modal as delete confirmation. But the problem is I need to transfer a dynamic variable (which contains item ID) value to bootstrap modal for submit post request to delete that specific item.

Please check Modal Part where value="foo" is set now tell me how can I make this "foo" as dynamic variable which will be coming from laravel blade template part ("Delete	")
Whats the solution? I prefer javascript solution.

Bootstrap Modal Part

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Are you sure?

                <form method="post">

                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" name="delete_dividend" value="foo">Delete</button>

                </form>

Laravel Blade Template Part

@foreach($dividends_10 as $_dividend_data)

                      {{Portfolio\StockModel::select('short_name')->where('id',$_dividend_data['stock_id'])->value('short_name')}}
                      {{$_dividend_data['amount']}}
                      {{$_dividend_data['date']}}
                      Edit
                      Delete

                  @endforeach

Body:
Assuming id field as Primary key of your table.

First replace your Laravel Blade Template Part with below code::

@foreach($dividends_10 as $_dividend_data)
<tr>
  <td>{{Portfolio\StockModel::select('short_name')->where('id',$_dividend_data['stock_id'])->value('short_name')}}</td>
  <td>{{$_dividend_data['amount']}}</td>
  <td>{{$_dividend_data['date']}}</td>
  <td><a href="{{'dividends'}}">Edit</a></td>
  <td><a href="{{'#'}}" class="delete-mdoal" data-value="{{$_dividend_data['id']}}" data-toggle="modal" data-target="#myModal">Delete</a></td>
</tr>
@endforeach

After that use below jQuery to made delete button value dynamic:

$(document).ready(function (e) {
    $(document).on("click", ".delete-mdoal", function (e) {
        var delete_id = $(this).attr('data-value');
        $('button[name="delete_dividend"]').val(delete_id);
    });
});


问:
Function composition or pipe operator
I have two functions:

```<code>user=> (def tmp (classificator.db/get-questions classificator.db/db))
#'user/tmp
user=> (def result (map classificator.core/transform-data tmp))
#'user/result
</code>```

First function return data which I pass to second function.

I would like to write in one expression without tmp variable:

```<code>user=> (-> (classificator.db/get-questions classificator.db/db) (map classificator.core/transform-data))

IllegalArgumentException Don't know how to create ISeq from: classificator.core$transform_data  clojure.lang.RT.seqFrom (RT.java:542)
</code>```

Looks like I don't mistake in the -> macros usage. How can I fix it?

答:
The thread-first macro -> puts arguments in the first position of the remaining forms, but you want it to go at the end. You can use the thread-last macro ->> instead:

```<code>(->> (classificator.db/get-questions classificator.db/db)
     (map classificator.core/transform-data))
</code>```

or

```<code>(->> classificator.db/db
     (classificator.db/get-questions)
     (map classificator.core/transform-data)))
</code>```

Title: Function composition or pipe operator

Body:
I have two functions:

user=> (def tmp (classificator.db/get-questions classificator.db/db))
#'user/tmp
user=> (def result (map classificator.core/transform-data tmp))
#'user/result

First function return data which I pass to second function.

I would like to write in one expression without tmp variable:

user=> (-> (classificator.db/get-questions classificator.db/db) (map classificator.core/transform-data))

IllegalArgumentException Don't know how to create ISeq from: classificator.core$transform_data  clojure.lang.RT.seqFrom (RT.java:542)

Looks like I don't mistake in the -> macros usage. How can I fix it?

Body:
The thread-first macro -> puts arguments in the first position of the remaining forms, but you want it to go at the end. You can use the thread-last macro ->> instead:

(->> (classificator.db/get-questions classificator.db/db)
     (map classificator.core/transform-data))

or

(->> classificator.db/db
     (classificator.db/get-questions)
     (map classificator.core/transform-data)))


问:
How to make my unordered list in html clickable all over
Hello I was just wondering how to make the unordered list I have in my html clickable in the box and not just on the text. It is currently only redirecting if you click directly on the text.
here is my html

```<code>    <ul>
        <li><a href="index.html" class="button">Home</a></li>
        <li><a href="page 1.html" class="button">page 1</a></li>
        <li><a href="page 2.html" class="button">page 2</a></li>
        <li><a href="page 3.html" class="button">page 3</a></li>
        <li><a href="page 4.html" class="button">page 4</a></li>
    </ul>
</code>```

and here is my CSS

```<code>.menu ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.menu li {
padding: 8px;
margin-bottom: 7px;
background-color: #f0f;
color: white;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
transition-property: background-color;
transition-duration: 0.2s;
transition-timing-function: linear;
transition-delay: 0s;
}
.menu li:hover {
background-color: #0099cc;
}
.button {
text-decoration: none;
color:white;
}
</code>```

Thanks in advance.

答:
Add display: block; to your button element:

.menu ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.menu li {
  padding: 8px;
  margin-bottom: 7px;
  background-color: #f0f;
  color: white;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
  transition-property: background-color;
  transition-duration: 0.2s;
  transition-timing-function: linear;
  transition-delay: 0s;
}
.menu li:hover {

}
.button {
  text-decoration: none;
  color:red;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body class="Site" cz-shortcut-listen="true">

 <div class="container">
 <div id="main">

    <ul>
        <li>Home</li>
        <li>page 1</li>
        <li>page 2</li>
        <li>page 3</li>
        <li>page 4</li>
    </ul>

</body>
</html></code>```

Body:
Hello I was just wondering how to make the unordered list I have in my html clickable in the box and not just on the text. It is currently only redirecting if you click directly on the text.
here is my html

Home

page 1

page 2

page 3

page 4

and here is my CSS

.menu ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.menu li {
padding: 8px;
margin-bottom: 7px;
background-color: #f0f;
color: white;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
transition-property: background-color;
transition-duration: 0.2s;
transition-timing-function: linear;
transition-delay: 0s;
}
.menu li:hover {
background-color: #0099cc;
}
.button {
text-decoration: none;
color:white;
}

Thanks in advance.

Body:
Add display: block; to your button element:

.menu ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
.menu li {
  padding: 8px;
  margin-bottom: 7px;
  background-color: #f0f;
  color: white;
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
  transition-property: background-color;
  transition-duration: 0.2s;
  transition-timing-function: linear;
  transition-delay: 0s;
}
.menu li:hover {

}
.button {
  text-decoration: none;
  color:red;
  display: block;
}

<html>
<body class="Site" cz-shortcut-listen="true">

 <div class="container">
 <div id="main">

    <ul>
        <li><a href="index.html" class="button">Home</a></li>
        <li><a href="page 1.html" class="button">page 1</a></li>
        <li><a href="page 2.html" class="button">page 2</a></li>
        <li><a href="page 3.html" class="button">page 3</a></li>
        <li><a href="page 4.html" class="button">page 4</a></li>
    </ul>

</body>
</html>


答:
Try as below, change display of a tag to display:inline-block and assign it a width of 100% thus this works, as you can't change your html format so this works.

```<code>.menu li > a{
  width:100%;
  display:inline-block;
}
</code>```

.menu ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.menu li {
padding: 8px;
margin-bottom: 7px;
background-color: #f0f;
color: white;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
transition-property: background-color;
transition-duration: 0.2s;
transition-timing-function: linear;
transition-delay: 0s;
}
.menu li:hover {
background-color: #0099cc;
}
.menu li > a{
  width:100%;
  display:inline-block;
}
.button {
text-decoration: none;
color:white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="menu">
<ul>
        <li>Home</li>
        <li>page 1</li>
        <li>page 2</li>
        <li>page 3</li>
        <li>page 4</li>
    </ul>
    </div></code>```

Title: How to make my unordered list in html clickable all over

Body:
Try as below, change display of a tag to display:inline-block and assign it a width of 100% thus this works, as you can't change your html format so this works.

.menu li > a{
  width:100%;
  display:inline-block;
}

.menu ul {
list-style-type: none;
margin: 0;
padding: 0;
}
.menu li {
padding: 8px;
margin-bottom: 7px;
background-color: #f0f;
color: white;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
transition-property: background-color;
transition-duration: 0.2s;
transition-timing-function: linear;
transition-delay: 0s;
}
.menu li:hover {
background-color: #0099cc;
}
.menu li > a{
  width:100%;
  display:inline-block;
}
.button {
text-decoration: none;
color:white;
}

<div class="menu">
<ul>
        <li><a href="index.html" class="button">Home</a></li>
        <li><a href="page 1.html" class="button">page 1</a></li>
        <li><a href="page 2.html" class="button">page 2</a></li>
        <li><a href="page 3.html" class="button">page 3</a></li>
        <li><a href="page 4.html" class="button">page 4</a></li>
    </ul>
    </div>


问:
Ionic2 and Angular2 image upload example?
This code is not working..

<ion-item>
    <ion-label stacked>Name</ion-label>
    <ion-input ngControl="name" type="text" placeholder="Enter Category Name"></ion-input>
</ion-item>

<ion-item>
    <ion-label stacked>Image</ion-label>
    <ion-input ngControl="image" type="file" placeholder="Select Category Image"></ion-input>
</ion-item>```
</div>
</div>
</p>

<p>Is there any way to upload image file using Ion-input and get uploaded file in type script using formBuilder.?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>formBuilder.group({
  name:  ['', Validators.required],
  image: ['', Validators.required]
})</code>```

答:
To upload image to the server using Ionic 2 Framework, you have to use the Transfer plugin.
Install transfer plugin using

```<code>ionic plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/transfer
</code>```

Then call the upload function from Transfer class.

```<code>const fileTransfer: TransferObject = this.transfer.create();

  let options1: FileUploadOptions = {
     fileKey: 'file',
     fileName: 'name.jpg',
     headers: {}

  }

 fileTransfer.upload(imageDataLocalURL, 'http://localhost/ionic/upload.php',  options1)
.then((data) => {
 // success
 alert("success");
}, (err) => {
 // error
 alert("error"+JSON.stringify(err));
});
</code>```

Use the link to know more https://ampersandacademy.com/tutorials/ionic-framework-version-2/upload-an-image-to-the-php-server-using-ionic-2-transfer-and-camera-plugin

Body:
This code is not working..

<ion-item>
    <ion-label stacked>Name</ion-label>
    <ion-input ngControl="name" type="text" placeholder="Enter Category Name"></ion-input>
</ion-item>

<ion-item>
    <ion-label stacked>Image</ion-label>
    <ion-input ngControl="image" type="file" placeholder="Select Category Image"></ion-input>
</ion-item>

Is there any way to upload image file using Ion-input and get uploaded file in type script using formBuilder.?

formBuilder.group({
  name:  ['', Validators.required],
  image: ['', Validators.required]
})

Body:
To upload image to the server using Ionic 2 Framework, you have to use the Transfer plugin.
Install transfer plugin using

ionic plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/transfer

Then call the upload function from Transfer class.

const fileTransfer: TransferObject = this.transfer.create();

  let options1: FileUploadOptions = {
     fileKey: 'file',
     fileName: 'name.jpg',
     headers: {}

  }

 fileTransfer.upload(imageDataLocalURL, 'http://localhost/ionic/upload.php',  options1)
.then((data) => {
 // success
 alert("success");
}, (err) => {
 // error
 alert("error"+JSON.stringify(err));
});

Use the link to know more https://ampersandacademy.com/tutorials/ionic-framework-version-2/upload-an-image-to-the-php-server-using-ionic-2-transfer-and-camera-plugin


问:
Size of png file is reduced
I changed the last 4 bits of all pixels in a png image to zero. Why was the size of image reduced to less than half?. I believe png is lossless compression. Will I be able to retrieve the embedded data.(here I added 0000 to all pixels, but in actual case i need to add different data)  I'm using vb 2015. The code I used is attached below.

Dim image1 As Bitmap = New Bitmap("C:\STEG\originalimage.png")

```<code>        For i As Integer = 0 To image1.Height - 1
            For j As Integer = 0 To image1.Width - 1

                Dim value As Color = image1.GetPixel(j, i)
                Dim t1 As Byte = value.R
                Dim t2 As Byte = value.G
                Dim t3 As Byte = value.B

                t1 = t1 And 240
                t2 = t2 And 240
                t3 = t3 And 240
                image1.SetPixel(j, i, Color.FromArgb(255, t1, t2, t3))

            Next

        Next

        image1.Save("C:\STEG\originalimageedited.png")
</code>```

答:
PNG is a lossless image compression format, yes. However if it's lossless or not doesn't anything have to do with the great reduction in size. What affects it is how the compression algorithm works.

I don't know how PNG's algorithm work, but basically compression is about repeating data. For instance if the last 4 bits of every byte is 0000, like so:

```<code>1000 0000
0000 0000
1101 0000
0110 0000
</code>```

...then a compression algorithm could for example express it as:

```<code>repeat 0000 every 4 bits
</code>```

or:

```<code>1000 4-0
4-0  4-0
1101 4-0
0110 4-0

(4-0 indicates that it should write four '0' bits)
</code>```

which might only take up a few bytes in the compressed file, while in the uncompressed file these four bits make up half of every byte.

Thus if you have 1 KB = 1024 bytes of color data and compress it like the first example above, the file size will (roughly speaking) shrink to 512 bytes + the few bytes that indicate the repeat.

Title: Size of png file is reduced

Body:
I changed the last 4 bits of all pixels in a png image to zero. Why was the size of image reduced to less than half?. I believe png is lossless compression. Will I be able to retrieve the embedded data.(here I added 0000 to all pixels, but in actual case i need to add different data)  I'm using vb 2015. The code I used is attached below.

Dim image1 As Bitmap = New Bitmap("C:\STEG\originalimage.png")

        For i As Integer = 0 To image1.Height - 1
            For j As Integer = 0 To image1.Width - 1

                Dim value As Color = image1.GetPixel(j, i)
                Dim t1 As Byte = value.R
                Dim t2 As Byte = value.G
                Dim t3 As Byte = value.B

                t1 = t1 And 240
                t2 = t2 And 240
                t3 = t3 And 240
                image1.SetPixel(j, i, Color.FromArgb(255, t1, t2, t3))

            Next

        Next

        image1.Save("C:\STEG\originalimageedited.png")

Body:
PNG is a lossless image compression format, yes. However if it's lossless or not doesn't anything have to do with the great reduction in size. What affects it is how the compression algorithm works.

I don't know how PNG's algorithm work, but basically compression is about repeating data. For instance if the last 4 bits of every byte is 0000, like so:

1000 0000
0000 0000
1101 0000
0110 0000

...then a compression algorithm could for example express it as:

repeat 0000 every 4 bits

or:

1000 4-0
4-0  4-0
1101 4-0
0110 4-0

(4-0 indicates that it should write four '0' bits)

which might only take up a few bytes in the compressed file, while in the uncompressed file these four bits make up half of every byte.

Thus if you have 1 KB = 1024 bytes of color data and compress it like the first example above, the file size will (roughly speaking) shrink to 512 bytes + the few bytes that indicate the repeat.


问:
How To Determine How Much Data Left In The Log
I have 2 servers set up using MySQL. It's using a standard replication setup, with one slave, no circular replication.

Is there a way to programmatically tell how far behind the slave is in reading the data from the binary log?

If I run the statement:

```<code>SHOW MASTER STATUS;
</code>```

On the master, and run

```<code>SHOW SLAVE STATUS;
</code>```

on the slave, I can compare the Position column from master status, and the Read_Master_Log_Pos column from slave status to determine how far behind the slave is.

However, this only works if the slave is reading from the same file the master is writing to.  So if the slave is still reading a previous log file, because it is running behind, I can't figure out how to determine how much data is left until it catches up to the current position that the master is at.  A solution using only SQL would be optimal, but I'm open to other solutions.  Hopefully not one that requires reading the directory containing the log files.

答: I like to use the 'Seconds_behind_master' field from SHOW SLAVE STATUS in order to determine if the MASTER-SLAVE servers are caught up.  As a secondary guard I also to a COUNT(*) query on a specific table (ie one that gets updated frequently) on both servers and then compare the record counts.</p>

Body:
I have 2 servers set up using MySQL. It's using a standard replication setup, with one slave, no circular replication.

Is there a way to programmatically tell how far behind the slave is in reading the data from the binary log?

If I run the statement:

SHOW MASTER STATUS;

On the master, and run

SHOW SLAVE STATUS;

on the slave, I can compare the Position column from master status, and the Read_Master_Log_Pos column from slave status to determine how far behind the slave is.

However, this only works if the slave is reading from the same file the master is writing to.  So if the slave is still reading a previous log file, because it is running behind, I can't figure out how to determine how much data is left until it catches up to the current position that the master is at.  A solution using only SQL would be optimal, but I'm open to other solutions.  Hopefully not one that requires reading the directory containing the log files.


问:
Why use binary shifts in enums
I'm looking at this code:

```<code>/**
 * Bitmask of states
 */
export const enum ViewState {
    FirstCheck = 1 << 0,      // result is 1
    ChecksEnabled = 1 << 1,   // result is 2
    Errored = 1 << 2,         // result is 4
    Destroyed = 1 << 3        // result is 8
}
</code>```

I don't understand why not simply specify the integer results there or integer numbers 0,1,2,3. Does anyone have any idea?

答:
Because it's easier to read (it is for me anyways and apparently the author as well). As this list grows its much easier (for a human) to add a 16th element and use 1<<15 then figure out what the resulting value would be. So just a matter of preference

The reason for using shifts is that you can combine multiple states into a single value. Example: A value of 6 would be Errored and ChecksEnabled.

```<code>var combined = ViewState.ChecksEnabled | ViewState.Errored;

var isChecksEnabled = (combined & ViewState.ChecksEnabled) == ViewState.ChecksEnabled;
// or
var isChecksEnabled = !!(combined & ViewState.ChecksEnabled);
</code>```

Title: Why use binary shifts in enums

Body:
I'm looking at this code:

/**
 * Bitmask of states
 */
export const enum ViewState {
    FirstCheck = 1 << 0,      // result is 1
    ChecksEnabled = 1 << 1,   // result is 2
    Errored = 1 << 2,         // result is 4
    Destroyed = 1 << 3        // result is 8
}

I don't understand why not simply specify the integer results there or integer numbers 0,1,2,3. Does anyone have any idea?

Body:
Because it's easier to read (it is for me anyways and apparently the author as well). As this list grows its much easier (for a human) to add a 16th element and use 1<<15 then figure out what the resulting value would be. So just a matter of preference

The reason for using shifts is that you can combine multiple states into a single value. Example: A value of 6 would be Errored and ChecksEnabled.

var combined = ViewState.ChecksEnabled | ViewState.Errored;

var isChecksEnabled = (combined & ViewState.ChecksEnabled) == ViewState.ChecksEnabled;
// or
var isChecksEnabled = !!(combined & ViewState.ChecksEnabled);