问:
cannot access net.sf.ehcache.CacheManager, class file for net.sf.ehcache.CacheManager not found
I have been implementing some caching in my project using EhCache. I have added following dependencies to my pom.xml

```<code><!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.3.1</version>
</dependency>
</code>```

Note the third dependency which is for EhCache. In all the tutorials I found online, the group id is different. The reason for me to change the group id was it had been moved to org.ehcache.

I have the following ehcache.xml file in my classpath.

```<code><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true"
         monitoring="autodetect"
         dynamicConfig="true">

    <diskStore path="java.io.tmpdir"/>

    <cache name="cardTypes"
           maxEntriesLocalHeap="100"
           maxEntriesLocalDisk="1000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>
</code>```

Following is my configuration file.

```<code>import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.core.io.ClassPathResource;

@EnableCaching
@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
        factory.setConfigLocation(new ClassPathResource("ehcache.xml"));
        factory.setShared(true);
        return factory;
    }

}
</code>```

Now, I am getting an error in following line.

```<code>return new EhCacheCacheManager(ehCacheCacheManager().getObject());
</code>```

That is:

In Eclipse:-

The type net.sf.ehcache.CacheManager cannot be resolved. It is
  indirectly referenced from required .class files

In JIdea:

```<code>Error:(21, 71) java: cannot access net.sf.ehcache.CacheManager
  class file for net.sf.ehcache.CacheManager not found
</code>```

I have not added any net.sf.ehcache stuff into my project. As I mentioned before, the ehcache has been moved to org.ehcache.

Why I am getting this error? It is related to net.sf.ehcache which is not a part of the dependencies I have added.

Should I code the second bean in a different way since the artifact has been moved? or how can I get this resolved?

答:
Ehcache 2 is in the net.sf.ehcache package. Most tutorial are about it since it had a long and useful life. Ehcache 3, the version you configured, is quite new (but of course better) and in the org.ehcache package.

The package moved because having its own domain was nicer but also because the new version is quite different and be able to cohabit with the old version can be necessary (because of some framework using it).

Your error comes from the fact that EhCacheCacheManager is using Ehcache 2. Ehcache 3 doesn't need it because it is JCache compliant. So you can use JCacheCacheManager instead.

So, right now, you have the Spring wiring and an ehcache.xml for Ehcache 2. And a dependency to Ehcache 3. You should align them to fix your problem.

To use Ehcache 3, the easiest is to add this in your application.properties

```<code>spring.cache.jcache.config=ehcache.xml
</code>```

And this:

```<code>@EnableCaching
@Configuration
public class CacheConfig {
}
</code>```

And that's it.

Body:
I have been implementing some caching in my project using EhCache. I have added following dependencies to my pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.3.8.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.3.1</version>
</dependency>

Note the third dependency which is for EhCache. In all the tutorials I found online, the group id is different. The reason for me to change the group id was it had been moved to org.ehcache.

I have the following ehcache.xml file in my classpath.

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true"
         monitoring="autodetect"
         dynamicConfig="true">

    <diskStore path="java.io.tmpdir"/>

    <cache name="cardTypes"
           maxEntriesLocalHeap="100"
           maxEntriesLocalDisk="1000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LFU"
           transactionalMode="off">
        <persistence strategy="localTempSwap"/>
    </cache>

</ehcache>

Following is my configuration file.

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.core.io.ClassPathResource;

@EnableCaching
@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheCacheManager().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean ehCacheCacheManager() {
        EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
        factory.setConfigLocation(new ClassPathResource("ehcache.xml"));
        factory.setShared(true);
        return factory;
    }

}

Now, I am getting an error in following line.

return new EhCacheCacheManager(ehCacheCacheManager().getObject());

That is:

In Eclipse:-

The type net.sf.ehcache.CacheManager cannot be resolved. It is
  indirectly referenced from required .class files

In JIdea:

Error:(21, 71) java: cannot access net.sf.ehcache.CacheManager
  class file for net.sf.ehcache.CacheManager not found

I have not added any net.sf.ehcache stuff into my project. As I mentioned before, the ehcache has been moved to org.ehcache.

Why I am getting this error? It is related to net.sf.ehcache which is not a part of the dependencies I have added.

Should I code the second bean in a different way since the artifact has been moved? or how can I get this resolved?

Body:
Ehcache 2 is in the net.sf.ehcache package. Most tutorial are about it since it had a long and useful life. Ehcache 3, the version you configured, is quite new (but of course better) and in the org.ehcache package.

The package moved because having its own domain was nicer but also because the new version is quite different and be able to cohabit with the old version can be necessary (because of some framework using it).

Your error comes from the fact that EhCacheCacheManager is using Ehcache 2. Ehcache 3 doesn't need it because it is JCache compliant. So you can use JCacheCacheManager instead.

So, right now, you have the Spring wiring and an ehcache.xml for Ehcache 2. And a dependency to Ehcache 3. You should align them to fix your problem.

To use Ehcache 3, the easiest is to add this in your application.properties

spring.cache.jcache.config=ehcache.xml

And this:

@EnableCaching
@Configuration
public class CacheConfig {
}

And that's it.


来源: stackexchange

问:
Planning Javascript Word API out of beta?
We currently use some functions from the beta release of the word API (https://appsforoffice.microsoft.com/lib/beta/hosted/office.js)

Does anybody know when functions like CreateDocument will be available in https://appsforoffice.microsoft.com/lib/1/hosted/Office.js

Our plugin is now rejected for the Office appstore because of the use of the beta js.

any info is appreciated!

答: You can monitor here for updates about when WordApi1.4 version is made available in GA. There is no definite date available yet. </p>

ContentLicense: CC BY-SA 3.0


问:
Where can I download the source for cron utility?
I have searched for the source for cron, to adapt it to modify/exend it. I cant locate it (thought it would be in coreutils).

Anyone knows where I can get the sources for cron?

BTW, I am running on Linux (Ubuntu 10.0.4)

答: apt-get source cron

ContentLicense: CC BY-SA 2.5

Body: apt-get source cron


问:
CMakeFiles/Makefile2:1429: recipe for target 'caffe2/CMakeFiles/conv_op_cache_cudnn_test.dir/all' failed
When I've installed all the prerequisites listed in the install page of caffe2, I type the command make && cd build && sudo make install the compile caffe2, then I got the following error, the 1st part is log file using Cmake.

cama@cama:/home/chaoyang/caffe2-master/build$ cmake ..
-- The CXX compiler identification is GNU 4.9.3
-- The C compiler identification is GNU 4.9.3
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Build type not set - defaulting to Release
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE

-- Found Protobuf: /usr/lib/x86_64-linux-gnu/libprotobuf.so

-- The BLAS backend of choice:Eigen
-- Could NOT find NNPACK (missing:  NNPACK_INCLUDE_DIR NNPACK_LIBRARY)
-- Will try to build NNPACK from source. If anything fails, follow the NNPACK prerequisite installation steps.
CMake Warning at cmake/External/nnpack.cmake:157 (message):
  NNPACK is chosen to be installed, but confu and ninja that are needed by it
  are not installed.  As a result we won't build with NNPACK.
Call Stack (most recent call first):
  cmake/Dependencies.cmake:52 (include)
  CMakeLists.txt:72 (include)

CMake Warning at cmake/Dependencies.cmake:57 (message):
  Not compiling with NNPACK.  Suppress this warning with -DUSE_NNPACK=OFF
Call Stack (most recent call first):
  CMakeLists.txt:72 (include)

-- Found GFlags: /usr/include

-- Found gflags  (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libgflags.so)
-- Found system gflags install.
-- Found Glog: /usr/include

-- Found glog    (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libglog.so)
-- Found system glog install.
-- Found PythonInterp: /home/cama/anaconda3/bin/python (found version "3.6")
-- Could NOT find Benchmark (missing:  Benchmark_INCLUDE_DIR Benchmark_LIBRARY)
-- Found Git: /usr/bin/git (found version "2.7.4")
-- git Version: v0.0.0
-- Version: 0.0.0
-- Performing Test HAVE_CXX_FLAG_STD_CXX11
-- Performing Test HAVE_CXX_FLAG_STD_CXX11 - Success
-- Performing Test HAVE_CXX_FLAG_WALL
-- Performing Test HAVE_CXX_FLAG_WALL - Success
-- Performing Test HAVE_CXX_FLAG_WEXTRA
-- Performing Test HAVE_CXX_FLAG_WEXTRA - Success
-- Performing Test HAVE_CXX_FLAG_WSHADOW
-- Performing Test HAVE_CXX_FLAG_WSHADOW - Success
-- Performing Test HAVE_CXX_FLAG_WERROR
-- Performing Test HAVE_CXX_FLAG_WERROR - Success
-- Performing Test HAVE_CXX_FLAG_PEDANTIC
-- Performing Test HAVE_CXX_FLAG_PEDANTIC - Success
-- Performing Test HAVE_CXX_FLAG_PEDANTIC_ERRORS
-- Performing Test HAVE_CXX_FLAG_PEDANTIC_ERRORS - Success
-- Performing Test HAVE_CXX_FLAG_WSHORTEN_64_TO_32
-- Performing Test HAVE_CXX_FLAG_WSHORTEN_64_TO_32 - Failed
-- Performing Test HAVE_CXX_FLAG_WFLOAT_EQUAL
-- Performing Test HAVE_CXX_FLAG_WFLOAT_EQUAL - Success
-- Performing Test HAVE_CXX_FLAG_FSTRICT_ALIASING
-- Performing Test HAVE_CXX_FLAG_FSTRICT_ALIASING - Success
-- Performing Test HAVE_CXX_FLAG_WZERO_AS_NULL_POINTER_CONSTANT
-- Performing Test HAVE_CXX_FLAG_WZERO_AS_NULL_POINTER_CONSTANT - Success
-- Performing Test HAVE_CXX_FLAG_WSTRICT_ALIASING
-- Performing Test HAVE_CXX_FLAG_WSTRICT_ALIASING - Success
-- Performing Test HAVE_CXX_FLAG_WTHREAD_SAFETY
-- Performing Test HAVE_CXX_FLAG_WTHREAD_SAFETY - Failed
-- Performing Test HAVE_CXX_FLAG_COVERAGE
-- Performing Test HAVE_CXX_FLAG_COVERAGE - Success
-- Performing Test HAVE_STD_REGEX
-- Performing Test HAVE_STD_REGEX -- success
-- Performing Test HAVE_GNU_POSIX_REGEX
-- Performing Test HAVE_GNU_POSIX_REGEX -- failed to compile
-- Performing Test HAVE_POSIX_REGEX
-- Performing Test HAVE_POSIX_REGEX -- success
-- Performing Test HAVE_STEADY_CLOCK
-- Performing Test HAVE_STEADY_CLOCK -- success
-- Performing Test BENCHMARK_HAS_CXX03_FLAG
-- Performing Test BENCHMARK_HAS_CXX03_FLAG - Success
-- Found LMDB: /usr/include

-- Found lmdb    (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/liblmdb.so)
-- Found LevelDB: /usr/include

-- Found LevelDB (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libleveldb.so)
-- Found Snappy: /usr/include

-- Found Snappy  (include: /usr/include, library: /usr/lib/libsnappy.so)
-- Could NOT find RocksDB (missing:  RocksDB_INCLUDE_DIR RocksDB_LIBRARIES)
CMake Warning at cmake/Dependencies.cmake:138 (message):
  Not compiling with RocksDB.  Suppress this warning with -DUSE_ROCKSDB=OFF
Call Stack (most recent call first):
  CMakeLists.txt:72 (include)

CMake Warning at cmake/Dependencies.cmake:181 (message):
  Not compiling with OpenCV.  Suppress this warning with -DUSE_OPENCV=OFF
Call Stack (most recent call first):
  CMakeLists.txt:72 (include)

CMake Warning at cmake/Dependencies.cmake:201 (find_package):
  By not providing "FindEigen3.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Eigen3", but
  CMake did not find one.

Could not find a package configuration file provided by "Eigen3" with any
  of the following names:

```<code>Eigen3Config.cmake
eigen3-config.cmake
</code>```

Add the installation prefix of "Eigen3" to CMAKE_PREFIX_PATH or set
  "Eigen3_DIR" to a directory containing one of the above files.  If "Eigen3"
  provides a separate development package or SDK, be sure it has been
  installed.
Call Stack (most recent call first):
  CMakeLists.txt:72 (include)

-- Found PythonInterp: /home/cama/anaconda3/bin/python (found suitable version "3.6", minimum required is "2.7")
-- Found PythonLibs: /home/cama/anaconda3/lib/libpython3.6m.so (found suitable version "3.6.0", minimum required is "2.7")
-- Found NumPy: /home/cama/anaconda3/lib/python3.6/site-packages/numpy/core/include (found version "1.11.3")
-- NumPy ver. 1.11.3 found (include: /home/cama/anaconda3/lib/python3.6/site-packages/numpy/core/include)
-- Could NOT find pybind11 (missing:  pybind11_INCLUDE_DIR)
-- Could NOT find MPI_C (missing:  MPI_C_LIBRARIES MPI_C_INCLUDE_PATH)
-- Could NOT find MPI_CXX (missing:  MPI_CXX_LIBRARIES MPI_CXX_INCLUDE_PATH)
CMake Warning at cmake/Dependencies.cmake:257 (message):
  Not compiling with MPI.  Suppress this warning with -DUSE_MPI=OFF
Call Stack (most recent call first):
  CMakeLists.txt:72 (include)

-- Try OpenMP C flag = [-fopenmp]
-- Performing Test OpenMP_FLAG_DETECTED
-- Performing Test OpenMP_FLAG_DETECTED - Success
-- Try OpenMP CXX flag = [-fopenmp]
-- Performing Test OpenMP_FLAG_DETECTED
-- Performing Test OpenMP_FLAG_DETECTED - Success
-- Found OpenMP: -fopenmp

-- Adding -fopenmp
-- CUDA detected: 8.0
-- Added CUDA NVCC flags for: sm_61
-- Found libcuda: /usr/local/cuda-8.0/lib64/stubs/libcuda.so
-- Found libnvrtc: /usr/local/cuda-8.0/lib64/libnvrtc.so
-- Found CUDNN: /usr/local/cuda-8.0/include

-- Found cuDNN: v5.1.5  (include: /usr/local/cuda-8.0/include, library: /usr/local/cuda-8.0/lib64/libcudnn.so)
-- Could NOT find NCCL (missing:  NCCL_INCLUDE_DIR NCCL_LIBRARY)
-- NCCL: /home/chaoyang/caffe2-master/third_party/nccl/build/lib/libnccl_static.a
-- Could NOT find CUB (missing:  CUB_INCLUDE_DIR)
-- Could NOT find Gloo (missing:  Gloo_INCLUDE_DIR Gloo_LIBRARY)
-- Found CUDA: /usr/local/cuda-8.0 (found suitable version "8.0", minimum required is "7.0")
-- CUDA detected: 8.0
-- Found libcuda: /usr/local/cuda-8.0/lib64/stubs/libcuda.so
-- Found libnvrtc: /usr/local/cuda-8.0/lib64/libnvrtc.so
-- Performing Test CAFFE2_LONG_IS_INT32_OR_64
-- Performing Test CAFFE2_LONG_IS_INT32_OR_64 - Success
-- Does not need to define long separately.
-- Performing Test HAS_BUILTIN_CPU_SUPPORTS
-- Performing Test HAS_BUILTIN_CPU_SUPPORTS - Success
-- This compiler has builtin_cpu_supports feature.
-- Performing Test CAFFE2_NEED_TO_TURN_OFF_DEPRECATION_WARNING
-- Performing Test CAFFE2_NEED_TO_TURN_OFF_DEPRECATION_WARNING - Failed
-- Turning off deprecation warning due to glog.
-- GCC 4.9.3: Adding gcc and gcc_s libs to link line
-- Include NCCL operators
-- Excluding image processing operators due to no opencv
-- Excluding video processing operators due to no opencv
-- Excluding mkl operators as we are not using mkl
-- MPI operators skipped due to no MPI support

-- Automatically generating missing init.py files.

-- ******** Summary ********
-- General:
--   Git version           :
--   System                : Linux
--   C++ compiler          : /usr/bin/c++
--   C++ compiler version  : 4.9.3
--   Protobuf compiler     : /usr/bin/protoc
--   CXX flags             :  -fopenmp -Wno-deprecated -std=c++11 -fPIC -Wno-narrowing
--   Build type            : Release

--   Compile definitions   : CAFFE2_USE_EIGEN_FOR_BLAS;CAFFE2_USE_GOOGLE_GLOG;CAFFE2_USE_GFLAGS;EIGEN_MPL2_ONLY

--   BUILD_SHARED_LIBS     : ON
--   BUILD_PYTHON          : ON
--     Python version      : 3.6.0
--     Python library      : /home/cama/anaconda3/lib/libpython3.6m.so
--   USE_CUDA              : ON
--     CUDA version        : 8.0
--   USE_CNMEM             : OFF
--   USE_NERVANA_GPU       : OFF
--   USE_GLOG              : ON
--   USE_GFLAGS            : ON
--   USE_LMDB              : ON
--     LMDB version        : 0.9.10
--   USE_LEVELDB           : ON
--     LevelDB version     : 1.15
--     Snappy version      : 1.1.0
--   USE_OPENCV            : OFF
--   USE_FFMPEG            :
--   USE_ZMQ               : OFF
--   USE_ROCKSDB           : OFF
--   USE_MPI               : OFF
--   USE_NCCL              : ON
--   USE_NNPACK            : OFF
--   USE_OPENMP            : ON
--   USE_REDIS             : OFF
--   USE_GLOO              : ON
-- Configuring done
-- Generating done
-- Build files have been written to: /home/chaoyang/caffe2-master/build

The following is the normal output of make. Please focus on the last lines for the reason that these indicate the errors.

[ 77%] Building CXX object caffe2/CMakeFiles/conv_op_cache_cudnn_test.dir/operators/conv_op_cache_cudnn_test.cc.o
[ 77%] Linking CXX executable binaries/conv_op_cache_cudnn_test
libCaffe2_CPU.so: undefined reference to gflags::SetUsageMessage(std::string const&)'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::internal::WireFormatLite::ReadString(google::protobuf::io::CodedInputStream*, std::string*)'
libCaffe2_CPU.so: undefined reference to google::protobuf::Message::GetTypeName() const'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::internal::StringTypeHandlerBase::Delete(std::string*)'
libCaffe2_GPU.so: undefined reference to google::protobuf::internal::kEmptyString'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::MessageLite::SerializeToString(std::string*) const'
libCaffe2_CPU.so: undefined reference to google::protobuf::MessageFactory::InternalRegisterGeneratedFile(char const*, void (*)(std::string const&))'
libCaffe2_GPU.so: undefined reference togoogle::protobuf::TextFormat::ParseFromString(std::string const&, google::protobuf::Message*)'
libCaffe2_GPU.so: undefined reference to google::base::CheckOpMessageBuilder::NewString()'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::internal::WireFormatLite::WriteBytes(int, std::string const&, google::protobuf::io::CodedOutputStream*)'
libCaffe2_GPU.so: undefined reference to google::protobuf::internal::StringTypeHandlerBase::New()'
libCaffe2_CPU.so: undefined reference togflags::ParseCommandLineFlags(int*, char***, bool)'
libCaffe2_GPU.so: undefined reference to google::protobuf::Message::ShortDebugString() const'
libCaffe2_GPU.so: undefined reference togoogle::protobuf::MessageLite::ParseFromString(std::string const&)'
libCaffe2_GPU.so: undefined reference to gflags::FlagRegisterer::FlagRegisterer(char const*, char const*, char const*, char const*, void*, void*)'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::internal::WireFormatLite::WriteString(int, std::string const&, google::protobuf::io::CodedOutputStream*)'
libCaffe2_GPU.so: undefined reference to google::protobuf::internal::ParseNamedEnum(google::protobuf::EnumDescriptor const*, std::string const&, int*)'
libCaffe2_GPU.so: undefined reference togoogle::protobuf::MessageLite::SerializeAsString() const'
libCaffe2_CPU.so: undefined reference to google::protobuf::DescriptorPool::FindFileByName(std::string const&) const'
libCaffe2_CPU.so: undefined reference togflags::ProgramUsage()'
libCaffe2_CPU.so: undefined reference to google::protobuf::internal::WireFormatLite::ReadBytes(google::protobuf::io::CodedInputStream*, std::string*)'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::Message::InitializationErrorString() const'
collect2: error: ld returned 1 exit status
caffe2/CMakeFiles/conv_op_cache_cudnn_test.dir/build.make:130: recipe for target 'caffe2/binaries/conv_op_cache_cudnn_test' failed
make[3]: * [caffe2/binaries/conv_op_cache_cudnn_test] Error 1
make[3]: Leaving directory '/home/chaoyang/caffe2-master/build'
CMakeFiles/Makefile2:1429: recipe for target 'caffe2/CMakeFiles/conv_op_cache_cudnn_test.dir/all' failed
make[2]:  [caffe2/CMakeFiles/conv_op_cache_cudnn_test.dir/all] Error 2
make[2]: Leaving directory '/home/chaoyang/caffe2-master/build'
Makefile:138: recipe for target 'all' failed
make[1]:  [all] Error 2
make[1]: Leaving directory '/home/chaoyang/caffe2-master/build'
Makefile:4: recipe for target 'all' failed
make: * [all] Error 2

It seems that cudnn library caused this error, while I've successfully used cudnn-v5.1 and cuda-8.0 in ubuntu, specifically, in matconvnet, which requires cuda and cudnn for accelerating the computation speed. And it seems no one else has got this error before, so any advice will be appreciated!

答:
it's hard for me to follow the log, but your command doesn't seem right.
I suggest you do cd build && cmake .. && sudo make install.

Body:
When I've installed all the prerequisites listed in the install page of caffe2, I type the command make && cd build && sudo make install the compile caffe2, then I got the following error, the 1st part is log file using Cmake.

cama@cama:/home/chaoyang/caffe2-master/build$ cmake ..
-- The CXX compiler identification is GNU 4.9.3
-- The C compiler identification is GNU 4.9.3
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Build type not set - defaulting to Release
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE

-- Found Protobuf: /usr/lib/x86_64-linux-gnu/libprotobuf.so

-- The BLAS backend of choice:Eigen
-- Could NOT find NNPACK (missing:  NNPACK_INCLUDE_DIR NNPACK_LIBRARY)
-- Will try to build NNPACK from source. If anything fails, follow the NNPACK prerequisite installation steps.
CMake Warning at cmake/External/nnpack.cmake:157 (message):
  NNPACK is chosen to be installed, but confu and ninja that are needed by it
  are not installed.  As a result we won't build with NNPACK.
Call Stack (most recent call first):
  cmake/Dependencies.cmake:52 (include)
  CMakeLists.txt:72 (include)

CMake Warning at cmake/Dependencies.cmake:57 (message):
  Not compiling with NNPACK.  Suppress this warning with -DUSE_NNPACK=OFF
Call Stack (most recent call first):
  CMakeLists.txt:72 (include)

-- Found GFlags: /usr/include

-- Found gflags  (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libgflags.so)
-- Found system gflags install.
-- Found Glog: /usr/include

-- Found glog    (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libglog.so)
-- Found system glog install.
-- Found PythonInterp: /home/cama/anaconda3/bin/python (found version "3.6")
-- Could NOT find Benchmark (missing:  Benchmark_INCLUDE_DIR Benchmark_LIBRARY)
-- Found Git: /usr/bin/git (found version "2.7.4")
-- git Version: v0.0.0
-- Version: 0.0.0
-- Performing Test HAVE_CXX_FLAG_STD_CXX11
-- Performing Test HAVE_CXX_FLAG_STD_CXX11 - Success
-- Performing Test HAVE_CXX_FLAG_WALL
-- Performing Test HAVE_CXX_FLAG_WALL - Success
-- Performing Test HAVE_CXX_FLAG_WEXTRA
-- Performing Test HAVE_CXX_FLAG_WEXTRA - Success
-- Performing Test HAVE_CXX_FLAG_WSHADOW
-- Performing Test HAVE_CXX_FLAG_WSHADOW - Success
-- Performing Test HAVE_CXX_FLAG_WERROR
-- Performing Test HAVE_CXX_FLAG_WERROR - Success
-- Performing Test HAVE_CXX_FLAG_PEDANTIC
-- Performing Test HAVE_CXX_FLAG_PEDANTIC - Success
-- Performing Test HAVE_CXX_FLAG_PEDANTIC_ERRORS
-- Performing Test HAVE_CXX_FLAG_PEDANTIC_ERRORS - Success
-- Performing Test HAVE_CXX_FLAG_WSHORTEN_64_TO_32
-- Performing Test HAVE_CXX_FLAG_WSHORTEN_64_TO_32 - Failed
-- Performing Test HAVE_CXX_FLAG_WFLOAT_EQUAL
-- Performing Test HAVE_CXX_FLAG_WFLOAT_EQUAL - Success
-- Performing Test HAVE_CXX_FLAG_FSTRICT_ALIASING
-- Performing Test HAVE_CXX_FLAG_FSTRICT_ALIASING - Success
-- Performing Test HAVE_CXX_FLAG_WZERO_AS_NULL_POINTER_CONSTANT
-- Performing Test HAVE_CXX_FLAG_WZERO_AS_NULL_POINTER_CONSTANT - Success
-- Performing Test HAVE_CXX_FLAG_WSTRICT_ALIASING
-- Performing Test HAVE_CXX_FLAG_WSTRICT_ALIASING - Success
-- Performing Test HAVE_CXX_FLAG_WTHREAD_SAFETY
-- Performing Test HAVE_CXX_FLAG_WTHREAD_SAFETY - Failed
-- Performing Test HAVE_CXX_FLAG_COVERAGE
-- Performing Test HAVE_CXX_FLAG_COVERAGE - Success
-- Performing Test HAVE_STD_REGEX
-- Performing Test HAVE_STD_REGEX -- success
-- Performing Test HAVE_GNU_POSIX_REGEX
-- Performing Test HAVE_GNU_POSIX_REGEX -- failed to compile
-- Performing Test HAVE_POSIX_REGEX
-- Performing Test HAVE_POSIX_REGEX -- success
-- Performing Test HAVE_STEADY_CLOCK
-- Performing Test HAVE_STEADY_CLOCK -- success
-- Performing Test BENCHMARK_HAS_CXX03_FLAG
-- Performing Test BENCHMARK_HAS_CXX03_FLAG - Success
-- Found LMDB: /usr/include

-- Found lmdb    (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/liblmdb.so)
-- Found LevelDB: /usr/include

-- Found LevelDB (include: /usr/include, library: /usr/lib/x86_64-linux-gnu/libleveldb.so)
-- Found Snappy: /usr/include

-- Found Snappy  (include: /usr/include, library: /usr/lib/libsnappy.so)
-- Could NOT find RocksDB (missing:  RocksDB_INCLUDE_DIR RocksDB_LIBRARIES)
CMake Warning at cmake/Dependencies.cmake:138 (message):
  Not compiling with RocksDB.  Suppress this warning with -DUSE_ROCKSDB=OFF
Call Stack (most recent call first):
  CMakeLists.txt:72 (include)

CMake Warning at cmake/Dependencies.cmake:181 (message):
  Not compiling with OpenCV.  Suppress this warning with -DUSE_OPENCV=OFF
Call Stack (most recent call first):
  CMakeLists.txt:72 (include)

CMake Warning at cmake/Dependencies.cmake:201 (find_package):
  By not providing "FindEigen3.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Eigen3", but
  CMake did not find one.

Could not find a package configuration file provided by "Eigen3" with any
  of the following names:

Eigen3Config.cmake
eigen3-config.cmake

Add the installation prefix of "Eigen3" to CMAKE_PREFIX_PATH or set
  "Eigen3_DIR" to a directory containing one of the above files.  If "Eigen3"
  provides a separate development package or SDK, be sure it has been
  installed.
Call Stack (most recent call first):
  CMakeLists.txt:72 (include)

-- Found PythonInterp: /home/cama/anaconda3/bin/python (found suitable version "3.6", minimum required is "2.7")
-- Found PythonLibs: /home/cama/anaconda3/lib/libpython3.6m.so (found suitable version "3.6.0", minimum required is "2.7")
-- Found NumPy: /home/cama/anaconda3/lib/python3.6/site-packages/numpy/core/include (found version "1.11.3")
-- NumPy ver. 1.11.3 found (include: /home/cama/anaconda3/lib/python3.6/site-packages/numpy/core/include)
-- Could NOT find pybind11 (missing:  pybind11_INCLUDE_DIR)
-- Could NOT find MPI_C (missing:  MPI_C_LIBRARIES MPI_C_INCLUDE_PATH)
-- Could NOT find MPI_CXX (missing:  MPI_CXX_LIBRARIES MPI_CXX_INCLUDE_PATH)
CMake Warning at cmake/Dependencies.cmake:257 (message):
  Not compiling with MPI.  Suppress this warning with -DUSE_MPI=OFF
Call Stack (most recent call first):
  CMakeLists.txt:72 (include)

-- Try OpenMP C flag = [-fopenmp]
-- Performing Test OpenMP_FLAG_DETECTED
-- Performing Test OpenMP_FLAG_DETECTED - Success
-- Try OpenMP CXX flag = [-fopenmp]
-- Performing Test OpenMP_FLAG_DETECTED
-- Performing Test OpenMP_FLAG_DETECTED - Success
-- Found OpenMP: -fopenmp

-- Adding -fopenmp
-- CUDA detected: 8.0
-- Added CUDA NVCC flags for: sm_61
-- Found libcuda: /usr/local/cuda-8.0/lib64/stubs/libcuda.so
-- Found libnvrtc: /usr/local/cuda-8.0/lib64/libnvrtc.so
-- Found CUDNN: /usr/local/cuda-8.0/include

-- Found cuDNN: v5.1.5  (include: /usr/local/cuda-8.0/include, library: /usr/local/cuda-8.0/lib64/libcudnn.so)
-- Could NOT find NCCL (missing:  NCCL_INCLUDE_DIR NCCL_LIBRARY)
-- NCCL: /home/chaoyang/caffe2-master/third_party/nccl/build/lib/libnccl_static.a
-- Could NOT find CUB (missing:  CUB_INCLUDE_DIR)
-- Could NOT find Gloo (missing:  Gloo_INCLUDE_DIR Gloo_LIBRARY)
-- Found CUDA: /usr/local/cuda-8.0 (found suitable version "8.0", minimum required is "7.0")
-- CUDA detected: 8.0
-- Found libcuda: /usr/local/cuda-8.0/lib64/stubs/libcuda.so
-- Found libnvrtc: /usr/local/cuda-8.0/lib64/libnvrtc.so
-- Performing Test CAFFE2_LONG_IS_INT32_OR_64
-- Performing Test CAFFE2_LONG_IS_INT32_OR_64 - Success
-- Does not need to define long separately.
-- Performing Test HAS_BUILTIN_CPU_SUPPORTS
-- Performing Test HAS_BUILTIN_CPU_SUPPORTS - Success
-- This compiler has builtin_cpu_supports feature.
-- Performing Test CAFFE2_NEED_TO_TURN_OFF_DEPRECATION_WARNING
-- Performing Test CAFFE2_NEED_TO_TURN_OFF_DEPRECATION_WARNING - Failed
-- Turning off deprecation warning due to glog.
-- GCC 4.9.3: Adding gcc and gcc_s libs to link line
-- Include NCCL operators
-- Excluding image processing operators due to no opencv
-- Excluding video processing operators due to no opencv
-- Excluding mkl operators as we are not using mkl
-- MPI operators skipped due to no MPI support

-- Automatically generating missing init.py files.

-- ******** Summary ********
-- General:
--   Git version           :
--   System                : Linux
--   C++ compiler          : /usr/bin/c++
--   C++ compiler version  : 4.9.3
--   Protobuf compiler     : /usr/bin/protoc
--   CXX flags             :  -fopenmp -Wno-deprecated -std=c++11 -fPIC -Wno-narrowing
--   Build type            : Release

--   Compile definitions   : CAFFE2_USE_EIGEN_FOR_BLAS;CAFFE2_USE_GOOGLE_GLOG;CAFFE2_USE_GFLAGS;EIGEN_MPL2_ONLY

--   BUILD_SHARED_LIBS     : ON
--   BUILD_PYTHON          : ON
--     Python version      : 3.6.0
--     Python library      : /home/cama/anaconda3/lib/libpython3.6m.so
--   USE_CUDA              : ON
--     CUDA version        : 8.0
--   USE_CNMEM             : OFF
--   USE_NERVANA_GPU       : OFF
--   USE_GLOG              : ON
--   USE_GFLAGS            : ON
--   USE_LMDB              : ON
--     LMDB version        : 0.9.10
--   USE_LEVELDB           : ON
--     LevelDB version     : 1.15
--     Snappy version      : 1.1.0
--   USE_OPENCV            : OFF
--   USE_FFMPEG            :
--   USE_ZMQ               : OFF
--   USE_ROCKSDB           : OFF
--   USE_MPI               : OFF
--   USE_NCCL              : ON
--   USE_NNPACK            : OFF
--   USE_OPENMP            : ON
--   USE_REDIS             : OFF
--   USE_GLOO              : ON
-- Configuring done
-- Generating done
-- Build files have been written to: /home/chaoyang/caffe2-master/build

The following is the normal output of make. Please focus on the last lines for the reason that these indicate the errors.

[ 77%] Building CXX object caffe2/CMakeFiles/conv_op_cache_cudnn_test.dir/operators/conv_op_cache_cudnn_test.cc.o
[ 77%] Linking CXX executable binaries/conv_op_cache_cudnn_test
libCaffe2_CPU.so: undefined reference to gflags::SetUsageMessage(std::string const&)'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::internal::WireFormatLite::ReadString(google::protobuf::io::CodedInputStream*, std::string*)'
libCaffe2_CPU.so: undefined reference to google::protobuf::Message::GetTypeName() const'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::internal::StringTypeHandlerBase::Delete(std::string*)'
libCaffe2_GPU.so: undefined reference to google::protobuf::internal::kEmptyString'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::MessageLite::SerializeToString(std::string*) const'
libCaffe2_CPU.so: undefined reference to google::protobuf::MessageFactory::InternalRegisterGeneratedFile(char const*, void (*)(std::string const&))'
libCaffe2_GPU.so: undefined reference togoogle::protobuf::TextFormat::ParseFromString(std::string const&, google::protobuf::Message*)'
libCaffe2_GPU.so: undefined reference to google::base::CheckOpMessageBuilder::NewString()'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::internal::WireFormatLite::WriteBytes(int, std::string const&, google::protobuf::io::CodedOutputStream*)'
libCaffe2_GPU.so: undefined reference to google::protobuf::internal::StringTypeHandlerBase::New()'
libCaffe2_CPU.so: undefined reference togflags::ParseCommandLineFlags(int*, char***, bool)'
libCaffe2_GPU.so: undefined reference to google::protobuf::Message::ShortDebugString() const'
libCaffe2_GPU.so: undefined reference togoogle::protobuf::MessageLite::ParseFromString(std::string const&)'
libCaffe2_GPU.so: undefined reference to gflags::FlagRegisterer::FlagRegisterer(char const*, char const*, char const*, char const*, void*, void*)'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::internal::WireFormatLite::WriteString(int, std::string const&, google::protobuf::io::CodedOutputStream*)'
libCaffe2_GPU.so: undefined reference to google::protobuf::internal::ParseNamedEnum(google::protobuf::EnumDescriptor const*, std::string const&, int*)'
libCaffe2_GPU.so: undefined reference togoogle::protobuf::MessageLite::SerializeAsString() const'
libCaffe2_CPU.so: undefined reference to google::protobuf::DescriptorPool::FindFileByName(std::string const&) const'
libCaffe2_CPU.so: undefined reference togflags::ProgramUsage()'
libCaffe2_CPU.so: undefined reference to google::protobuf::internal::WireFormatLite::ReadBytes(google::protobuf::io::CodedInputStream*, std::string*)'
libCaffe2_CPU.so: undefined reference togoogle::protobuf::Message::InitializationErrorString() const'
collect2: error: ld returned 1 exit status
caffe2/CMakeFiles/conv_op_cache_cudnn_test.dir/build.make:130: recipe for target 'caffe2/binaries/conv_op_cache_cudnn_test' failed
make[3]: * [caffe2/binaries/conv_op_cache_cudnn_test] Error 1
make[3]: Leaving directory '/home/chaoyang/caffe2-master/build'
CMakeFiles/Makefile2:1429: recipe for target 'caffe2/CMakeFiles/conv_op_cache_cudnn_test.dir/all' failed
make[2]:  [caffe2/CMakeFiles/conv_op_cache_cudnn_test.dir/all] Error 2
make[2]: Leaving directory '/home/chaoyang/caffe2-master/build'
Makefile:138: recipe for target 'all' failed
make[1]:  [all] Error 2
make[1]: Leaving directory '/home/chaoyang/caffe2-master/build'
Makefile:4: recipe for target 'all' failed
make: * [all] Error 2

It seems that cudnn library caused this error, while I've successfully used cudnn-v5.1 and cuda-8.0 in ubuntu, specifically, in matconvnet, which requires cuda and cudnn for accelerating the computation speed. And it seems no one else has got this error before, so any advice will be appreciated!


问:
What the difference with Angular code
I'm a little confused about this way of getting data from a component in Angular. Why or when should I use the public and get keywords, and is it even needed?

```<code>public get data$(): Observable<any> {
    return this._data$;
}
</code>```

In most examples I've seen it would be like this,

```<code>getData(){
    return this._data;
}
</code>```

Also does the $ have any special meaning?
I tried to google this, but can't seem to find an answer.

答: i dont think $ is anything special than what angular makes it like for terms like $scope $watch this are term created in the angular library and data is normally stored in variables like $scope.data mainly because of the $scope variable can interact with the DOM view ,hope this clears u rather than confuses u</p>

Title: What the difference with Angular code

Body:
I'm a little confused about this way of getting data from a component in Angular. Why or when should I use the public and get keywords, and is it even needed?

public get data$(): Observable<any> {
    return this._data$;
}

In most examples I've seen it would be like this,

getData(){
    return this._data;
}

Also does the $ have any special meaning?
I tried to google this, but can't seem to find an answer.


问:
How can i convert string to double ? I'm getting exception
```<code>for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
            }
        }
</code>```

The first number is 0.49052715 and the Convert.ToDouble of a is fine.
But when it's getting to the line:

```<code>double b = Convert.ToDouble(secondNumber);
</code>```

I'm getting exception:

FormatException: Unknown char: ,

But there is no any char/s at all the string in secondNumber is: 0.87142591

This is the whole string in transform: matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)

And i'm extracting the first two numbers: 0.49052715 and 0.87142591 and then trying to convert them to double. But getting the exception.

The code including the Rect.rectangles definition:

```<code>private void ParseSvgMap()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();

        for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
                float degree = FindDegree(a, b);
            }
        }
    }

    public static float FindDegree(double a, double b)
    {
        float value = (float)((System.Math.Atan2(a, b) / System.Math.PI) * 180f);
        if (value < 0) value += 360f;

        return value;
    }

    public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }
        public double degree { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }
</code>```

答:
You can write a method along the lines of :</p>

```<code> public double fixString(string incoming)
 {
  Double a;
  if(incoming.Contains(','))
  {
   string fixedNum = incoming.Remove(incoming.IndexOf(','));
   a = Convert.ToDouble(fixedNum);
   return a;
  }
  else
  {
   a = Convert.ToDouble(incoming);
   return a;
  }
 }
</code>```

Body:
for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
            }
        }

The first number is 0.49052715 and the Convert.ToDouble of a is fine.
But when it's getting to the line:

double b = Convert.ToDouble(secondNumber);

I'm getting exception:

FormatException: Unknown char: ,

But there is no any char/s at all the string in secondNumber is: 0.87142591

This is the whole string in transform: matrix(0.87142591,0.49052715,-0.49052715,0.87142591,0,0)

And i'm extracting the first two numbers: 0.49052715 and 0.87142591 and then trying to convert them to double. But getting the exception.

The code including the Rect.rectangles definition:

private void ParseSvgMap()
    {
        XDocument document = XDocument.Load(@"C:\Users\mysvg\Documents\my.svg");

        Rect.rectangles = document.Descendants().Where(x => x.Name.LocalName == "rect").Select(x => new Rect()
        {
            style = Rect.GetStyle((string)x.Attribute("style")),
            id = (string)x.Attribute("id"),
            width = (double)x.Attribute("width"),
            height = (double)x.Attribute("width"),
            x = (double?)x.Attribute("width"),
            y = (double?)x.Attribute("width"),
            transform = x.Attribute("transform") == null ? "" : (string)x.Attribute("transform")
        }).ToList();

        for(int i = 0; i < Rect.rectangles.Count; i++)
        {
            if (Rect.rectangles[i].transform != null && Rect.rectangles[i].transform != "")
            {
                string firstNumber = Rect.rectangles[i].transform.Substring(18, 10);
                string secondNumber = Rect.rectangles[i].transform.Substring(7, 10);
                double a = Convert.ToDouble(firstNumber);
                double b = Convert.ToDouble(secondNumber);
                float degree = FindDegree(a, b);
            }
        }
    }

    public static float FindDegree(double a, double b)
    {
        float value = (float)((System.Math.Atan2(a, b) / System.Math.PI) * 180f);
        if (value < 0) value += 360f;

        return value;
    }

    public class Rect
    {
        public static List<Rect> rectangles { get; set; }
        public Dictionary<string, string> style { get; set; }
        public string id { get; set; }
        public double width { get; set; }
        public double height { get; set; }
        public double? x { get; set; }
        public double? y { get; set; }
        public string transform { get; set; }
        public double degree { get; set; }

        public static Dictionary<string, string> GetStyle(string styles)
        {
            string pattern = @"(?'name'[^:]+):(?'value'.*)";
            string[] splitArray = styles.Split(new char[] { ';' });
            Dictionary<string, string> style = splitArray.Select(x => Regex.Match(x, pattern))
                .GroupBy(x => x.Groups["name"].Value, y => y.Groups["value"].Value)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());
            return style;
        }
    }

Body:
You can write a method along the lines of :

 public double fixString(string incoming)
 {
  Double a;
  if(incoming.Contains(','))
  {
   string fixedNum = incoming.Remove(incoming.IndexOf(','));
   a = Convert.ToDouble(fixedNum);
   return a;
  }
  else
  {
   a = Convert.ToDouble(incoming);
   return a;
  }
 }


问:
If-Else Statement C++ Error
I am having an issue with this if else statement. This is part of an bigger c++ program, but there is something wrong.

```<code>void owed(int classchoice)
{
  double cost;
  if (classchoice == 1)
    cost = 1750.00;
  else if  (classchoice == 2)
    cost = 1500.00;
  else (classchoice == 3);
    cost = 1000.00:

  cout << "You owe about: " << cost << endl;
  cout << "Enjoy your flight!\n\n\n";
}
</code>```

The output is ALWAYS 1000 dollars. I know for a fact that my input is correct, I have no idea what is wrong. Also I get an error at this point  "else (classchoice == 3);", it tells me to to put a semicolon after this statement, I do not know why. All the help is appreciated.

Thanks.

答:
It should look like this</p>

```<code>   void owed(int classchoice)
    {
      double cost;
      if (classchoice == 1)
        cost = 1750.00;
      else if  (classchoice == 2)
        cost = 1500.00;
      else if (classchoice == 3)
        cost = 1000.00;

      cout << "You owe about: " << cost << endl;
      cout << "Enjoy your flight!\n\n\n";
    }
</code>```

Title: If-Else Statement C++ Error

Body:
I am having an issue with this if else statement. This is part of an bigger c++ program, but there is something wrong.

void owed(int classchoice)
{
  double cost;
  if (classchoice == 1)
    cost = 1750.00;
  else if  (classchoice == 2)
    cost = 1500.00;
  else (classchoice == 3);
    cost = 1000.00:

  cout << "You owe about: " << cost << endl;
  cout << "Enjoy your flight!\n\n\n";
}

The output is ALWAYS 1000 dollars. I know for a fact that my input is correct, I have no idea what is wrong. Also I get an error at this point  "else (classchoice == 3);", it tells me to to put a semicolon after this statement, I do not know why. All the help is appreciated.

Thanks.

Body:
It should look like this

   void owed(int classchoice)
    {
      double cost;
      if (classchoice == 1)
        cost = 1750.00;
      else if  (classchoice == 2)
        cost = 1500.00;
      else if (classchoice == 3)
        cost = 1000.00;

      cout << "You owe about: " << cost << endl;
      cout << "Enjoy your flight!\n\n\n";
    }


问:
Where to mount Vuejs keeping HTML5 structure right?
From official Vuejs documentation, about mounting point:

The provided element merely serves as a mounting point. Unlike in Vue 1.x, the mounted element will be replaced with Vue-generated DOM in all cases. It is therefore not recommended to mount the root instance to html or body

What if I have page structured like this:
(I omitting HTML,HEAD tags here)

```<code><body>
  <!-- <div class="wrapper"> It just doesn't feel right -->
  <header>
     <!-- Header content, NAV, etc. -->
  </header>
  <div role="main">
    <!-- Page content -->
  </div>
  <footer>
    <!-- Footer content -->
  </footer>
  <!-- </div>-->
</body>
</code>```

I really don't want to add wrapper inside body because I'd like to have my HTML structured according recommendations. At the same time I'd like to use only one instance of Vue application.

What is the best technique in this case?

答:
You use to be able to add an id to the body tag and use that, but apparently that wasn't pure enough either. How you have it is how I do it and I believe it is the recommended way. See this and this. It is a fun exercise to strive for purity but in the wild it is hard to attain.</p>

```<code><body>
  <div class="wrapper" id="app">
  <header>
     <!-- Header content, NAV, etc. -->
  </header>
  <div role="main">
    <!-- Page content -->
  </div>
  <footer>
    <!-- Footer content -->
  </footer>
  </div>
</body>
</code>```

Body:
From official Vuejs documentation, about mounting point:

The provided element merely serves as a mounting point. Unlike in Vue 1.x, the mounted element will be replaced with Vue-generated DOM in all cases. It is therefore not recommended to mount the root instance to html or body

What if I have page structured like this:
(I omitting HTML,HEAD tags here)

I really don't want to add wrapper inside body because I'd like to have my HTML structured according recommendations. At the same time I'd like to use only one instance of Vue application.

What is the best technique in this case?

Body:
You use to be able to add an id to the body tag and use that, but apparently that wasn't pure enough either. How you have it is how I do it and I believe it is the recommended way. See this and this. It is a fun exercise to strive for purity but in the wild it is hard to attain.

<body>
  <div class="wrapper" id="app">
  <header>
     <!-- Header content, NAV, etc. -->
  </header>
  <div role="main">
    <!-- Page content -->
  </div>
  <footer>
    <!-- Footer content -->
  </footer>
  </div>
</body>


问:
jquery how to get data from API xml
I need to get data from an API which returns xml format. here's the api url: http://api.tubeupdates.com/?method=get.status&lines=all&format=xml

here's my jquery code:

```<code>$(document).ready(function(){
                $.get('http://api.tubeupdates.com/?method=get.status&lines=all&format=xml', function(d){

                    $(d).find('line').each(function(){
                        var $line = $(this).find('name').text()
                        var $mex = $(this).find('message').text()
                        $('#status').append($line+'<br>'+$mex+'<br><br>');
                    });
                });
            });
</code>```

The div #status returns empty. My jquery code seems fine because with a physical xml file it works. What am I doing wrong?

Thanks in advance,

Mauro

答:
Remove the $ from this variable line and add:

```<code>var line = $(this).find('name').text();
var mes  = $(this).find('message').text();
$('#status').append(line + '<br/>' + mes + <br/>);
</code>```

Title: jquery how to get data from API xml

Body:
I need to get data from an API which returns xml format. here's the api url: http://api.tubeupdates.com/?method=get.status&lines=all&format=xml

here's my jquery code:

$(document).ready(function(){
                $.get('http://api.tubeupdates.com/?method=get.status&lines=all&format=xml', function(d){

                    $(d).find('line').each(function(){
                        var $line = $(this).find('name').text()
                        var $mex = $(this).find('message').text()
                        $('#status').append($line+'
'+$mex+'

');
                    });
                });
            });

The div #status returns empty. My jquery code seems fine because with a physical xml file it works. What am I doing wrong?

Thanks in advance,

Mauro

Body:
Remove the $ from this variable line and add:

var line = $(this).find('name').text();
var mes  = $(this).find('message').text();
$('#status').append(line + '<br/>' + mes + <br/>);


问:
JavaScript By Reference Object
I have code which is similar to

emp1 = emp;

emp= emp2;

if objects are by reference then why emp1 is not equal to emp2?

why emp1 prints "shilpa" instead of "manish" .

var emp =
    {
      name : "manish",
      number :  10
    }

var emp1 = emp;

var emp2 =
    {
      name : "shilpa",
      number :  20
    }

emp = emp2;

console.log(emp);
console.log(emp1);
console.log(emp2);```

答:
ThiS is what happens.

You create a variable emp which points to a location in the memory where is stored the object value you defined.

Then you you create a variable emp1 which points to the same location in memory of the object value.

Then you define a new variable emp2 which points to a location in the memory where is stored your object value you define.

Then you set that emp points to the nrw location in memory of the emp2 object value.

But emp1 still points to the first location/object.

I think you are getting confused between variable declarations and passing parameters in methods/functions (by reference or by value)

Title: JavaScript By Reference Object


问:
`enum` type always getting `0` while passing it as parameter from one viewController to another
This is my enum :

```<code>typedef enum {
    ViewControllerNameSignUpViewController,
    ViewControllerNameForgotPasswordViewController,
    ViewControllerNameProfileViewController,
} ViewControllerName;
</code>```

I want to send ViewControllerName from my LeftMenuViewController to HomeViewController

Code of LeftMenuViewController :

```<code>HomeViewController *controller = [HomeViewController initViewControllerWithFurtherNavigationFor:ViewControllerNameProfileViewController];
UINavigationController *navController = (UINavigationController *)self.revealViewController.frontViewController;
[navController setViewControllers:@[controller] animated:NO];
[self.revealViewController setFrontViewPosition:FrontViewPositionLeft animated:YES];
</code>```

Code of HomeViewController :

```<code>@property (assign, nonatomic) ViewControllerName viewControllerName;
</code>```

.

```<code>+ (instancetype)initViewControllerWithFurtherNavigationFor:(ViewControllerName)viewControllerName
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    HomeViewController *controller = [storyboard instantiateViewControllerWithIdentifier:kHomeViewControllerID];

    if (controller) {
        controller.viewControllerName = viewControllerName;
    }

    return controller;
}
</code>```

Here controller.viewControllerName is getting the parameter perfectly, which is 2. But when I check it from viewDidLoad, it is always getting 0 :

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    [self leftMenuButtonInitialization];
    [self initialViewSetUp];
    [self furtherNavigation];
}
</code>```

.

```<code>- (void)furtherNavigation
{
    if (self.viewControllerName == ViewControllerNameProfileViewController) {
        ProfileViewController *controller = [ProfileViewController initViewController];
        [controller presentViewController:controller animated:YES completion:nil];
    }
}
</code>```

Here, self.viewControllerName always 0. When I set the value in my initViewController, Isn't it that I can access it as self.viewControllerName though out the class? Or I am missing something?

Thanks a lot in advance.

答:
After digging through 1 hour, I have found the alternative. The Problem may be relay on the calling method of initViewControllerWithFurtherNavigationFor.

I have called that method in - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender with ([[segue identifier] isEqualToString:@"goToProfileViewController"]) using segue. So I don't have to instantiateViewControllerWithIdentifier again. I can simply introduce it as destinationViewController. And then can pass any associated parameter with it. So instead of using this code :

```<code>- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"goToProfileViewController"]) {
    HomeViewController *controller = [HomeViewController initViewControllerWithFurtherNavigationFor:ViewControllerNameProfileViewController];
    UINavigationController *navController = (UINavigationController *)self.revealViewController.frontViewController;
    [navController setViewControllers:@[controller] animated:NO];
    [self.revealViewController setFrontViewPosition:FrontViewPositionLeft animated:YES];
    }
}
</code>```

Use this :

```<code>- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"goToProfileViewController"]) {
    HomeViewController *controller = [segue destinationViewController];
    controller.viewControllerName = ViewControllerNameProfileViewController;
    }
}
</code>```

Hope it will help for this kind of problem. :)

Body:
This is my enum :

typedef enum {
    ViewControllerNameSignUpViewController,
    ViewControllerNameForgotPasswordViewController,
    ViewControllerNameProfileViewController,
} ViewControllerName;

I want to send ViewControllerName from my LeftMenuViewController to HomeViewController

Code of LeftMenuViewController :

HomeViewController *controller = [HomeViewController initViewControllerWithFurtherNavigationFor:ViewControllerNameProfileViewController];
UINavigationController *navController = (UINavigationController *)self.revealViewController.frontViewController;
[navController setViewControllers:@[controller] animated:NO];
[self.revealViewController setFrontViewPosition:FrontViewPositionLeft animated:YES];

Code of HomeViewController :

@property (assign, nonatomic) ViewControllerName viewControllerName;

.

+ (instancetype)initViewControllerWithFurtherNavigationFor:(ViewControllerName)viewControllerName
{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    HomeViewController *controller = [storyboard instantiateViewControllerWithIdentifier:kHomeViewControllerID];

    if (controller) {
        controller.viewControllerName = viewControllerName;
    }

    return controller;
}

Here controller.viewControllerName is getting the parameter perfectly, which is 2. But when I check it from viewDidLoad, it is always getting 0 :

- (void)viewDidLoad {
    [super viewDidLoad];
    [self leftMenuButtonInitialization];
    [self initialViewSetUp];
    [self furtherNavigation];
}

.

- (void)furtherNavigation
{
    if (self.viewControllerName == ViewControllerNameProfileViewController) {
        ProfileViewController *controller = [ProfileViewController initViewController];
        [controller presentViewController:controller animated:YES completion:nil];
    }
}

Here, self.viewControllerName always 0. When I set the value in my initViewController, Isn't it that I can access it as self.viewControllerName though out the class? Or I am missing something?

Thanks a lot in advance.

Body:
After digging through 1 hour, I have found the alternative. The Problem may be relay on the calling method of initViewControllerWithFurtherNavigationFor.

I have called that method in - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender with ([[segue identifier] isEqualToString:@"goToProfileViewController"]) using segue. So I don't have to instantiateViewControllerWithIdentifier again. I can simply introduce it as destinationViewController. And then can pass any associated parameter with it. So instead of using this code :

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"goToProfileViewController"]) {
    HomeViewController *controller = [HomeViewController initViewControllerWithFurtherNavigationFor:ViewControllerNameProfileViewController];
    UINavigationController *navController = (UINavigationController *)self.revealViewController.frontViewController;
    [navController setViewControllers:@[controller] animated:NO];
    [self.revealViewController setFrontViewPosition:FrontViewPositionLeft animated:YES];
    }
}

Use this :

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"goToProfileViewController"]) {
    HomeViewController *controller = [segue destinationViewController];
    controller.viewControllerName = ViewControllerNameProfileViewController;
    }
}

Hope it will help for this kind of problem. :)


问:
Eloquent Eager Loading with $append Attribute
I'm kinda stuck with this here and don't know how to move forward with this one.

I have two Models: user and child and they are in a Relationship.

( Keep in mind that this only illustrate the problem )

```<code>class Child extends Model{

    protected $primaryKey = 'id_child';

    public $appends = ['is_alive'];

    public function user(){

        return $this->belongsTo('Models\User','id_user');

    }

    public function getIsAliveAttribute(){

        if (!is_null($this->lifetime_updated_at))
            return (Carbon::parse($this->lifetime_updated_at)->addMinute($this->lifetime) >= Carbon::now());
        else
            return false;
    }
}

class User extends Model{

    protected $primaryKey = 'id_user';

    public $appends = ['is_alive'];

    public function childs(){

        return $this->hasMany('Models\Child','id_user');
}

public function getIsAliveAttribute(){

    if (!is_null($this->lifetime_updated_at))
        return (Carbon::parse($this->lifetime_updated_at)->addMinute($this->lifetime) >= Carbon::now());
    else
        return false;
}
</code>```

}

Now I want to use Eager Loading in the Controller to retrieve my Childs data from User.

But my User Model Object comes from an MiddleWare in my Application. So I only have the User Model Object to use and I don't want to Query the User again using "with()".

```<code>$user = User::where('name','DoctorWho')->first();

return user->childs()->find(3);
</code>```

What this operation returns:

```<code>    {
        "id_child": 3,
        "name": "JayZ",
        "last_name": "Etc",
        "lifetime": 1,
        "lifetime_updated_at": null,
        "created_at": "2017-05-29 21:40:02",
        "updated_at": "2017-05-29 21:40:02",
        "active": 1
}
</code>```

What I needed ( With Attribute Appended)

```<code>{
    "id_child": 3,
    "name": "JayZ",
    "last_name": "Etc",
    "lifetime": 1,
    "lifetime_updated_at": null,
    "created_at": "2017-05-29 21:40:02",
    "updated_at": "2017-05-29 21:40:02",
    "active": 1,
    "is_alive": true
  }
</code>```

Is even possible to retrieve Child Data with Appended Attributes using Eager Loading ?

Notes: This user object come from an Middleware, I must use the User Model Object to get its child's with the appended attribute.

Thanks in Advance,
LosLobos

答: The thing is I was doing something wrong that is not related to Eloquent acessing the model like that does come with the appended attributes!</p>

Body:
I'm kinda stuck with this here and don't know how to move forward with this one.

I have two Models: user and child and they are in a Relationship.

( Keep in mind that this only illustrate the problem )

class Child extends Model{

    protected $primaryKey = 'id_child';

    public $appends = ['is_alive'];

    public function user(){

        return $this->belongsTo('Models\User','id_user');

    }

    public function getIsAliveAttribute(){

        if (!is_null($this->lifetime_updated_at))
            return (Carbon::parse($this->lifetime_updated_at)->addMinute($this->lifetime) >= Carbon::now());
        else
            return false;
    }
}

class User extends Model{

    protected $primaryKey = 'id_user';

    public $appends = ['is_alive'];

    public function childs(){

        return $this->hasMany('Models\Child','id_user');
}

public function getIsAliveAttribute(){

    if (!is_null($this->lifetime_updated_at))
        return (Carbon::parse($this->lifetime_updated_at)->addMinute($this->lifetime) >= Carbon::now());
    else
        return false;
}

}

Now I want to use Eager Loading in the Controller to retrieve my Childs data from User.

But my User Model Object comes from an MiddleWare in my Application. So I only have the User Model Object to use and I don't want to Query the User again using "with()".

$user = User::where('name','DoctorWho')->first();

return user->childs()->find(3);

What this operation returns:

    {
        "id_child": 3,
        "name": "JayZ",
        "last_name": "Etc",
        "lifetime": 1,
        "lifetime_updated_at": null,
        "created_at": "2017-05-29 21:40:02",
        "updated_at": "2017-05-29 21:40:02",
        "active": 1
}

What I needed ( With Attribute Appended)

{
    "id_child": 3,
    "name": "JayZ",
    "last_name": "Etc",
    "lifetime": 1,
    "lifetime_updated_at": null,
    "created_at": "2017-05-29 21:40:02",
    "updated_at": "2017-05-29 21:40:02",
    "active": 1,
    "is_alive": true
  }

Is even possible to retrieve Child Data with Appended Attributes using Eager Loading ?

Notes: This user object come from an Middleware, I must use the User Model Object to get its child's with the appended attribute.

Thanks in Advance,
LosLobos


问:
VBA save value from cell before it changes
I have a spreadsheet where i implement a score board.
The behavior i need is when the cell that has the score value rises the cell near it, on column b, changes it's color to green, when the the cell score value goes down the cell near it changes it's color to red.

The cell range where the score is changing is e5:e67

In short:
When the user inputs a number in column f, the score raises in column e, and in column b (on same row) the color must change to green or red

I made this VBA code, but without luck.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
 If Not Intersect(Target, Range("e5:e67")) Is Nothing Then
 If Target.Column = 5 Then
  thisRow = Target.Row
  Dim OldValue As Variant
  Application.EnableEvents = False
  Application.Undo
  OldValue = Target.Value
  Application.Undo
  Application.EnableEvents = True
 If OldValue < Target.Value Then
  Range("b" & thisRow).Interior.ColorIndex = 4
 ElseIf OldValue > Target.Value Then
  Range("b" & thisRow).Interior.ColorIndex = 3
 End If
 End If
End If
End Sub
</code>```

Here is a screen capture of my ranking sheet:

答:
```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    Dim i As Integer
 If Not Intersect(Target, Range("e6:e67")) Is Nothing Then
    If Target.Offset(-1) < Target Then
        i = 4
    Else
        i = 3
    End If
    Range("b" & Target.Row).Interior.ColorIndex = i
End If
End Sub
</code>```

Body:
I have a spreadsheet where i implement a score board.
The behavior i need is when the cell that has the score value rises the cell near it, on column b, changes it's color to green, when the the cell score value goes down the cell near it changes it's color to red.

The cell range where the score is changing is e5:e67

In short:
When the user inputs a number in column f, the score raises in column e, and in column b (on same row) the color must change to green or red

I made this VBA code, but without luck.

Private Sub Worksheet_Change(ByVal Target As Range)
 If Not Intersect(Target, Range("e5:e67")) Is Nothing Then
 If Target.Column = 5 Then
  thisRow = Target.Row
  Dim OldValue As Variant
  Application.EnableEvents = False
  Application.Undo
  OldValue = Target.Value
  Application.Undo
  Application.EnableEvents = True
 If OldValue < Target.Value Then
  Range("b" & thisRow).Interior.ColorIndex = 4
 ElseIf OldValue > Target.Value Then
  Range("b" & thisRow).Interior.ColorIndex = 3
 End If
 End If
End If
End Sub

Here is a screen capture of my ranking sheet:


问:
Allowing user to reset a list... but also allowing them to restore the deleted list?
I am currently working on a Todo list for practice and was wondering if there was a way to restore a list. I was thinking of creating a copy of the list and then re-adding the contents to the DOM once the user hits a restore 'Restore List' button but I just can't figure it out!

Here is my current code, the button appears when I hit 'Reset List' button but it is not functional yet.

```<code>document.addEventListener('DOMContentLoaded', () => {

  //Targets the unordered list element
  const list = document.getElementById("myUL");
  //Targets the children of the unordered list
  const li = list.children;

  const resetDiv = document.getElementById('resetPanel');
  const resetButton = document.createElement('button');
  const restoreButton = document.createElement('button');
  restoreButton.textContent = 'Restore Items';
  resetButton.textContent = 'Reset List';
  resetDiv.appendChild(resetButton);

  //Targets the form element.
  const form = document.getElementById("registrar");

  //Function declaration (Begins process of creating list item)
  function createListItem(text){
    //Creates the list item
    const li = document.createElement('li');
    //Function delcaration (creates an element and returns element)
    function createElement(elementName, property, value) {
      const element = document.createElement(elementName);
      element[property] = value;
      return element;
    }

    //Function declaration (Adds the created element to the list)
    function appendToLi(elementName, property, value){
      const element = createElement(elementName, property, value);
      li.appendChild(element);
      return element;
    }

      //Appends all children to the list item.
      appendToLi('span', 'textContent', text);
      appendToLi('label', 'textContent', 'Completed')
        .appendChild(createElement('input', 'type', 'checkbox'));
      appendToLi('button', 'textContent', 'remove');
      appendToLi('button', 'textContent', 'edit');

      /*Returns the list item and it's children to what has called the
      createListItem function*/
      return li;
  }

  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");
      const listCopy = document.getElementById("myUL");

      //Moves through the unordered list and removes each list item.
      while (ul.firstChild) {
        ul.removeChild(ul.firstChild);
      }
    resetDiv.appendChild(restoreButton);
  });

  //This button should restore the removed list items. ***********************
  restoreButton.addEventListener('click', (e) => {
    resetDiv.removeChild(restoreButton);
  });

    //Event listener (listens for click on submit button/enter press)
    form.addEventListener('submit', (e) => {
      e.preventDefault();

      //Targets the input element.
      const input = document.querySelector('input');

      //If the user has not entered any text in the  input field, alerts.
      if(input.value === '') {
        alert('Please enter an item!');

      //Otherise begins the process of creating the list item.
      } else {

        //Holds the user text input.
        const text = input.value;

        /*Calls the createListItem function which will begin the process
          through various other functions.*/
        const listItem = createListItem(text);
        list.appendChild(listItem);
        input.value = '';
      }

  });

  //Listens for clicks on the list item's children buttons.
  list.addEventListener('click', (e) => {
    const button = e.target;
    const li = e.target.parentNode;
    const ul = li.parentNode;

    //Click on remove button
    if(button.textContent === 'remove'){
      ul.removeChild(li);

    //Click on edit button
    } else if (button.textContent === 'edit'){
      const span = li.firstElementChild;
      const input = document.createElement('input');
      input.type = 'text';
      input.value = span.textContent;

      //Inserts a text field in place of the previous span item (User's input)
      li.insertBefore(input, span);
      li.removeChild(span);
      button.textContent = 'save';

    //Click on save button
    } else if (button.textContent === 'save'){
      const span = document.createElement('span');
      const input = li.firstElementChild;
      span.textContent = input.value;

      //Inserts the new text over the input field.
      li.insertBefore(span, input);
      li.removeChild(input);
      button.textContent = 'edit';
    }

  });

});
</code>```

答: Looking at what you wanna do u obviously have to save deleted items into a cache but copying d whole thing wont be efficient (it would work maybe with a bit more code) try placing d deleted item into an array list with d position iD on d initial list and putting d item back u could just put it back at the initial position and if d id is a numbering system that helps with position you could just add 1 to all d items after d previously deleted item</p>

Body:
I am currently working on a Todo list for practice and was wondering if there was a way to restore a list. I was thinking of creating a copy of the list and then re-adding the contents to the DOM once the user hits a restore 'Restore List' button but I just can't figure it out!

Here is my current code, the button appears when I hit 'Reset List' button but it is not functional yet.

document.addEventListener('DOMContentLoaded', () => {

  //Targets the unordered list element
  const list = document.getElementById("myUL");
  //Targets the children of the unordered list
  const li = list.children;

  const resetDiv = document.getElementById('resetPanel');
  const resetButton = document.createElement('button');
  const restoreButton = document.createElement('button');
  restoreButton.textContent = 'Restore Items';
  resetButton.textContent = 'Reset List';
  resetDiv.appendChild(resetButton);

  //Targets the form element.
  const form = document.getElementById("registrar");

  //Function declaration (Begins process of creating list item)
  function createListItem(text){
    //Creates the list item
    const li = document.createElement('li');
    //Function delcaration (creates an element and returns element)
    function createElement(elementName, property, value) {
      const element = document.createElement(elementName);
      element[property] = value;
      return element;
    }

    //Function declaration (Adds the created element to the list)
    function appendToLi(elementName, property, value){
      const element = createElement(elementName, property, value);
      li.appendChild(element);
      return element;
    }

      //Appends all children to the list item.
      appendToLi('span', 'textContent', text);
      appendToLi('label', 'textContent', 'Completed')
        .appendChild(createElement('input', 'type', 'checkbox'));
      appendToLi('button', 'textContent', 'remove');
      appendToLi('button', 'textContent', 'edit');

      /*Returns the list item and it's children to what has called the
      createListItem function*/
      return li;
  }

  //Sets an event listener to the reset button.
  resetButton.addEventListener('click', (e) => {
      const ul = document.getElementById("myUL");
      const listCopy = document.getElementById("myUL");

      //Moves through the unordered list and removes each list item.
      while (ul.firstChild) {
        ul.removeChild(ul.firstChild);
      }
    resetDiv.appendChild(restoreButton);
  });

  //This button should restore the removed list items. ***********************
  restoreButton.addEventListener('click', (e) => {
    resetDiv.removeChild(restoreButton);
  });

    //Event listener (listens for click on submit button/enter press)
    form.addEventListener('submit', (e) => {
      e.preventDefault();

      //Targets the input element.
      const input = document.querySelector('input');

      //If the user has not entered any text in the  input field, alerts.
      if(input.value === '') {
        alert('Please enter an item!');

      //Otherise begins the process of creating the list item.
      } else {

        //Holds the user text input.
        const text = input.value;

        /*Calls the createListItem function which will begin the process
          through various other functions.*/
        const listItem = createListItem(text);
        list.appendChild(listItem);
        input.value = '';
      }

  });

  //Listens for clicks on the list item's children buttons.
  list.addEventListener('click', (e) => {
    const button = e.target;
    const li = e.target.parentNode;
    const ul = li.parentNode;

    //Click on remove button
    if(button.textContent === 'remove'){
      ul.removeChild(li);

    //Click on edit button
    } else if (button.textContent === 'edit'){
      const span = li.firstElementChild;
      const input = document.createElement('input');
      input.type = 'text';
      input.value = span.textContent;

      //Inserts a text field in place of the previous span item (User's input)
      li.insertBefore(input, span);
      li.removeChild(span);
      button.textContent = 'save';

    //Click on save button
    } else if (button.textContent === 'save'){
      const span = document.createElement('span');
      const input = li.firstElementChild;
      span.textContent = input.value;

      //Inserts the new text over the input field.
      li.insertBefore(span, input);
      li.removeChild(input);
      button.textContent = 'edit';
    }

  });

});


问:
What are the security concerns that I need to look out for with Java Persistence API (JPA)
I'm starting to learn JPA, and I have a considerable amount of legacy EJB2.0 code that will need to be refactored to use the new features, as well as any new functionality that I will add to the code base. Are there new attack vectors that I will need to account for in my code, or will defensive programming cover me?</p>

答:
If you are deserializing an object from bytes that you received from an untrusted source, then it can cause any class on the boot classpath to load, whether public or not, and cause that classes initialization to run.  It can also gain authority via constructors with side-effects and via custom deserialization methods.

If your classpath includes well known public classes with unbounded authority, like the Rhino interpreter shipped with most recent JVMs, or the javax.tools interface to javac, AND that authority is reachable via the constructor of a serializable class, then an attacker could use that to execute arbitrary java code.  In practice, this means arbitrary user-ring code with the privileges of the current user via java.lang.Runtime.

The first criterion is easily met.  The second one is probably much less easily met.


问:
C++ Declare array of unspecified length with string elements
What I'm trying to do here is quite simple. But some way, some how I'm missing something. I'm trying to "pre-declare" an array with strictly string elements in such a way that I can update the array contents during a specific period (periodically). So here are the snippets:

```<code>string ShotBox[] = {}; //"Pre-Declare" array that could contain as many elements here
</code>```

Then I have a loop within my Update container. Snippet's:

```<code>for (int i = 0; i < sizeof(ShotBox) - 1; i++){
            std::string soa = sPath;
            std::string so = soa + ShotBox[i];
            char *cstr = new char[so.length() + 1];
            strcpy(cstr, so.c_str());
            scPath = cstr;
}
</code>```

All is fine with everything except the fact that whichever way I try to "pre-declare", I get a memory access violation. In this very exact snippets, the exact error is: an empty array is invalid for an array with unspecified bound.

I tried using "vector" but can't seem to work around it. What's the way to solve this? Please I don't want libraries. I need direct short methods or something of such.

答:
Galik's answer suggesting std::vector is the Modern C++ way to do what you want to do.

The reason your code doesn't work is that the following line of code doesn't do what you think it does

string ShotBox[] = {}; //"Pre-Declare" array that could contain as many elements here

Try adding the following to your program ...

std::cout << sizeof(ShotBox) << std::endl;

... and you should find that you've declared an array that is zero bytes long.  Indeed some compilers will treat an empty initializer as an error if the array bounds are not specified.

In the C++ language arrays are fixed length entities.  One way to approximate a dynamic array is to use a pointer and to use memory management functions to allocate a larger array and then copy the old array contents into the new larger array.

But that is a really bad idea.

Doing it correctly with exception safety and efficiency is hard to do and if you do manage it, you'll have re-implemented std::vector which seems like wasted effort!

Body:
What I'm trying to do here is quite simple. But some way, some how I'm missing something. I'm trying to "pre-declare" an array with strictly string elements in such a way that I can update the array contents during a specific period (periodically). So here are the snippets:

string ShotBox[] = {}; //"Pre-Declare" array that could contain as many elements here

Then I have a loop within my Update container. Snippet's:

for (int i = 0; i < sizeof(ShotBox) - 1; i++){
            std::string soa = sPath;
            std::string so = soa + ShotBox[i];
            char *cstr = new char[so.length() + 1];
            strcpy(cstr, so.c_str());
            scPath = cstr;
}

All is fine with everything except the fact that whichever way I try to "pre-declare", I get a memory access violation. In this very exact snippets, the exact error is: an empty array is invalid for an array with unspecified bound.

I tried using "vector" but can't seem to work around it. What's the way to solve this? Please I don't want libraries. I need direct short methods or something of such.


问:
Extracting 3D netcdf variable from lists within nested loop in R
Say I have 10 model configurations of n timesteps for 3 different sites, producing a total 30 netcdf files I want to open and manipulate. I can open the 30 files such as

```<code>require(ncdf4)

allfiles= list()
nmod=10
nsites=3

for (i in 1:nmod) {
allfiles[[i]] = list(nc_open(paste0('Model',i,'siteA.nc')),
                     nc_open(paste0('Model',i,'siteB.nc')),
                     nc_open(paste0('Model',i,'siteC.nc')))
}
</code>```

When querying the class of what was opened, I have

class(allfiles)

[1] "list"

class(allfiles[[1]][[1]])

[1] "ncdf4"

as expected.
Now what I would like to do is extract the values from a variable in the files such that

```<code>var=list()
for (i in 1:nmod) {
  for (j in 1:nsites) {
    var[[i]][[j]] <- ncvar_get(allfiles[[i]][[j]],"var1")
    nc_close(allfiles[[i]][[j]])
   }}
</code>```

but I get this error message:

```<code> `Error in *tmp*[[i]] : subscript out of bounds`
</code>```

If I try

```<code> var[[i]] <- ncvar_get(allfiles[[i]][[j]],"var1")
</code>```

it (understandbly) only produces a list of 10 model configurations at one site, i.e. var[[1]][[1]][1] prints out the value of the variable at model configuration 1, site A, timestep 1 but var[[1]][[2]] doesn't exist.
How can I declare var in the above loop so that it contains all the values for all models, all sites and all timesteps (e.g. for var[[1]][[2]][1] to exist)?

答:
In your original version where the error occurs, in the first inner loop, you try to do something: var[[1]][[1]] <- something, but var[[1]] doesn't exist, and R doesn't know what to do, so I guess the following thing should work, you set var[i] <- list() before you do var[[i]][[j]] <- something:

```<code>var=list()
for (i in 1:nmod) {
var[i] <- list()
  for (j in 1:nsites) {
    var[[i]][[j]] <- ncvar_get(allfiles[[i]][[j]],"var1")
    nc_close(allfiles[[i]][[j]])
  }
}
</code>```

For example, if you do:

```<code>var <- list()
for (i in 1:10) {
    for (j in 1:10) {
        var[[i]][[j]] <- 1
    }
}
</code>```

Then the same error happens. But if you set var[[i]] <- list() before carrying out the inner loop like this:

```<code>var <- list()
for (i in 1:10) {
    var[[i]] <- list()
    for (j in 1:10) {
        var[[i]][[j]] <- 1
    }
}
</code>```

Then the problem will be solved.

Body:
Say I have 10 model configurations of n timesteps for 3 different sites, producing a total 30 netcdf files I want to open and manipulate. I can open the 30 files such as

require(ncdf4)

allfiles= list()
nmod=10
nsites=3

for (i in 1:nmod) {
allfiles[[i]] = list(nc_open(paste0('Model',i,'siteA.nc')),
                     nc_open(paste0('Model',i,'siteB.nc')),
                     nc_open(paste0('Model',i,'siteC.nc')))
}

When querying the class of what was opened, I have

class(allfiles)

[1] "list"

class(allfiles[[1]][[1]])

[1] "ncdf4"

as expected.
Now what I would like to do is extract the values from a variable in the files such that

var=list()
for (i in 1:nmod) {
  for (j in 1:nsites) {
    var[[i]][[j]] <- ncvar_get(allfiles[[i]][[j]],"var1")
    nc_close(allfiles[[i]][[j]])
   }}

but I get this error message:

 `Error in *tmp*[[i]] : subscript out of bounds`

If I try

 var[[i]] <- ncvar_get(allfiles[[i]][[j]],"var1")

it (understandbly) only produces a list of 10 model configurations at one site, i.e. var[[1]][[1]][1] prints out the value of the variable at model configuration 1, site A, timestep 1 but var[[1]][[2]] doesn't exist.
How can I declare var in the above loop so that it contains all the values for all models, all sites and all timesteps (e.g. for var[[1]][[2]][1] to exist)?

Body:
In your original version where the error occurs, in the first inner loop, you try to do something: var[[1]][[1]] <- something, but var[[1]] doesn't exist, and R doesn't know what to do, so I guess the following thing should work, you set var[i] <- list() before you do var[[i]][[j]] <- something:

var=list()
for (i in 1:nmod) {
var[i] <- list()
  for (j in 1:nsites) {
    var[[i]][[j]] <- ncvar_get(allfiles[[i]][[j]],"var1")
    nc_close(allfiles[[i]][[j]])
  }
}

For example, if you do:

var <- list()
for (i in 1:10) {
    for (j in 1:10) {
        var[[i]][[j]] <- 1
    }
}

Then the same error happens. But if you set var[[i]] <- list() before carrying out the inner loop like this:

var <- list()
for (i in 1:10) {
    var[[i]] <- list()
    for (j in 1:10) {
        var[[i]][[j]] <- 1
    }
}

Then the problem will be solved.


问:
Matlab. Place legend outside the plot
I have the following code

```<code>T = [0:1:30]
a = [5:1:35]; a2 = [0:1:30];
b = [-4:1:26]; b2 = [12:1:42];
c = [16:1:46]; c2 = [15:1:45];
d = [2:1:32]; d2 = [-5:1:25];
figure(1)
title('Time histories of output variables (measured vs estimated)')
subplot(411),plot(T,a, T,a2,'r'); grid; ylabel('p (°/s)');
subplot(412),plot(T,b, T,b2,'r'); grid; ylabel('r (°/s)');
subplot(413),plot(T,c, T,c2,'r'); grid; ylabel('phi (º)');
subplot(414),plot(T,d, T,d2,'r'); grid; ylabel('ay (m/s2)');
legend('measured','estimated','Location','bestoutside')
xlabel('Time [s]');
</code>```

Which generates the following plot

I would like to have the legend outside the plot and that all of them remains with the normal size. (So the legend should be in one of those red circles. Any solutions?

答:
Try getting handle positions using get method and manually change positions by doing some arithmetic. For example,

```<code>T = [0:1:30];
a = [5:1:35]; a2 = [0:1:30];
b = [-4:1:26]; b2 = [12:1:42];
c = [16:1:46]; c2 = [15:1:45];
d = [2:1:32]; d2 = [-5:1:25];
figure(1)

title('Time histories of output variables (measured vs estimated)')

f1 = subplot(411);plot(T,a, T,a2,'r'); grid; ylabel('p (°/s)');
pos_f1 = get(f1,'Position');
hl = legend('measured','estimated','Location','bestoutside');
pos_hl = get(hl, 'Position');

subplot(412),plot(T,b, T,b2,'r'); grid; ylabel('r (°/s)');
subplot(413),plot(T,c, T,c2,'r'); grid; ylabel('phi (º)');
subplot(414),plot(T,d, T,d2,'r'); grid; ylabel('ay (m/s2)');

set(hl,'Position',[pos_f1(1)+pos_f1(3)-pos_hl(3)...
pos_hl(2)+pos_hl(4)+0.015...
pos_hl(3)...
0.5*pos_hl(4)]);
</code>```

This should give you:

You may need to play around with the parameters in last line, but you get the idea.

Title: Matlab. Place legend outside the plot

Body:
I have the following code

T = [0:1:30]
a = [5:1:35]; a2 = [0:1:30];
b = [-4:1:26]; b2 = [12:1:42];
c = [16:1:46]; c2 = [15:1:45];
d = [2:1:32]; d2 = [-5:1:25];
figure(1)
title('Time histories of output variables (measured vs estimated)')
subplot(411),plot(T,a, T,a2,'r'); grid; ylabel('p (°/s)');
subplot(412),plot(T,b, T,b2,'r'); grid; ylabel('r (°/s)');
subplot(413),plot(T,c, T,c2,'r'); grid; ylabel('phi (º)');
subplot(414),plot(T,d, T,d2,'r'); grid; ylabel('ay (m/s2)');
legend('measured','estimated','Location','bestoutside')
xlabel('Time [s]');

Which generates the following plot

I would like to have the legend outside the plot and that all of them remains with the normal size. (So the legend should be in one of those red circles. Any solutions?

Body:
Try getting handle positions using get method and manually change positions by doing some arithmetic. For example,

T = [0:1:30];
a = [5:1:35]; a2 = [0:1:30];
b = [-4:1:26]; b2 = [12:1:42];
c = [16:1:46]; c2 = [15:1:45];
d = [2:1:32]; d2 = [-5:1:25];
figure(1)

title('Time histories of output variables (measured vs estimated)')

f1 = subplot(411);plot(T,a, T,a2,'r'); grid; ylabel('p (°/s)');
pos_f1 = get(f1,'Position');
hl = legend('measured','estimated','Location','bestoutside');
pos_hl = get(hl, 'Position');

subplot(412),plot(T,b, T,b2,'r'); grid; ylabel('r (°/s)');
subplot(413),plot(T,c, T,c2,'r'); grid; ylabel('phi (º)');
subplot(414),plot(T,d, T,d2,'r'); grid; ylabel('ay (m/s2)');

set(hl,'Position',[pos_f1(1)+pos_f1(3)-pos_hl(3)...
pos_hl(2)+pos_hl(4)+0.015...
pos_hl(3)...
0.5*pos_hl(4)]);

This should give you:

You may need to play around with the parameters in last line, but you get the idea.


问:
Why does this code return None when I don't put the else statement, but it doesn't return None when I put the else statement?
Why does this return the country codes?

```<code>from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
    """Return the Pygal 2-digit country code for the given country."""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
    return None

print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates')
</code>```

Why doesn't this return the country codes?

```<code>from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
    """Return the Pygal 2-digit country code for the given country."""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
        return None

print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates')
</code>```

The main difference is how I indented the 'return None.' Even if I put the else statement it doesn't return the codes. Can someone please explain this to me? I'm new in programming.

答:
The indentation is the difference -- check your indentation closely. in the second example, the return none is INSIDE the for code loop.  So it returns None as soon as `if name == country_name' fails once.

Python indentation acts like braces in C-based languages or Begin-End in BASIC dialects.  It's the main idiosyncrasy of Python.

Body:
Why does this return the country codes?

from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
    """Return the Pygal 2-digit country code for the given country."""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
    return None

print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates')

Why doesn't this return the country codes?

from pygal.maps.world import COUNTRIES

def get_country_code(country_name):
    """Return the Pygal 2-digit country code for the given country."""
    for code, name in COUNTRIES.items():
        if name == country_name:
            return code
        return None

print(get_country_code('Andorra'))
print(get_country_code('United Arab Emirates')

The main difference is how I indented the 'return None.' Even if I put the else statement it doesn't return the codes. Can someone please explain this to me? I'm new in programming.