问:
Android observeable in viewmodel only works once
I am using android architecture components and following a tutorial from here. This tutorial uses single source of truth strategy with local cashing using room and retrofit. I have implemented this part in my app and it works well. But in one Fragment I am facing the problem. The problem is that i have 4 buttons on activity and by clicking any button the data is filtered based on category say Category A category b etc. When I first load the fragment the data is displayed as expected but when I click on 2nd button to get data for category B the old data is showed and new data is never refreshed.
Here is my code.
In fragment inside oncreateview i have this observer

```<code> private fun getCategory() {
        viewModel.categorys.observe(viewLifecycleOwner, Observer { result ->
            when (result.status) {
                Result.Status.SUCCESS -> {
                    progressDialogue.hideDialog()

                    Log.d("category", "On success")
                    val item = result.data
                    setAdapter(item)
                }
                Result.Status.LOADING -> {
                    progressDialogue.showDialog()
                    Log.d("category", "On loading")
                }
                Result.Status.ERROR -> {
                    Log.d("category", "On Error")
                    progressDialogue.hideDialog()
                    Snackbar.make(binding.root, result.message!!, Snackbar.LENGTH_LONG).show()
                }
            }
        })
    }
</code>```

this is my view model

```<code>class CategoryViewModel @Inject constructor(repository: CateRepository) : ViewModel() {
         var categorys = repository.mCate// ***this value not changes after 1st run***
   }
</code>```

this is my repository

```<code>class CateRepository @Inject
constructor(
    private val daoCat: DaoCat,
    private val remoteDataSource: RemoteDataSource,
     private val request: String
) {
    val mCate= resultLiveData(
        databaseQuery = {
            daoBundles.getAllCategories(BaseClass.Category)
        },
        networkCall = { remoteDataSource.getBundles(request) },
        saveCallResult = {
            daoCat.deleteAndInsert()
        })
</code>```

My question is how can i refresh this value on button click
             var categorys = repository.mCate//
Update 1

This is my click listener

```<code>binding.btnGroup.setOnCheckedChangeListener { _, checkedId ->
            val dao = AppDatabase.getInstance(BaseClass.appContext).bundlesDao()
            when (checkedId) {
                R.id.btnHybrid -> {
                    BundleParams.setBundleType(BundleTypes.Hybrid.type)
                    getSelectedBundles(BundleTypes.Hybrid.type)
                }
                R.id.btnVoice -> {
                    BundleParams.setBundleType(BundleTypes.Voice.type)
                    getSelectedBundles(BundleTypes.Voice.type)
                }
                R.id.btnSMS -> {
                    BundleParams.setBundleType(BundleTypes.SMS.type)
                    getSelectedBundles(BundleTypes.SMS.type)
                }
                R.id.btnData -> {
                    BundleParams.setBundleType(BundleTypes.Data.type)
                    getSelectedBundles(BundleTypes.Data.type)
                }
                R.id.btnFavourites -> {
                    BundleParams.setBundleType(BundleTypes.Favorites.type)
                    getSelectedBundles(BundleTypes.Favorites.type)
                }
            }
        }

private fun getSelectedBundles(mType: String) {
        viewModel.updateCategory()
    }
</code>```

答:
I my case I try to implement a SwipeRefreshLayout to refresh data.

On the SwiperefreshListener =>

Removed the observer

Then add Observer again

call action to refresh data.

I followed this same tutorial and i had the same issue.

```<code>override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.swipeRefresh.setOnRefreshListener {
        vm.links.removeObservers(viewLifecycleOwner)
        vm.links.observe(viewLifecycleOwner, Observer { it?.let { observeLinks(it) } })
        vm.refresh()
    }
}

private fun observeLinks(result: Result<MutableList<Link>>) {
    when (result.status) {
        SUCCESS -> {
            binding.recyclerView.visibility = VISIBLE
            binding.progressBar.visibility = GONE
            binding.swipeRefresh.isRefreshing = false
            knowMoreAdapter.clearItems()
            knowMoreAdapter.updateItems(result.data!!)
        }
        ERROR -> {
            Snackbar.make(
                binding.root,
                mContext.getString(R.string.error_loading_data),
                Snackbar.LENGTH_LONG
            ).show()
            binding.progressBar.visibility = GONE
            binding.swipeRefresh.isRefreshing = false
        }
        LOADING -> {
            binding.progressBar.visibility = VISIBLE
            binding.swipeRefresh.isRefreshing = false
        }
    }
}
</code>```

Then on View model class  I call the method refresh()

```<code>class KnowMoreVM @Inject constructor(private val repository: KnowMoreRepository) : ViewModel() {

var links = repository.observeSingleSource()

fun refresh() {
    links = repository.observeSingleSource()
}
</code>```

}

Body:
I am using android architecture components and following a tutorial from here. This tutorial uses single source of truth strategy with local cashing using room and retrofit. I have implemented this part in my app and it works well. But in one Fragment I am facing the problem. The problem is that i have 4 buttons on activity and by clicking any button the data is filtered based on category say Category A category b etc. When I first load the fragment the data is displayed as expected but when I click on 2nd button to get data for category B the old data is showed and new data is never refreshed.
Here is my code.
In fragment inside oncreateview i have this observer

 private fun getCategory() {
        viewModel.categorys.observe(viewLifecycleOwner, Observer { result ->
            when (result.status) {
                Result.Status.SUCCESS -> {
                    progressDialogue.hideDialog()

                    Log.d("category", "On success")
                    val item = result.data
                    setAdapter(item)
                }
                Result.Status.LOADING -> {
                    progressDialogue.showDialog()
                    Log.d("category", "On loading")
                }
                Result.Status.ERROR -> {
                    Log.d("category", "On Error")
                    progressDialogue.hideDialog()
                    Snackbar.make(binding.root, result.message!!, Snackbar.LENGTH_LONG).show()
                }
            }
        })
    }

this is my view model

class CategoryViewModel @Inject constructor(repository: CateRepository) : ViewModel() {
         var categorys = repository.mCate// ***this value not changes after 1st run***
   }

this is my repository

class CateRepository @Inject
constructor(
    private val daoCat: DaoCat,
    private val remoteDataSource: RemoteDataSource,
     private val request: String
) {
    val mCate= resultLiveData(
        databaseQuery = {
            daoBundles.getAllCategories(BaseClass.Category)
        },
        networkCall = { remoteDataSource.getBundles(request) },
        saveCallResult = {
            daoCat.deleteAndInsert()
        })

My question is how can i refresh this value on button click
             var categorys = repository.mCate//
Update 1

This is my click listener

binding.btnGroup.setOnCheckedChangeListener { _, checkedId ->
            val dao = AppDatabase.getInstance(BaseClass.appContext).bundlesDao()
            when (checkedId) {
                R.id.btnHybrid -> {
                    BundleParams.setBundleType(BundleTypes.Hybrid.type)
                    getSelectedBundles(BundleTypes.Hybrid.type)
                }
                R.id.btnVoice -> {
                    BundleParams.setBundleType(BundleTypes.Voice.type)
                    getSelectedBundles(BundleTypes.Voice.type)
                }
                R.id.btnSMS -> {
                    BundleParams.setBundleType(BundleTypes.SMS.type)
                    getSelectedBundles(BundleTypes.SMS.type)
                }
                R.id.btnData -> {
                    BundleParams.setBundleType(BundleTypes.Data.type)
                    getSelectedBundles(BundleTypes.Data.type)
                }
                R.id.btnFavourites -> {
                    BundleParams.setBundleType(BundleTypes.Favorites.type)
                    getSelectedBundles(BundleTypes.Favorites.type)
                }
            }
        }

private fun getSelectedBundles(mType: String) {
        viewModel.updateCategory()
    }

Body:
I my case I try to implement a SwipeRefreshLayout to refresh data.

On the SwiperefreshListener =>

Removed the observer

Then add Observer again

call action to refresh data.

I followed this same tutorial and i had the same issue.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    binding.swipeRefresh.setOnRefreshListener {
        vm.links.removeObservers(viewLifecycleOwner)
        vm.links.observe(viewLifecycleOwner, Observer { it?.let { observeLinks(it) } })
        vm.refresh()
    }
}

private fun observeLinks(result: Result<MutableList<Link>>) {
    when (result.status) {
        SUCCESS -> {
            binding.recyclerView.visibility = VISIBLE
            binding.progressBar.visibility = GONE
            binding.swipeRefresh.isRefreshing = false
            knowMoreAdapter.clearItems()
            knowMoreAdapter.updateItems(result.data!!)
        }
        ERROR -> {
            Snackbar.make(
                binding.root,
                mContext.getString(R.string.error_loading_data),
                Snackbar.LENGTH_LONG
            ).show()
            binding.progressBar.visibility = GONE
            binding.swipeRefresh.isRefreshing = false
        }
        LOADING -> {
            binding.progressBar.visibility = VISIBLE
            binding.swipeRefresh.isRefreshing = false
        }
    }
}

Then on View model class  I call the method refresh()

class KnowMoreVM @Inject constructor(private val repository: KnowMoreRepository) : ViewModel() {

var links = repository.observeSingleSource()

fun refresh() {
    links = repository.observeSingleSource()
}

}


来源: stackexchange

问:
Can't install numpy - MS Visual C++ 14.1 is required. But it is installed
I am on Windows 10 using pypy3.6-v7.3.0. I am trying to install numpy with pip install numpy, but I keep getting the error: error: Microsoft Visual C++ 14.1 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/.

However I already have Visual Studio Community 2019 installed, and my C++ build tools are fully up to date.

Edit:

Here is the new error I am getting after installing build tools manually:

```<code>Collecting numpy
  Using cached https://files.pythonhosted.org/packages/2d/f3/795e50e3ea2dc7bc9d1a2eeea9997d5dce63b801e08dfc37c2efce341977/numpy-1.18.4.zip
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    Complete output from command C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\pypy3.exe C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\site-packages\pip-19.0.3-py3.6.egg\pip\_vendor\pep517\_in_process.py prepare_metadata_for_build_wheel C:\Users\Chris\AppData\Local\Temp\tmpjxmz4c4z:
    Processing numpy/random\_bounded_integers.pxd.in
    Processing numpy/random\mtrand.pyx
    Processing numpy/random\_bit_generator.pyx
    Processing numpy/random\_bounded_integers.pyx.in
    Processing numpy/random\_common.pyx
    Processing numpy/random\_generator.pyx
    Processing numpy/random\_mt19937.pyx
    Processing numpy/random\_pcg64.pyx
    Processing numpy/random\_philox.pyx
    Processing numpy/random\_sfc64.pyx
    Cythonizing sources
    blas_opt_info:
    blas_mkl_info:
    customize MSVCCompiler
      libraries mkl_rt not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    blis_info:
      libraries blis not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    openblas_info:
      libraries openblas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
    get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
    customize GnuFCompiler
    Could not locate executable g77
    Could not locate executable f77
    customize IntelVisualFCompiler
    Could not locate executable ifort
    Could not locate executable ifl
    customize AbsoftFCompiler
    Could not locate executable f90
    customize CompaqVisualFCompiler
    Could not locate executable DF
    customize IntelItaniumVisualFCompiler
    Could not locate executable efl
    customize Gnu95FCompiler
    Could not locate executable gfortran
    Could not locate executable f95
    customize G95FCompiler
    Could not locate executable g95
    customize IntelEM64VisualFCompiler
    customize IntelEM64TFCompiler
    Could not locate executable efort
    Could not locate executable efc
    customize PGroupFlangCompiler
    Could not locate executable flang
    don't know how to compile Fortran code on platform 'nt'
      NOT AVAILABLE

    atlas_3_10_blas_threads_info:
    Setting PTATLAS=ATLAS
      libraries tatlas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    atlas_3_10_blas_info:
      libraries satlas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    atlas_blas_threads_info:
    Setting PTATLAS=ATLAS
      libraries ptf77blas,ptcblas,atlas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    atlas_blas_info:
      libraries f77blas,cblas,atlas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    accelerate_info:
      NOT AVAILABLE

    blas_info:
      libraries blas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    blas_src_info:
      NOT AVAILABLE

      NOT AVAILABLE

    non-existing path in 'numpy\\distutils': 'site.cfg'
    lapack_opt_info:
    lapack_mkl_info:
      libraries mkl_rt not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    openblas_lapack_info:
      libraries openblas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    openblas_clapack_info:
      libraries openblas,lapack not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    flame_info:
      libraries flame not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    atlas_3_10_threads_info:
    Setting PTATLAS=ATLAS
      libraries lapack_atlas not found in C:\
      libraries tatlas,tatlas not found in C:\
      libraries lapack_atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
      libraries tatlas,tatlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
    <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
      NOT AVAILABLE

    atlas_3_10_info:
      libraries lapack_atlas not found in C:\
      libraries satlas,satlas not found in C:\
      libraries lapack_atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
      libraries satlas,satlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
    <class 'numpy.distutils.system_info.atlas_3_10_info'>
      NOT AVAILABLE

    atlas_threads_info:
    Setting PTATLAS=ATLAS
      libraries lapack_atlas not found in C:\
      libraries ptf77blas,ptcblas,atlas not found in C:\
      libraries lapack_atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
      libraries ptf77blas,ptcblas,atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
    <class 'numpy.distutils.system_info.atlas_threads_info'>
      NOT AVAILABLE

    atlas_info:
      libraries lapack_atlas not found in C:\
      libraries f77blas,cblas,atlas not found in C:\
      libraries lapack_atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
      libraries f77blas,cblas,atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
    <class 'numpy.distutils.system_info.atlas_info'>
      NOT AVAILABLE

    lapack_info:
      libraries lapack not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    lapack_src_info:
      NOT AVAILABLE

      NOT AVAILABLE

    running dist_info
    running build_src
    build_src
    building py_modules sources
    creating build
    creating build\src.win32-3.6
    creating build\src.win32-3.6\numpy
    creating build\src.win32-3.6\numpy\distutils
    building library "npymath" sources
    Running from numpy source directory.
    setup.py:461: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
      run_build = parse_setuppy_commands()
    C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\system_info.py:1896: UserWarning:
        Optimized (vendor) Blas libraries are not found.
        Falls back to netlib Blas library which has worse performance.
        A better performance should be easily gained by switching
        Blas library.
      if self._calc_info(blas):
    C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\system_info.py:1896: UserWarning:
        Blas (http://www.netlib.org/blas/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [blas]) or by setting
        the BLAS environment variable.
      if self._calc_info(blas):
    C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\system_info.py:1896: UserWarning:
        Blas (http://www.netlib.org/blas/) sources not found.
        Directories to search for the sources can be specified in the
        numpy/distutils/site.cfg file (section [blas_src]) or by setting
        the BLAS_SRC environment variable.
      if self._calc_info(blas):
    C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\system_info.py:1730: UserWarning:
        Lapack (http://www.netlib.org/lapack/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [lapack]) or by setting
        the LAPACK environment variable.
      return getattr(self, '_calc_info_{}'.format(name))()
    C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\system_info.py:1730: UserWarning:
        Lapack (http://www.netlib.org/lapack/) sources not found.
        Directories to search for the sources can be specified in the
        numpy/distutils/site.cfg file (section [lapack_src]) or by setting
        the LAPACK_SRC environment variable.
      return getattr(self, '_calc_info_{}'.format(name))()
    C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\dist.py:261: UserWarning: Unknown distribution option: 'define_macros'
      warnings.warn(msg)
    Traceback (most recent call last):
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\site-packages\pip-19.0.3-py3.6.egg\pip\_vendor\pep517\_in_process.py", line 207, in <module>
        main()
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\site-packages\pip-19.0.3-py3.6.egg\pip\_vendor\pep517\_in_process.py", line 197, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\site-packages\pip-19.0.3-py3.6.egg\pip\_vendor\pep517\_in_process.py", line 69, in prepare_metadata_for_build_wheel
        return hook(metadata_directory, config_settings)
      File "C:\Users\Chris\AppData\Local\Temp\pip-build-env-pt1e0dfd\overlay\site-packages\setuptools\build_meta.py", line 158, in prepare_metadata_for_build_wheel
        self.run_setup()
      File "C:\Users\Chris\AppData\Local\Temp\pip-build-env-pt1e0dfd\overlay\site-packages\setuptools\build_meta.py", line 250, in run_setup
        self).run_setup(setup_script=setup_script)
      File "C:\Users\Chris\AppData\Local\Temp\pip-build-env-pt1e0dfd\overlay\site-packages\setuptools\build_meta.py", line 143, in run_setup
        exec(compile(code, __file__, 'exec'), locals())
      File "setup.py", line 488, in <module>
        setup_package()
      File "setup.py", line 480, in setup_package
        setup(**metadata)
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\core.py", line 171, in setup
        return old_setup(**new_attr)
      File "C:\Users\Chris\AppData\Local\Temp\pip-build-env-pt1e0dfd\overlay\site-packages\setuptools\__init__.py", line 161, in setup
        return distutils.core.setup(**attrs)
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\core.py", line 148, in setup
        dist.run_commands()
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\dist.py", line 955, in run_commands
        self.run_command(cmd)
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\dist.py", line 974, in run_command
        cmd_obj.run()
      File "C:\Users\Chris\AppData\Local\Temp\pip-build-env-pt1e0dfd\overlay\site-packages\setuptools\command\dist_info.py", line 31, in run
        egg_info.run()
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\command\egg_info.py", line 26, in run
        self.run_command("build_src")
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\dist.py", line 974, in run_command
        cmd_obj.run()
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\command\build_src.py", line 146, in run
        self.build_sources()
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\command\build_src.py", line 157, in build_sources
        self.build_library_sources(*libname_info)
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\command\build_src.py", line 290, in build_library_sources
        sources = self.generate_sources(sources, (lib_name, build_info))
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\command\build_src.py", line 380, in generate_sources
        source = func(extension, build_dir)
      File "numpy\core\setup.py", line 661, in get_mathlib_info
        raise RuntimeError("Broken toolchain: cannot link a simple C program")
    RuntimeError: Broken toolchain: cannot link a simple C program

    ----------------------------------------
Command "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\pypy3.exe C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\site-packages\pip-19.0.3-py3.6.egg\pip\_vendor\pep517\_in_process.py prepare_metadata_for_build_wheel C:\Users\Chris\AppData\Local\Temp\tmpjxmz4c4z" failed with error code 1 in C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy
</code>```

I am no longer seeing the original error anymore, I am always getting this no matter what now. I tried using pip install numpy, pip3 install numpy, and pypy -m pip install numpy. All give this same output.

答:
If your build tools not answering to your problem, try to install build tools manually through this link.

After that you have to restart your PC or laptop.

Then try pip3 install numpy. In python 3.x versions we use pip3 not pip.

ContentLicense: CC BY-SA 4.0

Body:
I am on Windows 10 using pypy3.6-v7.3.0. I am trying to install numpy with pip install numpy, but I keep getting the error: error: Microsoft Visual C++ 14.1 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/.

However I already have Visual Studio Community 2019 installed, and my C++ build tools are fully up to date.

Edit:

Here is the new error I am getting after installing build tools manually:

Collecting numpy
  Using cached https://files.pythonhosted.org/packages/2d/f3/795e50e3ea2dc7bc9d1a2eeea9997d5dce63b801e08dfc37c2efce341977/numpy-1.18.4.zip
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    Complete output from command C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\pypy3.exe C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\site-packages\pip-19.0.3-py3.6.egg\pip\_vendor\pep517\_in_process.py prepare_metadata_for_build_wheel C:\Users\Chris\AppData\Local\Temp\tmpjxmz4c4z:
    Processing numpy/random\_bounded_integers.pxd.in
    Processing numpy/random\mtrand.pyx
    Processing numpy/random\_bit_generator.pyx
    Processing numpy/random\_bounded_integers.pyx.in
    Processing numpy/random\_common.pyx
    Processing numpy/random\_generator.pyx
    Processing numpy/random\_mt19937.pyx
    Processing numpy/random\_pcg64.pyx
    Processing numpy/random\_philox.pyx
    Processing numpy/random\_sfc64.pyx
    Cythonizing sources
    blas_opt_info:
    blas_mkl_info:
    customize MSVCCompiler
      libraries mkl_rt not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    blis_info:
      libraries blis not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    openblas_info:
      libraries openblas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
    get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
    customize GnuFCompiler
    Could not locate executable g77
    Could not locate executable f77
    customize IntelVisualFCompiler
    Could not locate executable ifort
    Could not locate executable ifl
    customize AbsoftFCompiler
    Could not locate executable f90
    customize CompaqVisualFCompiler
    Could not locate executable DF
    customize IntelItaniumVisualFCompiler
    Could not locate executable efl
    customize Gnu95FCompiler
    Could not locate executable gfortran
    Could not locate executable f95
    customize G95FCompiler
    Could not locate executable g95
    customize IntelEM64VisualFCompiler
    customize IntelEM64TFCompiler
    Could not locate executable efort
    Could not locate executable efc
    customize PGroupFlangCompiler
    Could not locate executable flang
    don't know how to compile Fortran code on platform 'nt'
      NOT AVAILABLE

    atlas_3_10_blas_threads_info:
    Setting PTATLAS=ATLAS
      libraries tatlas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    atlas_3_10_blas_info:
      libraries satlas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    atlas_blas_threads_info:
    Setting PTATLAS=ATLAS
      libraries ptf77blas,ptcblas,atlas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    atlas_blas_info:
      libraries f77blas,cblas,atlas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    accelerate_info:
      NOT AVAILABLE

    blas_info:
      libraries blas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    blas_src_info:
      NOT AVAILABLE

      NOT AVAILABLE

    non-existing path in 'numpy\\distutils': 'site.cfg'
    lapack_opt_info:
    lapack_mkl_info:
      libraries mkl_rt not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    openblas_lapack_info:
      libraries openblas not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    openblas_clapack_info:
      libraries openblas,lapack not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    flame_info:
      libraries flame not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    atlas_3_10_threads_info:
    Setting PTATLAS=ATLAS
      libraries lapack_atlas not found in C:\
      libraries tatlas,tatlas not found in C:\
      libraries lapack_atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
      libraries tatlas,tatlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
    <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
      NOT AVAILABLE

    atlas_3_10_info:
      libraries lapack_atlas not found in C:\
      libraries satlas,satlas not found in C:\
      libraries lapack_atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
      libraries satlas,satlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
    <class 'numpy.distutils.system_info.atlas_3_10_info'>
      NOT AVAILABLE

    atlas_threads_info:
    Setting PTATLAS=ATLAS
      libraries lapack_atlas not found in C:\
      libraries ptf77blas,ptcblas,atlas not found in C:\
      libraries lapack_atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
      libraries ptf77blas,ptcblas,atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
    <class 'numpy.distutils.system_info.atlas_threads_info'>
      NOT AVAILABLE

    atlas_info:
      libraries lapack_atlas not found in C:\
      libraries f77blas,cblas,atlas not found in C:\
      libraries lapack_atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
      libraries f77blas,cblas,atlas not found in C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\libs
    <class 'numpy.distutils.system_info.atlas_info'>
      NOT AVAILABLE

    lapack_info:
      libraries lapack not found in ['C:\\', 'C:\\Users\\Chris\\AppData\\Local\\Programs\\Python\\pypy3.6-v7.3.0-win32\\libs']
      NOT AVAILABLE

    lapack_src_info:
      NOT AVAILABLE

      NOT AVAILABLE

    running dist_info
    running build_src
    build_src
    building py_modules sources
    creating build
    creating build\src.win32-3.6
    creating build\src.win32-3.6\numpy
    creating build\src.win32-3.6\numpy\distutils
    building library "npymath" sources
    Running from numpy source directory.
    setup.py:461: UserWarning: Unrecognized setuptools command, proceeding with generating Cython sources and expanding templates
      run_build = parse_setuppy_commands()
    C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\system_info.py:1896: UserWarning:
        Optimized (vendor) Blas libraries are not found.
        Falls back to netlib Blas library which has worse performance.
        A better performance should be easily gained by switching
        Blas library.
      if self._calc_info(blas):
    C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\system_info.py:1896: UserWarning:
        Blas (http://www.netlib.org/blas/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [blas]) or by setting
        the BLAS environment variable.
      if self._calc_info(blas):
    C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\system_info.py:1896: UserWarning:
        Blas (http://www.netlib.org/blas/) sources not found.
        Directories to search for the sources can be specified in the
        numpy/distutils/site.cfg file (section [blas_src]) or by setting
        the BLAS_SRC environment variable.
      if self._calc_info(blas):
    C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\system_info.py:1730: UserWarning:
        Lapack (http://www.netlib.org/lapack/) libraries not found.
        Directories to search for the libraries can be specified in the
        numpy/distutils/site.cfg file (section [lapack]) or by setting
        the LAPACK environment variable.
      return getattr(self, '_calc_info_{}'.format(name))()
    C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\system_info.py:1730: UserWarning:
        Lapack (http://www.netlib.org/lapack/) sources not found.
        Directories to search for the sources can be specified in the
        numpy/distutils/site.cfg file (section [lapack_src]) or by setting
        the LAPACK_SRC environment variable.
      return getattr(self, '_calc_info_{}'.format(name))()
    C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\dist.py:261: UserWarning: Unknown distribution option: 'define_macros'
      warnings.warn(msg)
    Traceback (most recent call last):
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\site-packages\pip-19.0.3-py3.6.egg\pip\_vendor\pep517\_in_process.py", line 207, in <module>
        main()
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\site-packages\pip-19.0.3-py3.6.egg\pip\_vendor\pep517\_in_process.py", line 197, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\site-packages\pip-19.0.3-py3.6.egg\pip\_vendor\pep517\_in_process.py", line 69, in prepare_metadata_for_build_wheel
        return hook(metadata_directory, config_settings)
      File "C:\Users\Chris\AppData\Local\Temp\pip-build-env-pt1e0dfd\overlay\site-packages\setuptools\build_meta.py", line 158, in prepare_metadata_for_build_wheel
        self.run_setup()
      File "C:\Users\Chris\AppData\Local\Temp\pip-build-env-pt1e0dfd\overlay\site-packages\setuptools\build_meta.py", line 250, in run_setup
        self).run_setup(setup_script=setup_script)
      File "C:\Users\Chris\AppData\Local\Temp\pip-build-env-pt1e0dfd\overlay\site-packages\setuptools\build_meta.py", line 143, in run_setup
        exec(compile(code, __file__, 'exec'), locals())
      File "setup.py", line 488, in <module>
        setup_package()
      File "setup.py", line 480, in setup_package
        setup(**metadata)
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\core.py", line 171, in setup
        return old_setup(**new_attr)
      File "C:\Users\Chris\AppData\Local\Temp\pip-build-env-pt1e0dfd\overlay\site-packages\setuptools\__init__.py", line 161, in setup
        return distutils.core.setup(**attrs)
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\core.py", line 148, in setup
        dist.run_commands()
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\dist.py", line 955, in run_commands
        self.run_command(cmd)
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\dist.py", line 974, in run_command
        cmd_obj.run()
      File "C:\Users\Chris\AppData\Local\Temp\pip-build-env-pt1e0dfd\overlay\site-packages\setuptools\command\dist_info.py", line 31, in run
        egg_info.run()
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\command\egg_info.py", line 26, in run
        self.run_command("build_src")
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\lib-python\3\distutils\dist.py", line 974, in run_command
        cmd_obj.run()
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\command\build_src.py", line 146, in run
        self.build_sources()
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\command\build_src.py", line 157, in build_sources
        self.build_library_sources(*libname_info)
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\command\build_src.py", line 290, in build_library_sources
        sources = self.generate_sources(sources, (lib_name, build_info))
      File "C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy\numpy\distutils\command\build_src.py", line 380, in generate_sources
        source = func(extension, build_dir)
      File "numpy\core\setup.py", line 661, in get_mathlib_info
        raise RuntimeError("Broken toolchain: cannot link a simple C program")
    RuntimeError: Broken toolchain: cannot link a simple C program

    ----------------------------------------
Command "C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\pypy3.exe C:\Users\Chris\AppData\Local\Programs\Python\pypy3.6-v7.3.0-win32\site-packages\pip-19.0.3-py3.6.egg\pip\_vendor\pep517\_in_process.py prepare_metadata_for_build_wheel C:\Users\Chris\AppData\Local\Temp\tmpjxmz4c4z" failed with error code 1 in C:\Users\Chris\AppData\Local\Temp\pip-install-1iwlc8lz\numpy

I am no longer seeing the original error anymore, I am always getting this no matter what now. I tried using pip install numpy, pip3 install numpy, and pypy -m pip install numpy. All give this same output.


问:
Coding exercise - grabbing garbage for each player movement python
Imagine a bi-dimensional grid (NxN) where each square has garbage in it, for each movement described by N, S, E, W (for north, south, east and west), the player moves accordingly and grabs the garbage there was in that square.

If the input = 'NESW' the output should be = 4
- 1 for square the player started
- 1 going north, 1 going East, 1 going South and 0 going West because he reaches the initial square where he started which is already "cleaned"

For input = 'NSNSNSNS' output = 2 for the same reason.

I'm having trouble counting the garbage and knowing if the player already went to that place.

```<code>def total_garbage(positions):
  garbage = 0
  N, S, E, W = 0, 0, 0, 0

  for direction in positions:

    if direction.upper() == 'N':
      N += 1
      garbage += 1
    elif direction.upper() == 'S':
      S += 1
      garbage += 1
    elif direction.upper() == 'E':
      E += 1
      garbage += 1
    elif direction.upper() == 'W':
      W += 1
      garbage += 1

  if N == S and E == W and E != 0 and W != 0:
    return garbage
  elif N == S and E == 0 and W == 0:
    return (garbage - min(N,S))

qp = total_garbage(['N','E','S','W'])
print(qp)
</code>```

This is what I have so far, it was just to start and try some stuff, but haven't been very successful :/

答:
First, when I run this code, I get 4 as I believe you are looking for. If you want to know if garbage was already collected in your square, I think you might need to track that in parallel to your movements and collections.. there are a few ways you could do this, I would suggest a list of lists for your grid, if you wanted a 3x3 grid, create something like :

```<code>grid = [[0,0,0],[0,0,0],[0,0,0]]
</code>```

you can now have something to keep track of where garbage has been picked and if there is any to be picked.

So now, your next step would be to figure out a starting point like

```<code>grid[0][0]
</code>```

then if you move up one, you would be in

```<code>grid[1][0]
</code>```

if you visit that spot, in your function, do something like:

```<code>newPos = grid[1][0]
if (newPos != 1) {
     // do your collecting and change grid[1][0] form 0 to 1
} else {
     // don't collect, track your movement or whatever else you want.
}
</code>```

I hope that was helpful! Good luck

Body:
Imagine a bi-dimensional grid (NxN) where each square has garbage in it, for each movement described by N, S, E, W (for north, south, east and west), the player moves accordingly and grabs the garbage there was in that square.

If the input = 'NESW' the output should be = 4
- 1 for square the player started
- 1 going north, 1 going East, 1 going South and 0 going West because he reaches the initial square where he started which is already "cleaned"

For input = 'NSNSNSNS' output = 2 for the same reason.

I'm having trouble counting the garbage and knowing if the player already went to that place.

def total_garbage(positions):
  garbage = 0
  N, S, E, W = 0, 0, 0, 0

  for direction in positions:

    if direction.upper() == 'N':
      N += 1
      garbage += 1
    elif direction.upper() == 'S':
      S += 1
      garbage += 1
    elif direction.upper() == 'E':
      E += 1
      garbage += 1
    elif direction.upper() == 'W':
      W += 1
      garbage += 1

  if N == S and E == W and E != 0 and W != 0:
    return garbage
  elif N == S and E == 0 and W == 0:
    return (garbage - min(N,S))

qp = total_garbage(['N','E','S','W'])
print(qp)

This is what I have so far, it was just to start and try some stuff, but haven't been very successful :/

Body:
First, when I run this code, I get 4 as I believe you are looking for. If you want to know if garbage was already collected in your square, I think you might need to track that in parallel to your movements and collections.. there are a few ways you could do this, I would suggest a list of lists for your grid, if you wanted a 3x3 grid, create something like :

grid = [[0,0,0],[0,0,0],[0,0,0]]

you can now have something to keep track of where garbage has been picked and if there is any to be picked.

So now, your next step would be to figure out a starting point like

grid[0][0]

then if you move up one, you would be in

grid[1][0]

if you visit that spot, in your function, do something like:

newPos = grid[1][0]
if (newPos != 1) {
     // do your collecting and change grid[1][0] form 0 to 1
} else {
     // don't collect, track your movement or whatever else you want.
}

I hope that was helpful! Good luck


问:
(FLASK) I can't figure out why my html file doesn't update/render
I already tried clearing my browser cache and history, but that did not seem to help. The old html file I used (Jinja) doesn't seem to update.

Basically, I rendered a file before this and jinja seems to be rendering that old file (not sample or index) instead of either sample or index .html.

I'm a beginner at Flask, so if this is a simple fix I apologize I don't know much...

Here is my code:

sample.py

```<code>from flask import Flask, render_template, redirect, url_for

app = Flask(" APP ")

@app.route("/home")
def home():
    return render_template("sample.html")

if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug = True)
</code>```

index.html (inherits from sample.html)

```<code>{% extends "sample.html" %}
{% block title %}Home Page {% endblock %}
{% block content %}
<h1> Welcome to the Index Page!</h1>
{% endblock %}
</code>```

sample.html

```<code><!doctype html>
<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
       <span class="navbar-toggler-icon"></span>
   </button>
         <div class="collapse navbar-collapse" id="navbarNav">
             <ul class="navbar-nav">
           <li class="nav-item active">
                     <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
    </li>
    <li class="nav-item">
        <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
    </li>
      </ul>
        </div>
    </nav>
    {% block content %}
    {% endblock %}
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
</code>```

答:
Assuming passing index.html (instead of the template is extends) to render_template() doesn't resolve this, it may depend on how you're starting the app. If you're starting it via something other than

```<code>python sample.py
</code>```

Then the if __name__ == '__main__': won't execute, and TEMPLATES_AUTO_RELOAD won't get set. Try setting TEMPLATES_AUTO_RELOAD right after you instantiate Flask(). (Also, for good form, remove the spaces on either side of APP.)

Body:
I already tried clearing my browser cache and history, but that did not seem to help. The old html file I used (Jinja) doesn't seem to update.

Basically, I rendered a file before this and jinja seems to be rendering that old file (not sample or index) instead of either sample or index .html.

I'm a beginner at Flask, so if this is a simple fix I apologize I don't know much...

Here is my code:

sample.py

from flask import Flask, render_template, redirect, url_for

app = Flask(" APP ")

@app.route("/home")
def home():
    return render_template("sample.html")

if __name__ == "__main__":
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    app.run(debug = True)

index.html (inherits from sample.html)

{% extends "sample.html" %}
{% block title %}Home Page {% endblock %}
{% block content %}

 Welcome to the Index Page!

{% endblock %}

sample.html

<!doctype html>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>{% block title %}{% endblock %}</title>

        Navbar
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">

   </button>

                     Home (current)

        Features

        Pricing

        Disabled

    {% block content %}
    {% endblock %}

Body:
Assuming passing index.html (instead of the template is extends) to render_template() doesn't resolve this, it may depend on how you're starting the app. If you're starting it via something other than

python sample.py

Then the if __name__ == '__main__': won't execute, and TEMPLATES_AUTO_RELOAD won't get set. Try setting TEMPLATES_AUTO_RELOAD right after you instantiate Flask(). (Also, for good form, remove the spaces on either side of APP.)


问:
onkeyup is not working in jQuery Validate for tinymce
For validation the form I use the plugin JQuery Validation (jquery.validate.js) with the additional-methods.js. This form contains many inputs in which the fields to be filled out are checked. I use the onkeyup rule for the fileds. Everything works, but does not work the rule onkeyup for tinymce. What needs to be registered so that it works?</p>

```<code>jQuery(function ($) {
        var validator = $("#adminForm").submit(function() {
            // update underlying textarea before submit validation
            tinyMCE.triggerSave();
        }).validate({
    onkeyup: function(element) {
        this.element(element);  // <- "eager validation"
    },
    onfocusout: function(element) {
        this.element(element);  // <- "eager validation"
    },
            ignore: "",
            rules: {
                title: {
                    required: true,
                    minlength: 10,
                    maxlength: 50
                },
                donate: {
                    required: true,
                    digits: true,
                    min: 1,
                    max: 60000
                },
                text: {
                    required: true,
                    minlength: 250
                },
                checkbox: {
                    required: true
                }
            },
            messages: {
                title: {
                    required: "enter the title",
                    minlength: "no less than 10 symbols",
                    maxlength: "no more than 50 symbols"
                },
                donate: {
                    required: "enter the number",
                    digits: "Not a number",
                    min: "no less than 1",
                    max: "no more than 60000"
                },
                text: {
                    required: "here is your text",
                    minlength: "no less than 250 symbols"
                },
                checkbox: {
                    required: "do you public spam?"
                }
            },
            errorPlacement: function(label, element) {
                // position error label after generated textarea
                if (element.is("textarea")) {
                    label.insertAfter(element.next());
                } else {
                    label.insertAfter(element)
                }
            }
        });
        validator.focusInvalid = function() {
            // put focus on tinymce on submit validation
            if (this.settings.focusInvalid) {
                try {
                    var toFocus = $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []);
                    if (toFocus.is("textarea")) {
                        tinyMCE.get(toFocus.attr("id")).focus();
                    } else {
                        toFocus.filter(":visible").focus();
                    }
                } catch (e) {
                    // ignore IE throwing errors when focusing hidden elements
                }
            }
        }
    });
</code>```

答: When you load TinyMCE the editor area is actually an iframe and not part of the main page so events like keyup are not happening in the main page but in the iframe.  You can certainly add event handling to the iframe as well but this is why you are not seeing these events triggered based on typing in the editor.

Body:
For validation the form I use the plugin JQuery Validation (jquery.validate.js) with the additional-methods.js. This form contains many inputs in which the fields to be filled out are checked. I use the onkeyup rule for the fileds. Everything works, but does not work the rule onkeyup for tinymce. What needs to be registered so that it works?

jQuery(function ($) {
        var validator = $("#adminForm").submit(function() {
            // update underlying textarea before submit validation
            tinyMCE.triggerSave();
        }).validate({
    onkeyup: function(element) {
        this.element(element);  // <- "eager validation"
    },
    onfocusout: function(element) {
        this.element(element);  // <- "eager validation"
    },
            ignore: "",
            rules: {
                title: {
                    required: true,
                    minlength: 10,
                    maxlength: 50
                },
                donate: {
                    required: true,
                    digits: true,
                    min: 1,
                    max: 60000
                },
                text: {
                    required: true,
                    minlength: 250
                },
                checkbox: {
                    required: true
                }
            },
            messages: {
                title: {
                    required: "enter the title",
                    minlength: "no less than 10 symbols",
                    maxlength: "no more than 50 symbols"
                },
                donate: {
                    required: "enter the number",
                    digits: "Not a number",
                    min: "no less than 1",
                    max: "no more than 60000"
                },
                text: {
                    required: "here is your text",
                    minlength: "no less than 250 symbols"
                },
                checkbox: {
                    required: "do you public spam?"
                }
            },
            errorPlacement: function(label, element) {
                // position error label after generated textarea
                if (element.is("textarea")) {
                    label.insertAfter(element.next());
                } else {
                    label.insertAfter(element)
                }
            }
        });
        validator.focusInvalid = function() {
            // put focus on tinymce on submit validation
            if (this.settings.focusInvalid) {
                try {
                    var toFocus = $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []);
                    if (toFocus.is("textarea")) {
                        tinyMCE.get(toFocus.attr("id")).focus();
                    } else {
                        toFocus.filter(":visible").focus();
                    }
                } catch (e) {
                    // ignore IE throwing errors when focusing hidden elements
                }
            }
        }
    });


问:
Installing Rails 3.1
I'm trying to install Rails 3.1.

It says to use 'gem install rails --pre' in the announcement blog post here:

http://weblog.rubyonrails.org/2011/5/22/rails-3-1-release-candidate

When I try

$ gem install rails --pre

I get the error:

ERROR:  While executing gem ... (NameError)
  uninitialized constant Syck::Syck

What to do?

答:
Regarding your specific problem: You may be seeing an error introduced by a faulty build of Rails 3.0.8.rc3 that got pushed as "rails --pre". See this issue in the Rails repository.

Instead of

gem install rails --pre

for the newest version, use

gem install rails -v ">=3.1.0rc"

or for 3.1.0.rc1 specifically:

gem install rails --version=3.1.0.rc1

See the guide referenced above for more advice.

ContentLicense: CC BY-SA 3.0

Title: Installing Rails 3.1


问:
Replace Value with the number of times a group of numbers has appeared in the vector up to that point
I have a vector like this of 1s and 0s next to each other.

```<code>vec <- c(1,1,1,0,0,1,1,1,1,0,0,0,1,1,1)

</code>```

I want to replace the 1s with the number the consecutive 1s showed up so the final vector would look like the one below.

```<code>vec1 <- c(1,1,1,0,0,2,2,2,2,0,0,0,3,3,3)

</code>```

I am not sure how to even start with this problem. Any help is appreciated.

答:
We can use rleid from data.table

```<code>library(data.table)
vec[as.logical(vec)] <- as.integer(factor(rleid(vec)[as.logical(vec)]))
vec
#[1] 1 1 1 0 0 2 2 2 2 0 0 0 3 3 3
</code>```

Body:
I have a vector like this of 1s and 0s next to each other.

vec <- c(1,1,1,0,0,1,1,1,1,0,0,0,1,1,1)

I want to replace the 1s with the number the consecutive 1s showed up so the final vector would look like the one below.

vec1 <- c(1,1,1,0,0,2,2,2,2,0,0,0,3,3,3)

I am not sure how to even start with this problem. Any help is appreciated.

Body:
We can use rleid from data.table

library(data.table)
vec[as.logical(vec)] <- as.integer(factor(rleid(vec)[as.logical(vec)]))
vec
#[1] 1 1 1 0 0 2 2 2 2 0 0 0 3 3 3


问:
python 3.6 bug or i am nuts
checks if items in a list are consecutive.

```<code>[True for x in lst[:-1] for y in lst[1:] if x + 1 == y]
</code>```

so list [1, 2, 3, 4, 5]
returns [True, True, True, True] meaning that list is consecutive.

list [1,2,3,4,4]
returns [True, True, True, True] meaning that list is consecutive, but it's not.

doing for each statement proves that

```<code>lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

print(consecutive(lst))

some_list = []
for i,j in zip(lst[:-1], lst[1:]):
    if i+1 == j:
        some_list.append(True)
    else:
        some_list.append(False)

print(some_list)
</code>```

What am i missing here?

答:
Try this: </p>

```<code>[True  if(lst[x]+1 == lst[x+1])  else False for x in range(len(lst)-1)]
</code>```

Title: python 3.6 bug or i am nuts

Body:
checks if items in a list are consecutive.

[True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

so list [1, 2, 3, 4, 5]
returns [True, True, True, True] meaning that list is consecutive.

list [1,2,3,4,4]
returns [True, True, True, True] meaning that list is consecutive, but it's not.

doing for each statement proves that

lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

print(consecutive(lst))

some_list = []
for i,j in zip(lst[:-1], lst[1:]):
    if i+1 == j:
        some_list.append(True)
    else:
        some_list.append(False)

print(some_list)

What am i missing here?

Body:
Try this:

[True  if(lst[x]+1 == lst[x+1])  else False for x in range(len(lst)-1)]


问:
Kotlin Android: Assigning Bitmap to Imageview
I am building an app with Kotlin frontend/Python backend. My python script creates a .png file under getFilesDir() directory (/data/user/0/com.example.inprogress/files/mygraph.png). I then want to use kotlin to fetch the .png file and display it on imageview.

My goal is to assign Bitmap value to my imageview id graphId.

I use the code below but I get blank imageview instead of the .png file I want to display.
Note that I'm not getting any error message. Where am I doing things wrong?

```<code>class GraphRes : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_graphres)

        var data = intent.extras
        var graph = data!!.get("res").toString()
        // graph is where the .png file is stored
        // graph: /data/user/0/com.example.inprogress/files/mygraph.png

        var graphId = ImageView(this)
        graphId.setImageBitmap(BitmapFactory.decodeFile(graph))

    }
}
</code>```

答:
Do you have READ_EXTERNAL_STORAGE permission?

If you have that and it still dont work, try the following approach:

```<code>graphId.setImageURI(Uri.fromFile(File(graph)));
</code>```

Or you can also use Glide library to display your image, it will do it efficiently.

Body:
I am building an app with Kotlin frontend/Python backend. My python script creates a .png file under getFilesDir() directory (/data/user/0/com.example.inprogress/files/mygraph.png). I then want to use kotlin to fetch the .png file and display it on imageview.

My goal is to assign Bitmap value to my imageview id graphId.

I use the code below but I get blank imageview instead of the .png file I want to display.
Note that I'm not getting any error message. Where am I doing things wrong?

class GraphRes : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_graphres)

        var data = intent.extras
        var graph = data!!.get("res").toString()
        // graph is where the .png file is stored
        // graph: /data/user/0/com.example.inprogress/files/mygraph.png

        var graphId = ImageView(this)
        graphId.setImageBitmap(BitmapFactory.decodeFile(graph))

    }
}

Body:
Do you have READ_EXTERNAL_STORAGE permission?

If you have that and it still dont work, try the following approach:

graphId.setImageURI(Uri.fromFile(File(graph)));

Or you can also use Glide library to display your image, it will do it efficiently.


问:
Reactive function giving error in Shiny framework R
I am trying to make a reactive plot with radio buttons in shiny. However, after using the reactive expressions I am not able to see any plot.

Here is the reproducible code of the complete app

```<code># Loading libs
library(shiny)
library(shinythemes)
library(ggplot2)
library(mapdata)
library(mapproj)

ui <- fluidPage(theme = shinytheme("cosmo"),
    navbarPage("PageTitle",
        tabPanel("US-Data-Visualizer",
                sidebarPanel(tags$h2("Map Visualizer"), tags$h4("Visualize the counts on US map, state wise"),
                      radioButtons("radio_option", label = "Select from the following options:",
                          choices = list("Total Cases" = "state$TOTAL.CASES", "New Cases" = "state$NEW.CASES",
                              "Active Cases" = "state$ACTIVE.CASES", "Total Deaths" = "state$TOTAL.DEATHS",
                              "New Deaths" = "state$NEW.DEATHS", "Total Tests" = "state$TOTAL.TESTS"),
                              selected = "state$TOTAL.CASES")),
                mainPanel(plotOutput("us_cases"))))
) #close fluid page

server <- function(input, output){
  state <- read.csv("https://raw.githubusercontent.com/spriyansh/ShinyApps/master/datasets/USA_State_Wise_Data.csv", fileEncoding="UTF-8")
  us_geo_data <- map_data("county")
  reactive_df <- reactive({
    us_geo_data <- data.table(us_geo_data)
    covid_map <- data.frame(state_names=unique(us_geo_data$region),
    values = input$radio_option)
    setkey(us_geo_data,region)
    covid_map <- data.table(covid_map)
    setkey(covid_map,state_names)
    map.df <- us_geo_data[covid_map]})
  output$us_cases <- renderPlot(
    ggplot(reactive_df()$map.df,
           aes(x = reactive_df()$map.df$long, y = reactive_df()$map.df$lat,
               group = reactive_df()$map.df$group,fill = reactive_df()$covid_map$values)) +
      geom_polygon(alpha = 0.8) + coord_map()
  )}

shinyApp(ui, server)

</code>```

答:
Your example is not reproducible because there is no data and no library calls. Please see here and here to know how to make a minimal, reproducible example.

Edit following OP's edit:

The problem is that you try to return different dataframes from reactive_df, which is impossible. You should instead merge covid_map and state_names together, so that all the information you need is in map.df, which is returned by reactive since it is the last action. Then, you can remove the long expressions in ggplot.

There was also a problem with the choices in radioButtons. It is better to only put the column names as choices and then to call filter the data with these column names with state[[input$radio_option]].

Here's your code:

```<code># Loading libs
library(shiny)
library(shinythemes)
library(ggplot2)
library(mapdata)
library(mapproj)
library(data.table)
library(dplyr)

state <- read.csv("https://raw.githubusercontent.com/spriyansh/ShinyApps/master/datasets/USA_State_Wise_Data.csv", fileEncoding = "UTF-8")
us_geo_data <- map_data("county")

ui <- fluidPage(
  theme = shinytheme("cosmo"),
  navbarPage(
    "PageTitle",
    tabPanel(
      "US-Data-Visualizer",
      sidebarPanel(
        tags$h2("Map Visualizer"), tags$h4("Visualize the counts on US map, state wise"),
        radioButtons("radio_option",
          label = "Select from the following options:",
          choices = list(
            "Total Cases" = "TOTAL.CASES", "New Cases" = "NEW.CASES",
            "Active Cases" = "ACTIVE.CASES", "Total Deaths" = "TOTAL.DEATHS",
            "New Deaths" = "NEW.DEATHS", "Total Tests" = "TOTAL.TESTS"
          ),
          selected = "TOTAL.CASES"
        )
      ),
      mainPanel(plotOutput("us_cases"))
    )
  )
) # close fluid page

server <- function(input, output) {

  reactive_df <- reactive({
    us_geo_data <- data.table(us_geo_data)
    covid_map <- data.frame(
      state_names = unique(us_geo_data$region),
      values = state[[input$radio_option]]
    )
    setkey(us_geo_data, region)
    covid_map <- data.table(covid_map)
    setkey(covid_map, state_names)
    map.df <- dplyr::left_join(us_geo_data, covid_map, by = c("region" = "state_names"))
  })
  output$us_cases <- renderPlot(
    ggplot(
      reactive_df(),
      aes(
        x = long, y = lat,
        group = group, fill = values
      )
    ) +
      geom_polygon(alpha = 0.8) +
      coord_map()
  )
}

shinyApp(ui, server)
</code>```

Body:
I am trying to make a reactive plot with radio buttons in shiny. However, after using the reactive expressions I am not able to see any plot.

Here is the reproducible code of the complete app

# Loading libs
library(shiny)
library(shinythemes)
library(ggplot2)
library(mapdata)
library(mapproj)

ui <- fluidPage(theme = shinytheme("cosmo"),
    navbarPage("PageTitle",
        tabPanel("US-Data-Visualizer",
                sidebarPanel(tags$h2("Map Visualizer"), tags$h4("Visualize the counts on US map, state wise"),
                      radioButtons("radio_option", label = "Select from the following options:",
                          choices = list("Total Cases" = "state$TOTAL.CASES", "New Cases" = "state$NEW.CASES",
                              "Active Cases" = "state$ACTIVE.CASES", "Total Deaths" = "state$TOTAL.DEATHS",
                              "New Deaths" = "state$NEW.DEATHS", "Total Tests" = "state$TOTAL.TESTS"),
                              selected = "state$TOTAL.CASES")),
                mainPanel(plotOutput("us_cases"))))
) #close fluid page

server <- function(input, output){
  state <- read.csv("https://raw.githubusercontent.com/spriyansh/ShinyApps/master/datasets/USA_State_Wise_Data.csv", fileEncoding="UTF-8")
  us_geo_data <- map_data("county")
  reactive_df <- reactive({
    us_geo_data <- data.table(us_geo_data)
    covid_map <- data.frame(state_names=unique(us_geo_data$region),
    values = input$radio_option)
    setkey(us_geo_data,region)
    covid_map <- data.table(covid_map)
    setkey(covid_map,state_names)
    map.df <- us_geo_data[covid_map]})
  output$us_cases <- renderPlot(
    ggplot(reactive_df()$map.df,
           aes(x = reactive_df()$map.df$long, y = reactive_df()$map.df$lat,
               group = reactive_df()$map.df$group,fill = reactive_df()$covid_map$values)) +
      geom_polygon(alpha = 0.8) + coord_map()
  )}

shinyApp(ui, server)

Body:
Your example is not reproducible because there is no data and no library calls. Please see here and here to know how to make a minimal, reproducible example.

Edit following OP's edit:

The problem is that you try to return different dataframes from reactive_df, which is impossible. You should instead merge covid_map and state_names together, so that all the information you need is in map.df, which is returned by reactive since it is the last action. Then, you can remove the long expressions in ggplot.

There was also a problem with the choices in radioButtons. It is better to only put the column names as choices and then to call filter the data with these column names with state[[input$radio_option]].

Here's your code:

# Loading libs
library(shiny)
library(shinythemes)
library(ggplot2)
library(mapdata)
library(mapproj)
library(data.table)
library(dplyr)

state <- read.csv("https://raw.githubusercontent.com/spriyansh/ShinyApps/master/datasets/USA_State_Wise_Data.csv", fileEncoding = "UTF-8")
us_geo_data <- map_data("county")

ui <- fluidPage(
  theme = shinytheme("cosmo"),
  navbarPage(
    "PageTitle",
    tabPanel(
      "US-Data-Visualizer",
      sidebarPanel(
        tags$h2("Map Visualizer"), tags$h4("Visualize the counts on US map, state wise"),
        radioButtons("radio_option",
          label = "Select from the following options:",
          choices = list(
            "Total Cases" = "TOTAL.CASES", "New Cases" = "NEW.CASES",
            "Active Cases" = "ACTIVE.CASES", "Total Deaths" = "TOTAL.DEATHS",
            "New Deaths" = "NEW.DEATHS", "Total Tests" = "TOTAL.TESTS"
          ),
          selected = "TOTAL.CASES"
        )
      ),
      mainPanel(plotOutput("us_cases"))
    )
  )
) # close fluid page

server <- function(input, output) {

  reactive_df <- reactive({
    us_geo_data <- data.table(us_geo_data)
    covid_map <- data.frame(
      state_names = unique(us_geo_data$region),
      values = state[[input$radio_option]]
    )
    setkey(us_geo_data, region)
    covid_map <- data.table(covid_map)
    setkey(covid_map, state_names)
    map.df <- dplyr::left_join(us_geo_data, covid_map, by = c("region" = "state_names"))
  })
  output$us_cases <- renderPlot(
    ggplot(
      reactive_df(),
      aes(
        x = long, y = lat,
        group = group, fill = values
      )
    ) +
      geom_polygon(alpha = 0.8) +
      coord_map()
  )
}

shinyApp(ui, server)


问:
Align value labels in horizontal stacked bar plot (Matplotlib)
Using the following code, I've added value labels to the horizontal stacked bar plot in Matplotlib:

```<code>import pandas
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

def sumzip(*items):
    return [sum(values) for values in zip(*items)]

fig, ax = plt.subplots(figsize=(10,6))

N = 5
values1 = [130, 120, 170, 164, 155]
values2 = [120, 185, 162, 150, 153]
values3 = [100, 170, 160, 145, 150]

ind = np.arange(N) + .15
width = 0.3

rects1 = plt.barh(ind, values1, width, color='blue')
rects2 = plt.barh(ind, values2, width, left = sumzip(values1), color='green')
rects3 = plt.barh(ind, values3, width, left = sumzip(values1, values2), color='red')

extra_space = 0.15
ax.set_yticks(ind+width-extra_space)
ax.set_yticklabels( ('Label1', 'Label2', 'Label3', 'Label4', 'Label5') )
ax.yaxis.set_tick_params(length=0,labelbottom=True)

for i, v in enumerate(values1):
    plt.text(v * 0.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values2):
    plt.text(v * 1.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values3):
    plt.text(v * 2.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

plt.show()
</code>```

And the code gives me the following result:

As you can see, the labels in green and red sections are not aligned properly. What to I need to do to correct this issue?

答:
The factors 1.45 and 2.45 will give the desired result only when the numbers in values1, values2, values3 are all equal.

You need to do the following:

For the second bar, x = first bar value + 0.45 * second bar value

For the third bar, x = first bar value + second bar value + 0.45 * third bar value

Following is how you can do it.

```<code># Use values1[i] + v * 0.45 as the x-coordinate
for i, v in enumerate(values2):
    plt.text(values1[i] + v * 0.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

# Use values1[i] + values2[i] + v * 0.45 as the x-coordinate
for i, v in enumerate(values3):
    plt.text(values1[i] + values2[i] + v * 0.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')
</code>```

Body:
Using the following code, I've added value labels to the horizontal stacked bar plot in Matplotlib:

import pandas
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

def sumzip(*items):
    return [sum(values) for values in zip(*items)]

fig, ax = plt.subplots(figsize=(10,6))

N = 5
values1 = [130, 120, 170, 164, 155]
values2 = [120, 185, 162, 150, 153]
values3 = [100, 170, 160, 145, 150]

ind = np.arange(N) + .15
width = 0.3

rects1 = plt.barh(ind, values1, width, color='blue')
rects2 = plt.barh(ind, values2, width, left = sumzip(values1), color='green')
rects3 = plt.barh(ind, values3, width, left = sumzip(values1, values2), color='red')

extra_space = 0.15
ax.set_yticks(ind+width-extra_space)
ax.set_yticklabels( ('Label1', 'Label2', 'Label3', 'Label4', 'Label5') )
ax.yaxis.set_tick_params(length=0,labelbottom=True)

for i, v in enumerate(values1):
    plt.text(v * 0.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values2):
    plt.text(v * 1.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

for i, v in enumerate(values3):
    plt.text(v * 2.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

plt.show()

And the code gives me the following result:

As you can see, the labels in green and red sections are not aligned properly. What to I need to do to correct this issue?

Body:
The factors 1.45 and 2.45 will give the desired result only when the numbers in values1, values2, values3 are all equal.

You need to do the following:

For the second bar, x = first bar value + 0.45 * second bar value

For the third bar, x = first bar value + second bar value + 0.45 * third bar value

Following is how you can do it.

# Use values1[i] + v * 0.45 as the x-coordinate
for i, v in enumerate(values2):
    plt.text(values1[i] + v * 0.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')

# Use values1[i] + values2[i] + v * 0.45 as the x-coordinate
for i, v in enumerate(values3):
    plt.text(values1[i] + values2[i] + v * 0.45, i + .145, str(v), color='white', fontweight='bold', fontsize=10,
             ha='center', va='center')


问:
header file and standard library
I am new to programming. learning C as of now. I understand that header file only contains the declarations and function prototypes, not the functions themselves. Am I correct?

I understand that Library is a single file that contains different object codes. Are these object codes necessarily written only in C language or other languages can also be used to generate such object codes?

On linking, does the entire library file get attached to the executable or just the object codes declared in the header file?

答:
I understand that header file only
  contains the declarations and function
  prototypes, not the functions
  themselves.

Usually, yes (although you can theoretically put any code you want in a header file).  Remember that a header file is usually just #include-d into a source file, and #include is basically equivalent to a copy-and-paste.

I understand that Library is a single file

Not necessarily.  "Library" is a bit of a loose term, but generally speaking, it's used to describe a collection of functions (and potentially data) that together perform some useful set of tasks.  These functions may be defined in one or several source files.  Typically, a library is pre-compiled into a standalone object file.  But again, not necessarily.

Are these object codes necessarily written only in C language

No.  They can be written in any language (because it will always be compiled down to raw machine code).  But if you want to use the library from C, then certain compatibility requirements must be fulfilled, to ensure that the C compiler knows how to call the library functions correctly.

On linking, does the entire library file get attached to the executable

Sometimes.  This is what's known as static linking.  The other main type is dynamic linking, where the library object code is linked at run-time.

Title: header file and standard library


问:
How to reset initialization while calling method of same class
Following i have a worker class and there is a foreach.

Inside the forach there is service call which can be  GetX(), GetY() ...

as implementation, I have to re-initialize the Api client based on the parameter, is there pattern to avoid _aService.SetApiClient(p) Line?

```<code>public class Worker
    {
        private readonly IAService _aService;

        public Worker(IAService entryPointService)
        {
            _aService = entryPointService;
        }

        protected void ExecuteAsync()
        {
            while (true)
            {
                new List<string>() { "x", "y", "z" }.ForEach(p =>
                {
                    _aService.SetApiClient(p);
                    _aService.GetX();
                    // OR _aService.GetY(),_aService.GetYZ();//
                });

            }
        }
}
        public class AService : IAService
        {
            private GoogleApiClient _googleApiClient;
            public AService(GoogleApiClient apiClient)
            {
                _googleApiClient = apiClient;
            }

            public void SetApiClient(string param)
            {
                _googleApiClient = new GoogleApiClient(new AuthProvider (param));
            }
            public string GetX()
            {
                return _googleApiClient.CallX();
            }
        }

        public interface IAService
        {
            void SetApiClient(string param);
            string GetX();
        }

        public interface IGoogleApiClient
        {
            string CallX();
            string CallY();
            string CallZ();
        }

public class GoogleApiClient : IGoogleApiClient
    {
        private AuthProvider _param;
        public GoogleApiClient(AuthProvider param)
        {
            _param = param;
        }
        public string CallX()
        {
            return DoSomeCal("X", _param);
        }
        public string CallY()
        {
            return DoSomeCal("Y", _param);
        }
        public string CallZ()
        {
            return DoSomeCal("Z", _param)
        }
    }
</code>```

please note that string list values can be any thing

答: Your api client really doesn't need to hold state.(private field}) It is a service / gateway class. Rather just pass param into the methods e.g.GetX(string param}.</p>

Body:
Following i have a worker class and there is a foreach.

Inside the forach there is service call which can be  GetX(), GetY() ...

as implementation, I have to re-initialize the Api client based on the parameter, is there pattern to avoid _aService.SetApiClient(p) Line?

public class Worker
    {
        private readonly IAService _aService;

        public Worker(IAService entryPointService)
        {
            _aService = entryPointService;
        }

        protected void ExecuteAsync()
        {
            while (true)
            {
                new List<string>() { "x", "y", "z" }.ForEach(p =>
                {
                    _aService.SetApiClient(p);
                    _aService.GetX();
                    // OR _aService.GetY(),_aService.GetYZ();//
                });

            }
        }
}
        public class AService : IAService
        {
            private GoogleApiClient _googleApiClient;
            public AService(GoogleApiClient apiClient)
            {
                _googleApiClient = apiClient;
            }

            public void SetApiClient(string param)
            {
                _googleApiClient = new GoogleApiClient(new AuthProvider (param));
            }
            public string GetX()
            {
                return _googleApiClient.CallX();
            }
        }

        public interface IAService
        {
            void SetApiClient(string param);
            string GetX();
        }

        public interface IGoogleApiClient
        {
            string CallX();
            string CallY();
            string CallZ();
        }

public class GoogleApiClient : IGoogleApiClient
    {
        private AuthProvider _param;
        public GoogleApiClient(AuthProvider param)
        {
            _param = param;
        }
        public string CallX()
        {
            return DoSomeCal("X", _param);
        }
        public string CallY()
        {
            return DoSomeCal("Y", _param);
        }
        public string CallZ()
        {
            return DoSomeCal("Z", _param)
        }
    }

please note that string list values can be any thing


问:
unknown at rule @include css(unknownAtRules) error while including @include in css file
I am trying to customize card columns by using Bootstrap 4 card layout. But why it is showing error if i am writing this code in my css file?

Error showing is in VS code:
unknown at rule @include css(unknownatrules)

HTML file

```<code><div class="card-columns">
  <div class="card" *ngFor="let item of vision">
    <div class="card-header">{{item.heading}}</div>
    <carousel [showIndicators]="false">
      <slide *ngFor="let item of vision">
        <img class="card-img-top embed-responsive embed-responsive-16by9" [src]="item.img" alt="vision image">
      </slide>
    </carousel>
  </div>
</div>
</code>```

CSS file

.card-columns {
  @include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
}```

答:
@include is a SASS feature not CSS feature.
Alternatively, you can turn the warning off by

```<code>  "css.lint.unknownAtRules": "ignore"
</code>```

Reference : https://github.com/microsoft/vscode/issues/53175

https://github.com/stylelint/stylelint/issues/3190

Body:
I am trying to customize card columns by using Bootstrap 4 card layout. But why it is showing error if i am writing this code in my css file?

Error showing is in VS code:
unknown at rule @include css(unknownatrules)

HTML file

{{item.heading}}

    <carousel [showIndicators]="false">
      <slide *ngFor="let item of vision">

      </slide>
    </carousel>

CSS file

.card-columns {
  @include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
}

Body:
@include is a SASS feature not CSS feature.
Alternatively, you can turn the warning off by

  "css.lint.unknownAtRules": "ignore"

Reference : https://github.com/microsoft/vscode/issues/53175

https://github.com/stylelint/stylelint/issues/3190


问:
Export TypeScript typed string prop values from a React component?
I have a React / TypeScript component. In Button.tsx:

```<code>type Props = {
  type:
    | "primary"
    | "secondary"
    | "tertiary"
}

const Button = React.FC<Props> = ({ type }) => {
    const color = (() => {
        switch (type) {
          case "primary":
            return 'red';
          case "secondary":
            return 'blue';
          case "tertiary":
            return 'green';
          default:
            throw new Error("A backgroundColor condition was missed");
        }
    })();

    return(
        <button style={{ background: color }}>Im a button</button>
    )
}
</code>```

Which I can use in other components. In Page.tsx:

```<code>const Page = () => {
    return(
        <div>
            <h1>Heading</h1>
            <Button type="primary" />
        </div>
    )
}
</code>```

In Storybook I need to use all of the type values. In Button.stories.js:

```<code>const types = [
  "primary",
  "secondary",
  "tertiary",
];

export const AllButtons = () => {
    return(
        types.map(type=>{
            <Button type={type} key={type} />
        })
    )
}
</code>```

Rather than having to repeat "primary", "secondary", "tertiary" is there a way I can export them from Button.tsx? That way if a new type is added the Storybook file will automatically have it.

I could use an enum in Button.tsx:

```<code>export enum Types {
  primary = "primary",
  secondary = "secondary",
  tertiary = "tertiary",
}

type Props = {
  type: Types;
};
</code>```

However then components that use Button cant just pass a string, you would have to import the enum every time you used Button, which isn't worth the trade off. In Page.tsx:

```<code>import { Type } from './Button'

const Page = () => {
    return(
        <div>
            <h1>Heading</h1>
            <Button type={Type.primary} />
        </div>
    )
}
</code>```

答:
In TypeScript you can get a type from a value (using typeof) but you can never get a value from a type. So if you want to eliminate the duplication, you need to use a value as your source of truth and derive the type from it.

For example, if you make the array of button types the source of truth, then you can use a const assertion (as const) to derive the type from it:

```<code>// Button.tsx
export const BUTTON_TYPES = [
    "primary",
    "secondary",
    "tertiary",
] as const;

type Types = typeof BUTTON_TYPES[number];

type Props = {
    type: Types;
}

const Button: React.FC<Props> = ({ type }) => {
    // ...

    return(
        <button style={{ background: color }}>Im a button</button>
    )
}
</code>```

Then you can import BUTTON_TYPES in your story and iterate over it.

You could also make a mapping from button type to color and use that as your source of truth. This would let you eliminate the color function from your component:

```<code>const TYPE_TO_COLOR = {
  primary: 'red',
  secondary: 'blue',
  tertiary: 'green',
} as const;

type Types = keyof typeof TYPE_TO_COLOR;
// type Types = "primary" | "secondary" | "tertiary"
export const BUTTON_TYPES = Object.keys(TYPE_TO_COLOR);

type Props = {
  type: Types;
}

const Button: React.FC<Props> = ({ type }) => {
  const color = TYPE_TO_COLOR[type];
  if (!color) {
    throw new Error("A backgroundColor condition was missed");
  }

  return (
    <button style={{ background: color }}>Im a button</button>
  );
}
</code>```

Body:
I have a React / TypeScript component. In Button.tsx:

type Props = {
  type:
    | "primary"
    | "secondary"
    | "tertiary"
}

const Button = React.FC<Props> = ({ type }) => {
    const color = (() => {
        switch (type) {
          case "primary":
            return 'red';
          case "secondary":
            return 'blue';
          case "tertiary":
            return 'green';
          default:
            throw new Error("A backgroundColor condition was missed");
        }
    })();

    return(
        <button style={{ background: color }}>Im a button</button>
    )
}

Which I can use in other components. In Page.tsx:

const Page = () => {
    return(

Heading

            <Button type="primary" />

    )
}

In Storybook I need to use all of the type values. In Button.stories.js:

const types = [
  "primary",
  "secondary",
  "tertiary",
];

export const AllButtons = () => {
    return(
        types.map(type=>{
            <Button type={type} key={type} />
        })
    )
}

Rather than having to repeat "primary", "secondary", "tertiary" is there a way I can export them from Button.tsx? That way if a new type is added the Storybook file will automatically have it.

I could use an enum in Button.tsx:

export enum Types {
  primary = "primary",
  secondary = "secondary",
  tertiary = "tertiary",
}

type Props = {
  type: Types;
};

However then components that use Button cant just pass a string, you would have to import the enum every time you used Button, which isn't worth the trade off. In Page.tsx:

import { Type } from './Button'

const Page = () => {
    return(

Heading

            <Button type={Type.primary} />

    )
}

Body:
In TypeScript you can get a type from a value (using typeof) but you can never get a value from a type. So if you want to eliminate the duplication, you need to use a value as your source of truth and derive the type from it.

For example, if you make the array of button types the source of truth, then you can use a const assertion (as const) to derive the type from it:

// Button.tsx
export const BUTTON_TYPES = [
    "primary",
    "secondary",
    "tertiary",
] as const;

type Types = typeof BUTTON_TYPES[number];

type Props = {
    type: Types;
}

const Button: React.FC<Props> = ({ type }) => {
    // ...

    return(
        <button style={{ background: color }}>Im a button</button>
    )
}

Then you can import BUTTON_TYPES in your story and iterate over it.

You could also make a mapping from button type to color and use that as your source of truth. This would let you eliminate the color function from your component:

const TYPE_TO_COLOR = {
  primary: 'red',
  secondary: 'blue',
  tertiary: 'green',
} as const;

type Types = keyof typeof TYPE_TO_COLOR;
// type Types = "primary" | "secondary" | "tertiary"
export const BUTTON_TYPES = Object.keys(TYPE_TO_COLOR);

type Props = {
  type: Types;
}

const Button: React.FC<Props> = ({ type }) => {
  const color = TYPE_TO_COLOR[type];
  if (!color) {
    throw new Error("A backgroundColor condition was missed");
  }

  return (
    <button style={{ background: color }}>Im a button</button>
  );
}


问:
How do you know which Controller to use when multiple models are displayed on a page?
For example, consider a forum's homepage:

```<code>Category
  Forum
  Forum
Category
  Forum
  Forum
Category
  Forum
</code>```

Should the root path point to categories#index because you're populating @categories and then looping through the forums for each category in the view?

Or should the root path point to forums#index because, more conceptually, the purpose of this index is to showcase the forums and the categories are only used to organize what really amounts to a list of forums?

答:
Mentally (and technically) the Category object can be reduced to an attribute on the Forum model. Also, you are better of querying for the Forums and then "grouping" them per category.

So in this case this view belongs to the Forum controller.

Body:
For example, consider a forum's homepage:

Category
  Forum
  Forum
Category
  Forum
  Forum
Category
  Forum

Should the root path point to categories#index because you're populating @categories and then looping through the forums for each category in the view?

Or should the root path point to forums#index because, more conceptually, the purpose of this index is to showcase the forums and the categories are only used to organize what really amounts to a list of forums?


问:
React Router and Material-Table - filter column values
How can I pass values of Route params into the filter fields of a React table?

I'm using a component called material-table.
Got a set of links like this:

```<code><ul>
  <li>
    <Link to="/Products/Dogs/Foods">Dog Food Products</Link>
  </li>
  <li>
    <Link to="/Services/Cats/Grooming">Cat Grooming Services</Link>
  </li>
</ul>

<Switch>
  <Route exact path="/:business/:category/:product" component={Material_Table}/>
</Switch>
</code>```

Then in the Material_Table component, I need to filter the columns based on those url params. Right now just putting them in an h4:

```<code><div className="alert">
      <h4>Business: {business}. Category: {category}. Product: {product}.</h4>
    </div>

    <MaterialTable
        title = "Projects"
        icons = {tableIcons}
        columns={[
            {
                title: 'Name',
                field: 'name'
            },
            {
                title: 'Business',
                field: 'values[9]'
            },
            {
                title: 'Category',
                field: 'values[10]'
            },
            {
                title: 'Product',
                field: 'values[8]'
            },
        ]}
        data = {items}
        options ={{
          filtering: true
        }}
        />
</code>```

Tried putting expressions right in the columns object but that does not work.
I know there's an option for default value, but that doesn't seem right either.
Any help much appreciated!

答:
Using defaultFilter on each column works:

```<code><MaterialTable
    title = "Projects"
    icons = {tableIcons}
    columns={[
        {
            title: 'Name',
            field: 'name'
        },
        {
            title: 'Business',
            field: 'values[9]',
            defaultFiler: business
        },
        {
            title: 'Category',
            field: 'values[10]',
            defaultFilter: category
        },
        {
            title: 'Product',
            field: 'values[8]',
            defaultFiler: product
        },
    ]}
    data = {items}
    options ={{
      filtering: true
    }}
    />
</code>```

Body:
How can I pass values of Route params into the filter fields of a React table?

I'm using a component called material-table.
Got a set of links like this:

    <Link to="/Products/Dogs/Foods">Dog Food Products</Link>

    <Link to="/Services/Cats/Grooming">Cat Grooming Services</Link>

<Switch>
  <Route exact path="/:business/:category/:product" component={Material_Table}/>
</Switch>

Then in the Material_Table component, I need to filter the columns based on those url params. Right now just putting them in an h4:

Business: {business}. Category: {category}. Product: {product}.

    <MaterialTable
        title = "Projects"
        icons = {tableIcons}
        columns={[
            {
                title: 'Name',
                field: 'name'
            },
            {
                title: 'Business',
                field: 'values[9]'
            },
            {
                title: 'Category',
                field: 'values[10]'
            },
            {
                title: 'Product',
                field: 'values[8]'
            },
        ]}
        data = {items}
        options ={{
          filtering: true
        }}
        />

Tried putting expressions right in the columns object but that does not work.
I know there's an option for default value, but that doesn't seem right either.
Any help much appreciated!

Body:
Using defaultFilter on each column works:

<MaterialTable
    title = "Projects"
    icons = {tableIcons}
    columns={[
        {
            title: 'Name',
            field: 'name'
        },
        {
            title: 'Business',
            field: 'values[9]',
            defaultFiler: business
        },
        {
            title: 'Category',
            field: 'values[10]',
            defaultFilter: category
        },
        {
            title: 'Product',
            field: 'values[8]',
            defaultFiler: product
        },
    ]}
    data = {items}
    options ={{
      filtering: true
    }}
    />


问:
WTForms Regexp validator: How to match white space within html tags using regex
I have a form with a textarea field and wonder if I could use WTForms Regexp validator to prevent the form submitting when the textarea contains only blank spaces.
Is there a way?

This is my form:

```<code>class AddReviewForm(FlaskForm):
    review = TextAreaField("Review", validators=[DataRequired())
    submit = SubmitField("Post Review")
</code>```

I was hoping Regexp would allow me to prevent only spaces.
My textarea fields include CKEditor, which adds
 (or other tags) to the input in order to display it as WYSIWYG.

So in the database the whitespaces look like this:

```<code>"<p>     </p>"
</code>```

And that shouldn't validate.

答:
Take a look at this I think this might help you :

Here is the link to the above image

As you can see from the image above this should satisfy your condition :

"if the data is a string type, a string containing only whitespace characters is considered false."

Let me know if that works :D!

Body:
I have a form with a textarea field and wonder if I could use WTForms Regexp validator to prevent the form submitting when the textarea contains only blank spaces.
Is there a way?

This is my form:

class AddReviewForm(FlaskForm):
    review = TextAreaField("Review", validators=[DataRequired())
    submit = SubmitField("Post Review")

I was hoping Regexp would allow me to prevent only spaces.
My textarea fields include CKEditor, which adds
 (or other tags) to the input in order to display it as WYSIWYG.

So in the database the whitespaces look like this:

"

"

And that shouldn't validate.