问:
Getting Frame drop & laggy after play m3u8 url in exoplayer in Android TV
Here is my player Fragment code. I prepare an Android tv app using exoplayer using m3u8 url but after Play m3u8 url 2-3 second screen getting Frame drop & laggy in Android TV. I tried multiple way but can't fixed it. Here is my m3u8 url: http://15.1.1.34:8282/en3-37/tracks-v1a1/mono.m3u8

How I can fixed such kinds of issues. (Other iptv player this m3u8 url working fine & video quality is 1920x1080). Let me know if I missed anything here in code.

```<code>@AndroidEntryPoint
class SmartTvPlayerFragment : BaseFragment<FragmentSmartTvPlayerBinding>(),Player.Listener {

    private val viewModel: TvRemoteKeyEventViewModel by activityViewModels()

    @Inject
    lateinit var tvAdapter: SmartTvAdapter
    private lateinit var smartTvDTO: SmartTvDTO
    var dataList: List<SmartTvDTO.Saiptv> = ArrayList()
    var linkPosition = 0
    var ration = true
    var playListVisible = false

    private var qualityPopUp: PopupMenu?=null
    private var player: ExoPlayer? = null
    private var playbackPosition = 0L
    private var playWhenReady = true
    private var trackSelector: DefaultTrackSelector?=null
    var qualityList = ArrayList<Pair<String, TrackSelectionOverrides.Builder>>()

    override val layout: Int
        get() = R.layout.fragment_smart_tv_player

    override fun onCreated(savedInstanceState: Bundle?) {
        initListener()
        observeKeyEventChanges()
    }

    private fun initListener() {

        hideSystemBar(requireActivity())

        /** --- Receiving data & Set to recyclerview + list view --- **/
        tvAdapter = SmartTvAdapter(requireContext())
        smartTvDTO = arguments?.getParcelable("smarttv")!!
        dataList = smartTvDTO.saiptv
        tvAdapter.addTvChannelList(dataList)

        /** --- Recyclerview Setup --- **/
        binding.playerExo.findViewById<RecyclerView>(R.id.serverlist_reyclerview).apply {
            hasFixedSize()
            layoutManager = LinearLayoutManager(requireContext())
            adapter = tvAdapter

        }

        /** --- Channel Item Click For Play --- **/
        tvAdapter.iptvItemClickActionListener = {
            binding.playerExo.findViewById<TextView>(R.id.tv_channel_name).text =
                dataList[it].channelName
            if (Util.SDK_INT > 23) {
                releasePlayer()
                linkPosition = it
                initPlayer()
            }
        }
    }

    /** --- FUNCTION: Initialize player EXO--- **/
    private fun initPlayer() {
        trackSelector = DefaultTrackSelector(requireContext(), AdaptiveTrackSelection.Factory())
        player = ExoPlayer.Builder(requireContext())
            .setTrackSelector(trackSelector!!)
            .build()
        player?.playWhenReady = true
        binding.playerExo.player = player
        val defaultHttpDataSourceFactory = DefaultHttpDataSource.Factory()
        val mediaItem = MediaItem.fromUri(dataList[linkPosition].channelUrl) /** -- Set list item as list -- **/
        val mediaSource = HlsMediaSource.Factory(defaultHttpDataSourceFactory).createMediaSource(mediaItem)
        player?.setMediaSource(mediaSource)
        player?.seekTo(playbackPosition)
        player?.playWhenReady = playWhenReady
        player?.addListener(this)
        player?.prepare()

        /** -- Set Channel Name to Controller Text View -- **/
        binding.playerExo.findViewById<TextView>(R.id.tv_channel_name).text = dataList[linkPosition].channelName

        /** --- Channel Item Click For show tv channel list --- **/
        binding.playerExo.findViewById<ImageView>(R.id.playlist).setOnClickListener {
            if (!playListVisible) {
                playListVisible = true
                binding.playerExo.findViewById<RecyclerView>(R.id.serverlist_reyclerview).visibility =
                    View.VISIBLE
            } else {
                playListVisible = false
                binding.playerExo.findViewById<RecyclerView>(R.id.serverlist_reyclerview).visibility =
                    View.GONE
            }
        }

        /** -- Set Channel Quality -- **/
        binding.playerExo.findViewById<ImageView>(R.id.exo_quality).setOnClickListener {
            qualityPopUp?.show()
        }

        /** -- Set Previous Channel Action -- **/
        binding.playerExo.findViewById<ImageView>(R.id.exo_prev_link).setOnClickListener {
            if (linkPosition == 0) {
                showSimpleMessageWithSnackbar("This is First channel")
            } else {
                if (Util.SDK_INT > 23) {
                    releasePlayer()
                    linkPosition -= 1
                    initPlayer()
                }
            }
        }

        /** -- Set Previous Next Action -- **/
        binding.playerExo.findViewById<ImageView>(R.id.exo_next_link).setOnClickListener {
            if (linkPosition == tvAdapter.itemCount - 1) {
                showSimpleMessageWithSnackbar("This is last channel")
            } else {
                if (Util.SDK_INT > 23) {
                    releasePlayer()
                    linkPosition += 1
                    initPlayer()
                }
            }
        }

        /** -- Set Screen Aspect Ration Action -- **/
        binding.playerExo.findViewById<ImageView>(R.id.screenratio).setOnClickListener {
            if (ration) {
                binding.playerExo.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIXED_WIDTH
                ration = false
            } else {
                binding.playerExo.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL
                ration = true
            }
        }

    }

    /** --- FUNCTION: Prepare Channel Quality--- **/
    private fun setUpQualityList() {
        qualityPopUp = PopupMenu(requireContext(), binding.playerExo.findViewById(R.id.exo_quality))
        qualityList.let {
            for ((i, videoQuality) in it.withIndex()) {
                qualityPopUp?.menu?.add(0, i, 0, videoQuality.first)
            }
        }
        qualityPopUp?.setOnMenuItemClickListener { menuItem ->
            qualityList[menuItem.itemId].let {
                trackSelector!!.parameters = trackSelector!!.parameters
                    .buildUpon()
                    .setTrackSelectionOverrides(it.second.build())
                    .setTunnelingEnabled(true)
                    .setMaxVideoSizeSd()
                    .build()
            }
            true
        }
    }

    /** --- FUNCTION: Track information if change--- **/
    override fun onTracksInfoChanged(tracksInfo: TracksInfo) {
        println("TRACK CHANGED")
        println(tracksInfo.trackGroupInfos)
    }

    /** --- FUNCTION: Track Playback state change--- **/
    override fun onPlaybackStateChanged(playbackState: Int) {
        if (playbackState==Player.STATE_READY){
            trackSelector?.generateQualityList()?.let {
                qualityList = it
                setUpQualityList()
            }
        }
    }

    /** --- FUNCTION: Release Player when destroy or not used --- **/
    private fun releasePlayer() {
        player?.let {
            playbackPosition = it.currentPosition
            playWhenReady = it.playWhenReady
            it.release()
            player = null
        }
    }

    override fun onStart() {
        super.onStart()
        if (Util.SDK_INT >= 24) {
            initPlayer()
        }
    }

    override fun onStop() {
        super.onStop()
        if (Util.SDK_INT >= 24) {
            releasePlayer()
        }
    }

    override fun onResume() {
        super.onResume()
        if (Util.SDK_INT < 24) {
            initPlayer()
        }
    }
    override fun onPause() {
        super.onPause()
        if (Util.SDK_INT < 24) {
            releasePlayer()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        releasePlayer()
    }

    /** Whenever the key up event is either of the volume keys,
    capture an image or anything. The value is always set to
    KeyEvent.KEYCODE_VOLUME_UP or  KeyEvent.KEYCODE_VOLUME_DOWN
     **/
    private fun observeKeyEventChanges() {
        viewModel.keyEvent1.observe(viewLifecycleOwner) {
            nextKeyEvent()
        }
        viewModel.keyEvent2.observe(viewLifecycleOwner) {
            previousKeyEvent()
        }
    }

    /** --- FUNCTION: TV Remote Next Channel load action --- **/
    private fun nextKeyEvent(){
        if (linkPosition == tvAdapter.itemCount - 1) {
            showSimpleMessageWithSnackbar("This is last channel")
        } else {
            if (Util.SDK_INT > 23) {
                releasePlayer()
                linkPosition += 1
                initPlayer()
            }
        }
    }

    /** --- FUNCTION: TV Remote Previous Channel load action --- **/
    private fun previousKeyEvent(){
        if (linkPosition == 0) {
            showSimpleMessageWithSnackbar("This is First channel")
        } else {
            if (Util.SDK_INT > 23) {
                releasePlayer()
                linkPosition -= 1
                initPlayer()
            }
        }
    }
}
</code>```

Body:
Here is my player Fragment code. I prepare an Android tv app using exoplayer using m3u8 url but after Play m3u8 url 2-3 second screen getting Frame drop & laggy in Android TV. I tried multiple way but can't fixed it. Here is my m3u8 url: http://15.1.1.34:8282/en3-37/tracks-v1a1/mono.m3u8

How I can fixed such kinds of issues. (Other iptv player this m3u8 url working fine & video quality is 1920x1080). Let me know if I missed anything here in code.

@AndroidEntryPoint
class SmartTvPlayerFragment : BaseFragment<FragmentSmartTvPlayerBinding>(),Player.Listener {

    private val viewModel: TvRemoteKeyEventViewModel by activityViewModels()

    @Inject
    lateinit var tvAdapter: SmartTvAdapter
    private lateinit var smartTvDTO: SmartTvDTO
    var dataList: List<SmartTvDTO.Saiptv> = ArrayList()
    var linkPosition = 0
    var ration = true
    var playListVisible = false

    private var qualityPopUp: PopupMenu?=null
    private var player: ExoPlayer? = null
    private var playbackPosition = 0L
    private var playWhenReady = true
    private var trackSelector: DefaultTrackSelector?=null
    var qualityList = ArrayList<Pair<String, TrackSelectionOverrides.Builder>>()

    override val layout: Int
        get() = R.layout.fragment_smart_tv_player

    override fun onCreated(savedInstanceState: Bundle?) {
        initListener()
        observeKeyEventChanges()
    }

    private fun initListener() {

        hideSystemBar(requireActivity())

        /** --- Receiving data & Set to recyclerview + list view --- **/
        tvAdapter = SmartTvAdapter(requireContext())
        smartTvDTO = arguments?.getParcelable("smarttv")!!
        dataList = smartTvDTO.saiptv
        tvAdapter.addTvChannelList(dataList)

        /** --- Recyclerview Setup --- **/
        binding.playerExo.findViewById<RecyclerView>(R.id.serverlist_reyclerview).apply {
            hasFixedSize()
            layoutManager = LinearLayoutManager(requireContext())
            adapter = tvAdapter

        }

        /** --- Channel Item Click For Play --- **/
        tvAdapter.iptvItemClickActionListener = {
            binding.playerExo.findViewById<TextView>(R.id.tv_channel_name).text =
                dataList[it].channelName
            if (Util.SDK_INT > 23) {
                releasePlayer()
                linkPosition = it
                initPlayer()
            }
        }
    }

    /** --- FUNCTION: Initialize player EXO--- **/
    private fun initPlayer() {
        trackSelector = DefaultTrackSelector(requireContext(), AdaptiveTrackSelection.Factory())
        player = ExoPlayer.Builder(requireContext())
            .setTrackSelector(trackSelector!!)
            .build()
        player?.playWhenReady = true
        binding.playerExo.player = player
        val defaultHttpDataSourceFactory = DefaultHttpDataSource.Factory()
        val mediaItem = MediaItem.fromUri(dataList[linkPosition].channelUrl) /** -- Set list item as list -- **/
        val mediaSource = HlsMediaSource.Factory(defaultHttpDataSourceFactory).createMediaSource(mediaItem)
        player?.setMediaSource(mediaSource)
        player?.seekTo(playbackPosition)
        player?.playWhenReady = playWhenReady
        player?.addListener(this)
        player?.prepare()

        /** -- Set Channel Name to Controller Text View -- **/
        binding.playerExo.findViewById<TextView>(R.id.tv_channel_name).text = dataList[linkPosition].channelName

        /** --- Channel Item Click For show tv channel list --- **/
        binding.playerExo.findViewById<ImageView>(R.id.playlist).setOnClickListener {
            if (!playListVisible) {
                playListVisible = true
                binding.playerExo.findViewById<RecyclerView>(R.id.serverlist_reyclerview).visibility =
                    View.VISIBLE
            } else {
                playListVisible = false
                binding.playerExo.findViewById<RecyclerView>(R.id.serverlist_reyclerview).visibility =
                    View.GONE
            }
        }

        /** -- Set Channel Quality -- **/
        binding.playerExo.findViewById<ImageView>(R.id.exo_quality).setOnClickListener {
            qualityPopUp?.show()
        }

        /** -- Set Previous Channel Action -- **/
        binding.playerExo.findViewById<ImageView>(R.id.exo_prev_link).setOnClickListener {
            if (linkPosition == 0) {
                showSimpleMessageWithSnackbar("This is First channel")
            } else {
                if (Util.SDK_INT > 23) {
                    releasePlayer()
                    linkPosition -= 1
                    initPlayer()
                }
            }
        }

        /** -- Set Previous Next Action -- **/
        binding.playerExo.findViewById<ImageView>(R.id.exo_next_link).setOnClickListener {
            if (linkPosition == tvAdapter.itemCount - 1) {
                showSimpleMessageWithSnackbar("This is last channel")
            } else {
                if (Util.SDK_INT > 23) {
                    releasePlayer()
                    linkPosition += 1
                    initPlayer()
                }
            }
        }

        /** -- Set Screen Aspect Ration Action -- **/
        binding.playerExo.findViewById<ImageView>(R.id.screenratio).setOnClickListener {
            if (ration) {
                binding.playerExo.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIXED_WIDTH
                ration = false
            } else {
                binding.playerExo.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL
                ration = true
            }
        }

    }

    /** --- FUNCTION: Prepare Channel Quality--- **/
    private fun setUpQualityList() {
        qualityPopUp = PopupMenu(requireContext(), binding.playerExo.findViewById(R.id.exo_quality))
        qualityList.let {
            for ((i, videoQuality) in it.withIndex()) {
                qualityPopUp?.menu?.add(0, i, 0, videoQuality.first)
            }
        }
        qualityPopUp?.setOnMenuItemClickListener { menuItem ->
            qualityList[menuItem.itemId].let {
                trackSelector!!.parameters = trackSelector!!.parameters
                    .buildUpon()
                    .setTrackSelectionOverrides(it.second.build())
                    .setTunnelingEnabled(true)
                    .setMaxVideoSizeSd()
                    .build()
            }
            true
        }
    }

    /** --- FUNCTION: Track information if change--- **/
    override fun onTracksInfoChanged(tracksInfo: TracksInfo) {
        println("TRACK CHANGED")
        println(tracksInfo.trackGroupInfos)
    }

    /** --- FUNCTION: Track Playback state change--- **/
    override fun onPlaybackStateChanged(playbackState: Int) {
        if (playbackState==Player.STATE_READY){
            trackSelector?.generateQualityList()?.let {
                qualityList = it
                setUpQualityList()
            }
        }
    }

    /** --- FUNCTION: Release Player when destroy or not used --- **/
    private fun releasePlayer() {
        player?.let {
            playbackPosition = it.currentPosition
            playWhenReady = it.playWhenReady
            it.release()
            player = null
        }
    }

    override fun onStart() {
        super.onStart()
        if (Util.SDK_INT >= 24) {
            initPlayer()
        }
    }

    override fun onStop() {
        super.onStop()
        if (Util.SDK_INT >= 24) {
            releasePlayer()
        }
    }

    override fun onResume() {
        super.onResume()
        if (Util.SDK_INT < 24) {
            initPlayer()
        }
    }
    override fun onPause() {
        super.onPause()
        if (Util.SDK_INT < 24) {
            releasePlayer()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        releasePlayer()
    }

    /** Whenever the key up event is either of the volume keys,
    capture an image or anything. The value is always set to
    KeyEvent.KEYCODE_VOLUME_UP or  KeyEvent.KEYCODE_VOLUME_DOWN
     **/
    private fun observeKeyEventChanges() {
        viewModel.keyEvent1.observe(viewLifecycleOwner) {
            nextKeyEvent()
        }
        viewModel.keyEvent2.observe(viewLifecycleOwner) {
            previousKeyEvent()
        }
    }

    /** --- FUNCTION: TV Remote Next Channel load action --- **/
    private fun nextKeyEvent(){
        if (linkPosition == tvAdapter.itemCount - 1) {
            showSimpleMessageWithSnackbar("This is last channel")
        } else {
            if (Util.SDK_INT > 23) {
                releasePlayer()
                linkPosition += 1
                initPlayer()
            }
        }
    }

    /** --- FUNCTION: TV Remote Previous Channel load action --- **/
    private fun previousKeyEvent(){
        if (linkPosition == 0) {
            showSimpleMessageWithSnackbar("This is First channel")
        } else {
            if (Util.SDK_INT > 23) {
                releasePlayer()
                linkPosition -= 1
                initPlayer()
            }
        }
    }
}


来源: stackexchange

问:
How to use functions like op.add_column and op.alter_column from alembic, but without the whole alembic environment?
I try to use alembic functions but without the whole environement from alembic (ini, env.py, etc). It worked until I wanted to use the op-method-calls like op.add_column and op.alter_column. Then I got always this Error:
NameError: Can't invoke function 'add_column', as the proxy object has not yet been established for the Alembic 'Operations' class.  Try placing this code inside a callable.

I think it has something to do with the setting while the methode "create_module_class_proxy" in the op.py.
How Can I reproduce a normal application of the op.py?

I debugged throw the process and the "create_module_class_proxy" is called with other methods too. Then why doesn`t it work with the add and alter calls?

ContentLicense: CC BY-SA 4.0


问:
When executing a compiled C/C++ file with below code using seccomp and execve, it is exiting with status code 159 and signal 31
I'm trying to execute C/C++ code in a secure environment using Seccomp and Ececve. But, C/C++  code is not being executed while trying with this setup. Please look at the files.

seccomp_rules.c

#include <stdio.h>
#include <seccomp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdbool.h>

#include "seccomp_rules.h"

int c_cpp_seccomp_rules(struct config *_config, bool allow_write_file)
{

    int syscalls_whitelist[] = {SCMP_SYS(read), SCMP_SYS(fstat),
                                SCMP_SYS(mmap), SCMP_SYS(mprotect),
                                SCMP_SYS(munmap), SCMP_SYS(uname),
                                SCMP_SYS(arch_prctl), SCMP_SYS(brk),
                                SCMP_SYS(access), SCMP_SYS(exit_group),
                                SCMP_SYS(close), SCMP_SYS(readlink),
                                SCMP_SYS(sysinfo), SCMP_SYS(write),
                                SCMP_SYS(writev), SCMP_SYS(lseek),
                                SCMP_SYS(clock_gettime), SCMP_SYS(pread64)}; // add extra rule for pread64

    int syscalls_whitelist_length = sizeof(syscalls_whitelist) / sizeof(int);
    scmp_filter_ctx ctx = NULL;

    ctx = seccomp_init(SCMP_ACT_KILL);

    if (!ctx)
    {
        return LOAD_SECCOMP_FAILED;
    }
    for (int i = 0; i < syscalls_whitelist_length; i++)
    {
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, syscalls_whitelist[i], 0) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
    }
    if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(execve), 1, SCMP_A0(SCMP_CMP_EQ, (scmp_datum_t)(_config->exe_path))) != 0)
    {
        return LOAD_SECCOMP_FAILED;
    }
    if (!allow_write_file)
    {
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(open), 1, SCMP_CMP(1, SCMP_CMP_MASKED_EQ, O_WRONLY | O_RDWR, 0)) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(openat), 1, SCMP_CMP(2, SCMP_CMP_MASKED_EQ, O_WRONLY | O_RDWR, 0)) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
    }
    else
    {
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(open), 0) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(dup), 0) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(dup2), 0) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(dup3), 0) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
    }

    if (seccomp_load(ctx) != 0)
    {
        return LOAD_SECCOMP_FAILED;
    }
    seccomp_release(ctx);
    return 0;
}
```
<p><code>main.c</code></p>
<blockquote>
<p>temp.c is a simple C file, temp is the C object file that I'm trying to execute in the project</p>
</blockquote>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <seccomp.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdbool.h>

#include "seccomp_rules.h"

int main()
{

    struct config _config;
    long orig_eax;
    _config.exe_path = "/home/ubuntu/runner/temp";
    _config.args[0] = _config.exe_path;
    _config.args[1] = NULL;
    _config.env[0] = "PATH=/usr/local/bin:/usr/bin:/bin";
    _config.env[1] = "LANG=en_US.UTF-8";
    _config.env[2] = "LANGUAGE=en_US:en";
    _config.env[3] = "LC_ALL=en_US.UTF-8";
    _config.env[4] = NULL;

    pid_t child_pid = fork();

    // pid < 0 shows clone failed
    if (child_pid < 0)
    {
        printf("FORK_FAILED");
    }
    else if (child_pid == 0)
    {
        c_cpp_seccomp_rules(&_config, true);
        execve(_config.exe_path, _config.args, _config.env);
        printf("execve failed\n");
    }
    else if (child_pid > 0)
    {

    }
}
</code>```

seccomp_rules.h

#ifndef SECCOMP_RULES_H
#define SECCOMP_RULES_H
#include <stdbool.h>
#include <sys/types.h>

#define LOAD_SECCOMP_FAILED -1;

struct config
{
    char *exe_path;
    char *args[20];
    char *env[20];
};

int c_cpp_seccomp_rules(struct config *_config, bool allow_write_file);

#endif // SECCOMP_RULES_H
```
<p><code>CMakeLists.txt</code></p>
```cmake_minimum_required(VERSION 2.5)
# set(CMAKE_TRY_COMPILE_TARGET_TYPE "STATIC_LIBRARY")
# SET (CMAKE_C_COMPILER_WORKS 1)
# SET (CMAKE_CXX_COMPILER_WORKS 1)
project(Seccomp)

#set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/output)

set(CMAKE_C_FLAGS "-g -Wall -O3 -std=c99 -pie -fPIC")

file(GLOB SOURCE "./*.c")
add_executable(seccomp.so ${SOURCE})
target_link_libraries(seccomp.so pthread seccomp)

install(FILES output/seccomp.so
    PERMISSIONS OWNER_EXECUTE OWNER_READ
    DESTINATION /usr/lib/runner)
```

Put all these files in a folder and execute these commands.

cmake . &&  make

./output/seccomp.so

Body:
I'm trying to execute C/C++ code in a secure environment using Seccomp and Ececve. But, C/C++  code is not being executed while trying with this setup. Please look at the files.

seccomp_rules.c

#include <stdio.h>
#include <seccomp.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdbool.h>

#include "seccomp_rules.h"

int c_cpp_seccomp_rules(struct config *_config, bool allow_write_file)
{

    int syscalls_whitelist[] = {SCMP_SYS(read), SCMP_SYS(fstat),
                                SCMP_SYS(mmap), SCMP_SYS(mprotect),
                                SCMP_SYS(munmap), SCMP_SYS(uname),
                                SCMP_SYS(arch_prctl), SCMP_SYS(brk),
                                SCMP_SYS(access), SCMP_SYS(exit_group),
                                SCMP_SYS(close), SCMP_SYS(readlink),
                                SCMP_SYS(sysinfo), SCMP_SYS(write),
                                SCMP_SYS(writev), SCMP_SYS(lseek),
                                SCMP_SYS(clock_gettime), SCMP_SYS(pread64)}; // add extra rule for pread64

    int syscalls_whitelist_length = sizeof(syscalls_whitelist) / sizeof(int);
    scmp_filter_ctx ctx = NULL;

    ctx = seccomp_init(SCMP_ACT_KILL);

    if (!ctx)
    {
        return LOAD_SECCOMP_FAILED;
    }
    for (int i = 0; i < syscalls_whitelist_length; i++)
    {
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, syscalls_whitelist[i], 0) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
    }
    if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(execve), 1, SCMP_A0(SCMP_CMP_EQ, (scmp_datum_t)(_config->exe_path))) != 0)
    {
        return LOAD_SECCOMP_FAILED;
    }
    if (!allow_write_file)
    {
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(open), 1, SCMP_CMP(1, SCMP_CMP_MASKED_EQ, O_WRONLY | O_RDWR, 0)) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(openat), 1, SCMP_CMP(2, SCMP_CMP_MASKED_EQ, O_WRONLY | O_RDWR, 0)) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
    }
    else
    {
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(open), 0) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(dup), 0) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(dup2), 0) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
        if (seccomp_rule_add(ctx, SCMP_ACT_ALLOW, SCMP_SYS(dup3), 0) != 0)
        {
            return LOAD_SECCOMP_FAILED;
        }
    }

    if (seccomp_load(ctx) != 0)
    {
        return LOAD_SECCOMP_FAILED;
    }
    seccomp_release(ctx);
    return 0;
}

main.c

temp.c is a simple C file, temp is the C object file that I'm trying to execute in the project

#include <stdio.h>
#include <seccomp.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdbool.h>

#include "seccomp_rules.h"

int main()
{

    struct config _config;
    long orig_eax;
    _config.exe_path = "/home/ubuntu/runner/temp";
    _config.args[0] = _config.exe_path;
    _config.args[1] = NULL;
    _config.env[0] = "PATH=/usr/local/bin:/usr/bin:/bin";
    _config.env[1] = "LANG=en_US.UTF-8";
    _config.env[2] = "LANGUAGE=en_US:en";
    _config.env[3] = "LC_ALL=en_US.UTF-8";
    _config.env[4] = NULL;

    pid_t child_pid = fork();

    // pid < 0 shows clone failed
    if (child_pid < 0)
    {
        printf("FORK_FAILED");
    }
    else if (child_pid == 0)
    {
        c_cpp_seccomp_rules(&_config, true);
        execve(_config.exe_path, _config.args, _config.env);
        printf("execve failed\n");
    }
    else if (child_pid > 0)
    {

    }
}

seccomp_rules.h

#ifndef SECCOMP_RULES_H
#define SECCOMP_RULES_H
#include <stdbool.h>
#include <sys/types.h>

#define LOAD_SECCOMP_FAILED -1;

struct config
{
    char *exe_path;
    char *args[20];
    char *env[20];
};

int c_cpp_seccomp_rules(struct config *_config, bool allow_write_file);

#endif // SECCOMP_RULES_H

CMakeLists.txt

cmake_minimum_required(VERSION 2.5)
# set(CMAKE_TRY_COMPILE_TARGET_TYPE "STATIC_LIBRARY")
# SET (CMAKE_C_COMPILER_WORKS 1)
# SET (CMAKE_CXX_COMPILER_WORKS 1)
project(Seccomp)

#set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/output)

set(CMAKE_C_FLAGS "-g -Wall -O3 -std=c99 -pie -fPIC")

file(GLOB SOURCE "./*.c")
add_executable(seccomp.so ${SOURCE})
target_link_libraries(seccomp.so pthread seccomp)

install(FILES output/seccomp.so
    PERMISSIONS OWNER_EXECUTE OWNER_READ
    DESTINATION /usr/lib/runner)

Put all these files in a folder and execute these commands.

cmake . &&  make

./output/seccomp.so


问:
Salesforce Pub/Sub client in .NET
I would like to subscript to a Salesforce platform event.  I am trying to create a client in C#/.NET for a Salesforce Pub/Sub API.  There are examples in other languages but not in .NET : https://github.com/developerforce/pub-sub-api

I am using the Grpc.Net.Client nuget packages.

```<code>            var topicName = "/event/SomeEvent__e";
            var pubSubEndpoint = "https://api.pubsub.salesforce.com:7443";
            var accessToken = "xxxx";
            var organisationId = "xxxx";
            var instanceUrl = "https://xxxxx.sandbox.my.salesforce.com";

            var credentials = CallCredentials.FromInterceptor((c, m) =>
            {
                m.Add("accesstoken", accessToken);
                m.Add("instanceurl", instanceUrl);
                m.Add("tenantid", organisationId);
                return Task.CompletedTask;
            });

            var options = new GrpcChannelOptions
            {
                Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
            };

            var channel = GrpcChannel.ForAddress(pubSubEndpoint, options);
            var client = new PubSub.PubSubClient(channel);

            var topicRequest = new TopicRequest()
            {
                TopicName = topicName
            };
            var topic = client.GetTopic(topicRequest);
</code>```

I know my credentials are correct because I can use postman to hit the oauth2 endpoint and get a valid access token.  But when I try and call a client method like client.GetTopic, then I get the following error.

Status(StatusCode="PermissionDenied", Detail="An error occurred while getting the metadata for org CORE/prod/00DN0000000c8Hk and topic /event/SomeEvent__e. Ensure the credentials and topic name are correct. rpcId: 21d854fb-17dc-4778-9524-6264bd1a920d")

Am I setting up the credentials object wrong? I cannot find any example of subscribing to a Salesforce Pub/Sub in .NET.

Title: Salesforce Pub/Sub client in .NET

Body:
I would like to subscript to a Salesforce platform event.  I am trying to create a client in C#/.NET for a Salesforce Pub/Sub API.  There are examples in other languages but not in .NET : https://github.com/developerforce/pub-sub-api

I am using the Grpc.Net.Client nuget packages.

            var topicName = "/event/SomeEvent__e";
            var pubSubEndpoint = "https://api.pubsub.salesforce.com:7443";
            var accessToken = "xxxx";
            var organisationId = "xxxx";
            var instanceUrl = "https://xxxxx.sandbox.my.salesforce.com";

            var credentials = CallCredentials.FromInterceptor((c, m) =>
            {
                m.Add("accesstoken", accessToken);
                m.Add("instanceurl", instanceUrl);
                m.Add("tenantid", organisationId);
                return Task.CompletedTask;
            });

            var options = new GrpcChannelOptions
            {
                Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
            };

            var channel = GrpcChannel.ForAddress(pubSubEndpoint, options);
            var client = new PubSub.PubSubClient(channel);

            var topicRequest = new TopicRequest()
            {
                TopicName = topicName
            };
            var topic = client.GetTopic(topicRequest);

I know my credentials are correct because I can use postman to hit the oauth2 endpoint and get a valid access token.  But when I try and call a client method like client.GetTopic, then I get the following error.

Status(StatusCode="PermissionDenied", Detail="An error occurred while getting the metadata for org CORE/prod/00DN0000000c8Hk and topic /event/SomeEvent__e. Ensure the credentials and topic name are correct. rpcId: 21d854fb-17dc-4778-9524-6264bd1a920d")

Am I setting up the credentials object wrong? I cannot find any example of subscribing to a Salesforce Pub/Sub in .NET.


问:
How to get authorization url and get token url for oauth2 from generated code using swagger-codegen
```<code>swagger-codegen generate -i /path/to/api-spec.json -l python -o /output/directory
</code>```

This command will generate a Python client library in the specified output directory.

```<code>from your_api_client import YourAPIClient

# Initialize the client with your API's base URL and OAuth 2.0 credentials
client = YourAPIClient(base_url='https://your-api.com', client_id='your-client-id', client_secret='your-client-secret')

# How to Get the authorization endpoint something like this?
auth_endpoint = client.get_oauth_authorization_endpoint()  # NOT FOUND
</code>```

GithubSample not having any such method where as definition has the url.

```<code>petstore_auth: {
   type: "oauth2",
   authorizationUrl: "https://petstore.swagger.io/oauth/authorize",
   flow: "implicit",
   scopes: {
     read:pets: "read your pets",
     write:pets: "modify pets in your account"
   }
}
</code>```

How to get the URL for authorization and get token url from generated code?

Body:
swagger-codegen generate -i /path/to/api-spec.json -l python -o /output/directory

This command will generate a Python client library in the specified output directory.

from your_api_client import YourAPIClient

# Initialize the client with your API's base URL and OAuth 2.0 credentials
client = YourAPIClient(base_url='https://your-api.com', client_id='your-client-id', client_secret='your-client-secret')

# How to Get the authorization endpoint something like this?
auth_endpoint = client.get_oauth_authorization_endpoint()  # NOT FOUND

GithubSample not having any such method where as definition has the url.

petstore_auth: {
   type: "oauth2",
   authorizationUrl: "https://petstore.swagger.io/oauth/authorize",
   flow: "implicit",
   scopes: {
     read:pets: "read your pets",
     write:pets: "modify pets in your account"
   }
}

How to get the URL for authorization and get token url from generated code?


问:
Symfony: adding a block-prefix for an abstract custom type
I have a custom type that is abstract.
As it seems that leads to it not getting its own block_prefix in the hierarchy.
So I thought I would put that into configureOptions.
But in the deriving classes I do occassionally also have to define configureOptions which then again leads to either overwriting the parent method which defeats the purpose. Or if I call it explicitly
with parent::configureOptions the system will put the custom prefix above (in the sense of "higher priority") the automatically generated prefix of the implementing class which I obviously do not want.

Is there a solution to this problem that is not "make the parent class not abstract"?
I say that because if possible I don't want to loose the enforcement of the contract given by the abstract parent-class.

EDIT: I realized that it was a false assumption I made that making the base class non-abstract would lead to the addition of the class name as block-prefix.


问:
How to prevent displaying download oropen external link icons on specific links
I use js to automatically add classes: 'new-window' and 'download' automatically to links in the D2l/Brightspace LMS.

```<code>$('a[target=_blank]').addClass('new-window');
$("a").filter(function () {
 return $(this).attr("href").match(/\.  (pdf|doc|docx|ppt|pptx|xls|xlxs|epub|odt|odp|ods|txt|rtf)$/i);
}).addClass('download');

/** Links JavaScript **/
/* Check for links in document */
var links = document.querySelectorAll("a");
/* Create index for download links unique id*/
var downloadIndex = 0;
/* Create index for new window links unique id*/
var newWindowIndex = 0;
/* Check links on page */
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
   /* Creating a span to wrap the screen-reader text */
   var srTxtWrapper = document.createElement("span");
   /* Add class .sr-only to screen-reader span */
   srTxtWrapper.classList.add("sr-only");

   if (links[linkIndex].classList.contains("download")) {
      /* Add download attribute */
      links[linkIndex].setAttribute("download", "");
      /* Add unique id to download link */
      links[linkIndex].setAttribute("id", "download-file-" + downloadIndex);
      /* Add title attribute saying download file */
      links[linkIndex].setAttribute("title", "download bestand");
      /* Add data-toggle tooltip data attribute */
      links[linkIndex].setAttribute("data-toggle", "tooltip");
      /* Creating the screen-reader text */
      var srTxt = document.createTextNode("(deze link downloadt een bestand)");
      /* Adding the screen-reader text to the span*/
      srTxtWrapper.appendChild(srTxt);
      links[linkIndex].appendChild(srTxtWrapper);
      /* Increase downloadIndex by one for next download link */
      downloadIndex++;
   }
   else if (links[linkIndex].classList.contains("new-window")) {
      /* Add target _blank attribute for link to open in new window */
      links[linkIndex].setAttribute("target", "_blank");
      /* Add unique id to new window link */
      links[linkIndex].setAttribute("id", "new-window" + newWindowIndex);
      /* Add title attribute saying link opens in new window */
      links[linkIndex].setAttribute("title", "open in nieuw venster/tab");
      /* Add data-toggle tooltip data attribute */
      links[linkIndex].setAttribute("data-toggle", "tooltip");
      /* Creating the screen-reader text */
      var srTxt = document.createTextNode("(deze link opent in een nieuw venster/tab)");
      /* Adding the screen-reader text to the span*/
      srTxtWrapper.appendChild(srTxt);
      links[linkIndex].appendChild(srTxtWrapper);
      /* Increase newWindowIndex by one for next newWindow link */
      newWindowIndex++;
   }
}
</code>```

I use Font Awesome icons and the pseudoselector 'after' for this process.

```<code>a.new-window::after, a.download::after {
  -webkit-font-smoothing: antialiased;
  display: inline-block;
  font-style: normal;
  font-variant: normal;
  text-rendering: auto;
  line-height: 1;
  font-family: "Font Awesome 6 Free";
  font-weight: 900;
  margin-left: 0.35rem;
}

a.new-window::after {
  content: "\f08e";
}

a.download::after {
  content: "\f019";
}
</code>```

However, when I set the target to "_self" to link to places within the LMS an (external link) icon is also added after the link and the link also behaves as set to target="_blank" and therefore opens in a new tab. When I inspect the element, it also shows that the HTML is constructed as:

```<code><a target="_blank" href="/d2l/common/dialogs/quickLink/quickLink.d2l?ou=9767" class="new-window" id="new-window0" title="open in nieuw venster/tab" data-toggle="tooltip">Het AlfaBet van de aCute zorg<span class="sr-only">(deze link opent in een nieuw venster/tab)</span></a>
</code>```

The only way to prevent opening the link in a new tab and displaying the icon is to set the target to "_top".
I have no idea how to prevent this phenomenon. I tried to exclude this specific domain with:

```<code>a[href^="https://leren.windesheim.nl/d2l*"]::after
{display: none !important;}
</code>```

But this doesn't seem to work. Any pointers on what's causing this?

Body:
I use js to automatically add classes: 'new-window' and 'download' automatically to links in the D2l/Brightspace LMS.

$('a[target=_blank]').addClass('new-window');
$("a").filter(function () {
 return $(this).attr("href").match(/\.  (pdf|doc|docx|ppt|pptx|xls|xlxs|epub|odt|odp|ods|txt|rtf)$/i);
}).addClass('download');

/** Links JavaScript **/
/* Check for links in document */
var links = document.querySelectorAll("a");
/* Create index for download links unique id*/
var downloadIndex = 0;
/* Create index for new window links unique id*/
var newWindowIndex = 0;
/* Check links on page */
for (var linkIndex = 0; linkIndex < links.length; linkIndex++) {
   /* Creating a span to wrap the screen-reader text */
   var srTxtWrapper = document.createElement("span");
   /* Add class .sr-only to screen-reader span */
   srTxtWrapper.classList.add("sr-only");

   if (links[linkIndex].classList.contains("download")) {
      /* Add download attribute */
      links[linkIndex].setAttribute("download", "");
      /* Add unique id to download link */
      links[linkIndex].setAttribute("id", "download-file-" + downloadIndex);
      /* Add title attribute saying download file */
      links[linkIndex].setAttribute("title", "download bestand");
      /* Add data-toggle tooltip data attribute */
      links[linkIndex].setAttribute("data-toggle", "tooltip");
      /* Creating the screen-reader text */
      var srTxt = document.createTextNode("(deze link downloadt een bestand)");
      /* Adding the screen-reader text to the span*/
      srTxtWrapper.appendChild(srTxt);
      links[linkIndex].appendChild(srTxtWrapper);
      /* Increase downloadIndex by one for next download link */
      downloadIndex++;
   }
   else if (links[linkIndex].classList.contains("new-window")) {
      /* Add target _blank attribute for link to open in new window */
      links[linkIndex].setAttribute("target", "_blank");
      /* Add unique id to new window link */
      links[linkIndex].setAttribute("id", "new-window" + newWindowIndex);
      /* Add title attribute saying link opens in new window */
      links[linkIndex].setAttribute("title", "open in nieuw venster/tab");
      /* Add data-toggle tooltip data attribute */
      links[linkIndex].setAttribute("data-toggle", "tooltip");
      /* Creating the screen-reader text */
      var srTxt = document.createTextNode("(deze link opent in een nieuw venster/tab)");
      /* Adding the screen-reader text to the span*/
      srTxtWrapper.appendChild(srTxt);
      links[linkIndex].appendChild(srTxtWrapper);
      /* Increase newWindowIndex by one for next newWindow link */
      newWindowIndex++;
   }
}

I use Font Awesome icons and the pseudoselector 'after' for this process.

a.new-window::after, a.download::after {
  -webkit-font-smoothing: antialiased;
  display: inline-block;
  font-style: normal;
  font-variant: normal;
  text-rendering: auto;
  line-height: 1;
  font-family: "Font Awesome 6 Free";
  font-weight: 900;
  margin-left: 0.35rem;
}

a.new-window::after {
  content: "\f08e";
}

a.download::after {
  content: "\f019";
}

However, when I set the target to "_self" to link to places within the LMS an (external link) icon is also added after the link and the link also behaves as set to target="_blank" and therefore opens in a new tab. When I inspect the element, it also shows that the HTML is constructed as:

Het AlfaBet van de aCute zorg(deze link opent in een nieuw venster/tab)

The only way to prevent opening the link in a new tab and displaying the icon is to set the target to "_top".
I have no idea how to prevent this phenomenon. I tried to exclude this specific domain with:

a[href^="https://leren.windesheim.nl/d2l*"]::after
{display: none !important;}

But this doesn't seem to work. Any pointers on what's causing this?


问:
How to run an acceptance test in Codeception in Opera Browser?
When I run the test, Opera opens, but the test does not run and an error falls into the console

```<code>[Facebook\WebDriver\Exception\SessionNotCreatedException] Unable to create session from {
 "desiredCapabilities": {
"browserName": "opera"
},
"capabilities": {
"firstMatch": [
  {
    "browserName": "opera"
  }
]
  }
}

Driver info: driver.version: unknown
</code>```

I start the server with this command:

```<code>java "-Dwebdriver.opera.driver=C:\Users\user\Desktop\Auto\qa-tests\Codeception\operadriver.exe" -jar "C:\Users\user\Desktop\Auto\qa-tests\Codeception\selenium-server-standalone-3.14.0.jar"
</code>```

My acceptance.suite.yaml

```<code>  opera:
modules:
  config:
    PhpBrowser:
      url: 'https://sample.com/'
    WebDriver:
      url: 'https://samlpe.com/'
      window_size: 1900x1080 # for fullscreen shots
      port: 17570
      browser: opera # 'chrome' or 'firefox'   java "-Dwebdriver.opera.driver=C:\Users\user\Desktop\Auto\qa-tests\Codeception\operadriver.exe" -jar "C:\Users\user\Desktop\Auto\qa-tests\Codeception\selenium-server-standalone-3.14.0.jar" -port 17570 - для MicrosoftEdge
      #capabilities:
      args: [ '--no-sandbox' ]
</code>```

Body:
When I run the test, Opera opens, but the test does not run and an error falls into the console

[Facebook\WebDriver\Exception\SessionNotCreatedException] Unable to create session from {
 "desiredCapabilities": {
"browserName": "opera"
},
"capabilities": {
"firstMatch": [
  {
    "browserName": "opera"
  }
]
  }
}

Driver info: driver.version: unknown

I start the server with this command:

java "-Dwebdriver.opera.driver=C:\Users\user\Desktop\Auto\qa-tests\Codeception\operadriver.exe" -jar "C:\Users\user\Desktop\Auto\qa-tests\Codeception\selenium-server-standalone-3.14.0.jar"

My acceptance.suite.yaml

  opera:
modules:
  config:
    PhpBrowser:
      url: 'https://sample.com/'
    WebDriver:
      url: 'https://samlpe.com/'
      window_size: 1900x1080 # for fullscreen shots
      port: 17570
      browser: opera # 'chrome' or 'firefox'   java "-Dwebdriver.opera.driver=C:\Users\user\Desktop\Auto\qa-tests\Codeception\operadriver.exe" -jar "C:\Users\user\Desktop\Auto\qa-tests\Codeception\selenium-server-standalone-3.14.0.jar" -port 17570 - для MicrosoftEdge
      #capabilities:
      args: [ '--no-sandbox' ]


问:
Cannot read avro file which contains whitespace in columns name using Spark-Avro 2.12:3.2.0
After migrating to Spark 3.2.0 i had to upgrade the external package of spark-avro to spark-avro 2.12:3.2.0.

After this migration i was unable to read any avro file that contains spaces in their column names.

The errors occurs on the read method below so i'm not able to rename the column name using .alias() or .withColumnRenamed()

```<code>spark.read.format('avro').load(
    'hdfs:///avrofile')
</code>```

Here is an extract of the error logs:

```<code>pyspark.sql.utils.AnalysisException: Column name "Test Data" contains invalid character(s).Please use alias to rename it.
</code>```

Note that i don't have this issue using spark-avro version below 2.12:3.1.0 however due to imcopability issues i'm not able to use to write avro files using spark-avro versions whose Spark version are below 3.2.0.

Body:
After migrating to Spark 3.2.0 i had to upgrade the external package of spark-avro to spark-avro 2.12:3.2.0.

After this migration i was unable to read any avro file that contains spaces in their column names.

The errors occurs on the read method below so i'm not able to rename the column name using .alias() or .withColumnRenamed()

spark.read.format('avro').load(
    'hdfs:///avrofile')

Here is an extract of the error logs:

pyspark.sql.utils.AnalysisException: Column name "Test Data" contains invalid character(s).Please use alias to rename it.

Note that i don't have this issue using spark-avro version below 2.12:3.1.0 however due to imcopability issues i'm not able to use to write avro files using spark-avro versions whose Spark version are below 3.2.0.


问:
Change regionmap chart colouring option
I have some VBA code to insert a RegionMap chart in excel. The code then changes the range of the series' data (I did this because the chart entry directly for the region I need, for some reason was not working properly). I also have the The code to change the chart title. All these work properly. However I cannot find the code to change the way that countries are coloured. By default they are coloured based on series' values, but I want to colour them based on secondary categories. When I try to record a macro, I get an empty record. Any ideas?

My code so far

```<code>    Range("A9:A13,C9:C13").Select
    Range("C9").Activate
    ActiveSheet.Shapes.AddChart2(494, xlRegionMap).Select
    ActiveChart.FullSeriesCollection(1).Values = "=Heatmap!$B$9:$B$13"
    ActiveChart.ChartTitle.Select
    Selection.Caption = "Top Keywords"
</code>```

This is the data

This is what I get

This is what I need

Title: Change regionmap chart colouring option

Body:
I have some VBA code to insert a RegionMap chart in excel. The code then changes the range of the series' data (I did this because the chart entry directly for the region I need, for some reason was not working properly). I also have the The code to change the chart title. All these work properly. However I cannot find the code to change the way that countries are coloured. By default they are coloured based on series' values, but I want to colour them based on secondary categories. When I try to record a macro, I get an empty record. Any ideas?

My code so far

    Range("A9:A13,C9:C13").Select
    Range("C9").Activate
    ActiveSheet.Shapes.AddChart2(494, xlRegionMap).Select
    ActiveChart.FullSeriesCollection(1).Values = "=Heatmap!$B$9:$B$13"
    ActiveChart.ChartTitle.Select
    Selection.Caption = "Top Keywords"

This is the data

This is what I get

This is what I need


问:
Cannot access localhost on Chrome: Failed to load resource: the server responded with a status of 404 (Not Found)
I am trying to access an application on localhost:8080.

I can access it on edge, but not on Chrome.

On chrome it shows the following error:

Failed to load resource: the server responded with a status of 404 (Not Found)

I've already cleared the history and resetted the configurations of chrome to its defaults.

As suggested in https://stackoverflow.com/questions/33524826/localhost-not-working-in-chrome-127-0-0-1-does-work#:~:text=What%20you%20can%20do%20is,site%20it%20will%20be%20working:
I've also cleared host cache in chrome://net-internals/#dns.
Besides that I went to chrome://net-internals/#hsts and under "Delete domain", I've typed localhost and deleted it.

Any help on this would be appreciated.


问:
How to start a startForegroundService using WorkManager
Hi due to issues with startForegroundService not able to run in the background on certain android version. I am trying to startForegroundService using a WorkManager but unable to get it to work. this is what I tried so far.

Forground service that needs to start

```<code>  ContextCompat.startForegroundService(context, CarInfoProcessingService.createIntent(context = applicationContext,
                pushMsgData = message.data))
</code>```

class that starts the foreground service

```<code>class BackupWorker(private val context: Context,  workerParams: WorkerParameters,private val message: RemoteMessage) :
    Worker(context, workerParams) {
    override fun doWork(): Result {
        //call methods to perform background task
        ContextCompat.startForegroundService(context, CarInfoProcessingService.createIntent(context = applicationContext,
            pushMsgData = message.data))
        return Result.success()
    }

    companion object {
        private const val TAG = "BackupWorker"
    }
}
</code>```

how I am starting the workManager

```<code>   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val request =
                OneTimeWorkRequest.Builder(BackupWorker::class.java).addTag("BACKUP_WORKER_TAG")
                    .build()
            WorkManager.getInstance(context).enqueue(request)
        }
</code>```

Issues I have

The above code does not trigger CarInfoProcessingService.

Another question I had was for class BackupWorker I have a parameter message but I am never passing that any where,

Thank you for your help in advance

R

Body:
Hi due to issues with startForegroundService not able to run in the background on certain android version. I am trying to startForegroundService using a WorkManager but unable to get it to work. this is what I tried so far.

Forground service that needs to start

  ContextCompat.startForegroundService(context, CarInfoProcessingService.createIntent(context = applicationContext,
                pushMsgData = message.data))

class that starts the foreground service

class BackupWorker(private val context: Context,  workerParams: WorkerParameters,private val message: RemoteMessage) :
    Worker(context, workerParams) {
    override fun doWork(): Result {
        //call methods to perform background task
        ContextCompat.startForegroundService(context, CarInfoProcessingService.createIntent(context = applicationContext,
            pushMsgData = message.data))
        return Result.success()
    }

    companion object {
        private const val TAG = "BackupWorker"
    }
}

how I am starting the workManager

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            val request =
                OneTimeWorkRequest.Builder(BackupWorker::class.java).addTag("BACKUP_WORKER_TAG")
                    .build()
            WorkManager.getInstance(context).enqueue(request)
        }

Issues I have

The above code does not trigger CarInfoProcessingService.

Another question I had was for class BackupWorker I have a parameter message but I am never passing that any where,

Thank you for your help in advance

R


问:
NextJS's Backend service not working when deploying to Docker
So I have made a NextJS App as a frontend and backend server, it works fine when running it locally (by running yarn dev or yarn build then yarn start), but not working on Docker (using the content of Dockerfile from the official Github project). Found out that the whole backend server is not working at all (knew it because I tried to manually access the API outside from the frontend and it all returned NextJS's 404 Not Found Page), what did I do wrong?

Here's the next.config.js:

module.exports = {
  output: 'standalone',
  async redirects() {
    return [
      {
        source: '/',
        destination: `/${process.env.COUNTRY_CODE}/login`,
        permanent: false,
        basePath: false,
      },
      {
        source: '/login',
        destination: `/${process.env.COUNTRY_CODE}/login`,
        permanent: false,
        basePath: false,
      },
    ]
  },
  basePath: `/${process.env.COUNTRY_CODE}`,
  trailingSlash: true,
  env: {
    CRMNX_COUNTRY_CODE: process.env.COUNTRY_CODE,
    NEXTAUTH_URL: process.env.NEXTAUTH_URL,
    NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,
  }
};

```
<p>my <code>package.json</code>:</p>
<pre class="lang-json prettyprint-override"><code>{
  "name": "myapp",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "node server.js",
    "watch": "nodemon server.js",
    "build": "next build",
    "start": "NODE_ENV=production node server.js"
  },
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@headlessui/react": "^1.6.4",
    "@heroicons/react": "^1.0.6",
    "@mui/icons-material": "^5.10.9",
    "@mui/material": "^5.10.12",
    "@mui/x-date-pickers": "^5.0.8",
    "axios": "^0.27.2",
    "bootstrap": "^5.2.2",
    "cookie-session": "^2.0.0",
    "csurf": "^1.11.0",
    "date-format": "^4.0.14",
    "dayjs": "^1.11.6",
    "express": "^4.18.2",
    "express-rate-limit": "^6.4.0",
    "express-session": "^1.17.3",
    "formik": "^2.2.9",
    "iron-session": "^6.3.1",
    "jose": "^4.11.1",
    "jsonwebtoken": "^8.5.1",
    "libphonenumber-js": "^1.10.6",
    "moment": "^2.29.4",
    "mysql2": "^2.3.3",
    "next": "^13.0.6",
    "next-auth": "^4.17.0",
    "node-cache": "^5.1.2",
    "pure-react-carousel": "^1.30.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-device-detect": "^2.2.2",
    "react-hook-form": "^7.31.3",
    "react-phone-input-2": "^2.15.1",
    "sequelize": "^6.25.3",
    "sweetalert2": "^11.4.8",
    "yup": "^0.32.11"
  },
  "devDependencies": {
    "@babel/preset-react": "^7.18.6",
    "autoprefixer": "^10.4.7",
    "cors": "^2.8.5",
    "dotenv": "^16.0.1",
    "eslint": "8.20.0",
    "eslint-config-next": "^13.0.6",
    "nodemon": "^2.0.20",
    "postcss": "^8.4.14",
    "prettier": "2.7.1",
    "react-select": "^5.5.6",
    "sequelize-cli": "^6.5.2",
    "tailwindcss": "^3.0.24"
  }
}
</code>```

and my server.js:

```<code>const next = require("next");
require('dotenv').config()

const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== "production";
const hostname = process.env.APP_HOSTNAME || "localhost";
const app = next({
  dev,
  hostname,
  port,
});
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const csrf = require("csurf");
  const cookieSession = require("cookie-session");

  const server = express();
  server.disable("x-powered-by");
  server.use(express.json());
  server.use(express.urlencoded({ extended: true }));

  server.use(
    cookieSession({
      name: "myapp.sid",
      keys: [process.env.APP_KEY],
      maxAge: 24 * 60 * 60 * 1000,
    })
  );

  const rateLimit = require("express-rate-limit");
  const limiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 100,
  });
  // server.use('/api', limiter)

  const router = require("./server/route");
  server.use(`/${process.env.COUNTRY_CODE}/api`, router);

  server.all("*", (req, res) => {
    return handle(req, res);
  });

  server.listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});
</code>```

Body:
So I have made a NextJS App as a frontend and backend server, it works fine when running it locally (by running yarn dev or yarn build then yarn start), but not working on Docker (using the content of Dockerfile from the official Github project). Found out that the whole backend server is not working at all (knew it because I tried to manually access the API outside from the frontend and it all returned NextJS's 404 Not Found Page), what did I do wrong?

Here's the next.config.js:

module.exports = {
  output: 'standalone',
  async redirects() {
    return [
      {
        source: '/',
        destination: `/${process.env.COUNTRY_CODE}/login`,
        permanent: false,
        basePath: false,
      },
      {
        source: '/login',
        destination: `/${process.env.COUNTRY_CODE}/login`,
        permanent: false,
        basePath: false,
      },
    ]
  },
  basePath: `/${process.env.COUNTRY_CODE}`,
  trailingSlash: true,
  env: {
    CRMNX_COUNTRY_CODE: process.env.COUNTRY_CODE,
    NEXTAUTH_URL: process.env.NEXTAUTH_URL,
    NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,
  }
};

my package.json:

{
  "name": "myapp",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "node server.js",
    "watch": "nodemon server.js",
    "build": "next build",
    "start": "NODE_ENV=production node server.js"
  },
  "dependencies": {
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@headlessui/react": "^1.6.4",
    "@heroicons/react": "^1.0.6",
    "@mui/icons-material": "^5.10.9",
    "@mui/material": "^5.10.12",
    "@mui/x-date-pickers": "^5.0.8",
    "axios": "^0.27.2",
    "bootstrap": "^5.2.2",
    "cookie-session": "^2.0.0",
    "csurf": "^1.11.0",
    "date-format": "^4.0.14",
    "dayjs": "^1.11.6",
    "express": "^4.18.2",
    "express-rate-limit": "^6.4.0",
    "express-session": "^1.17.3",
    "formik": "^2.2.9",
    "iron-session": "^6.3.1",
    "jose": "^4.11.1",
    "jsonwebtoken": "^8.5.1",
    "libphonenumber-js": "^1.10.6",
    "moment": "^2.29.4",
    "mysql2": "^2.3.3",
    "next": "^13.0.6",
    "next-auth": "^4.17.0",
    "node-cache": "^5.1.2",
    "pure-react-carousel": "^1.30.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-device-detect": "^2.2.2",
    "react-hook-form": "^7.31.3",
    "react-phone-input-2": "^2.15.1",
    "sequelize": "^6.25.3",
    "sweetalert2": "^11.4.8",
    "yup": "^0.32.11"
  },
  "devDependencies": {
    "@babel/preset-react": "^7.18.6",
    "autoprefixer": "^10.4.7",
    "cors": "^2.8.5",
    "dotenv": "^16.0.1",
    "eslint": "8.20.0",
    "eslint-config-next": "^13.0.6",
    "nodemon": "^2.0.20",
    "postcss": "^8.4.14",
    "prettier": "2.7.1",
    "react-select": "^5.5.6",
    "sequelize-cli": "^6.5.2",
    "tailwindcss": "^3.0.24"
  }
}

and my server.js:

const next = require("next");
require('dotenv').config()

const port = process.env.PORT || 3000;
const dev = process.env.NODE_ENV !== "production";
const hostname = process.env.APP_HOSTNAME || "localhost";
const app = next({
  dev,
  hostname,
  port,
});
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const csrf = require("csurf");
  const cookieSession = require("cookie-session");

  const server = express();
  server.disable("x-powered-by");
  server.use(express.json());
  server.use(express.urlencoded({ extended: true }));

  server.use(
    cookieSession({
      name: "myapp.sid",
      keys: [process.env.APP_KEY],
      maxAge: 24 * 60 * 60 * 1000,
    })
  );

  const rateLimit = require("express-rate-limit");
  const limiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 100,
  });
  // server.use('/api', limiter)

  const router = require("./server/route");
  server.use(`/${process.env.COUNTRY_CODE}/api`, router);

  server.all("*", (req, res) => {
    return handle(req, res);
  });

  server.listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});


问:
How to timing a python funcion in loop using decorator and having partial timings?
I want to temporize some Python function in a loop. Starting from a simple timing decorator as:

```<code>def timer_func(func):
  def wrap_func(*args, **kwargs):
    t1 = time()
    result = func(*args, **kwargs)
    t2 = time()
    return result
return wrap_func
</code>```

Since my functions are in a loop, I need to add a partial timing to a global timing using different store variables. Something like that:

```<code>def timer_func(func, global_timer):
  def wrap_func(*args, **kwargs):
    t1 = time()
    result = func(*args, **kwargs)
    t2 = time()
    global_timer = global_timer + (t2 - t1)
    return result, global_timer
return wrap_func
</code>```

In such manner, I could call my function in a loop passing the global store variable to a decorator:

```<code>for i in range(1,10):

   @timer_func(global_timer_func1)
   func1()

   @timer_func(global_timer_func2)
   func2()

print(global_timer_func1)
print(global_timer_func2)
</code>```

Which is the best way to do that? Thanks.

Body:
I want to temporize some Python function in a loop. Starting from a simple timing decorator as:

def timer_func(func):
  def wrap_func(*args, **kwargs):
    t1 = time()
    result = func(*args, **kwargs)
    t2 = time()
    return result
return wrap_func

Since my functions are in a loop, I need to add a partial timing to a global timing using different store variables. Something like that:

def timer_func(func, global_timer):
  def wrap_func(*args, **kwargs):
    t1 = time()
    result = func(*args, **kwargs)
    t2 = time()
    global_timer = global_timer + (t2 - t1)
    return result, global_timer
return wrap_func

In such manner, I could call my function in a loop passing the global store variable to a decorator:

for i in range(1,10):

   @timer_func(global_timer_func1)
   func1()

   @timer_func(global_timer_func2)
   func2()

print(global_timer_func1)
print(global_timer_func2)

Which is the best way to do that? Thanks.


问:
How to make rapidjson headers accessible in all C++ project subdirectories using CMakeLists.txt?
I am trying to make #include <rapidjson/document.h> and other rapidjson headers available from all directories inside a C++ project. Rapidjson was installed successfully using vcpkg.

The project structure is as follows:

```<code>/root/
  + CMakeLists.txt
  + CMakePresets.json
  + apps/
      + CMakeLists.txt
      + main.cpp
  + cpp-library/
      + CMakeLists.txt
      + src/
          + testClass1.cpp
          + testClass2.cpp
          + ...
      + include/
          + testClass2.h
          + testClass2.h
          + ...
</code>```

/root/CMakeLists.txt:

```<code>    cmake_minimum_required(VERSION 3.11-3.18)

    set(VCPKG_TARGET_TRIPLET "x64-windows" CACHE STRING "")
    find_package(Rapidjson CONFIG REQUIRED)

    project(
        AngioDiabetesRegulation
        VERSION 0.1
        DESCRIPTION "Small CMake example built with VSCode")

    include_directories(C:/Aljosa/Development/Unity-Github/vcpkg/installed/x64-windows/include)
    # Rapidjson_INCLUDE_DIRS loaded with find_package(Rapidjson) - checked that it loads correctly
    # this is the same as C:/Aljosa/Development/Unity-Github/vcpkg/installed/x64-windows/include
    include_directories(${Rapidjson_INCLUDE_DIRS})

    add_subdirectory(cpp-library)
    add_subdirectory(apps)
</code>```

/apps/CMakeLists.txt

```<code>    cmake_minimum_required(VERSION 3.11-3.18)

    project(main)

    add_executable(main main.cpp)

    #find_package(Rapidjson CONFIG REQUIRED)
    #include_directories(${Rapidjson_INCLUDE_DIRS})
    #target_link_libraries(main PRIVATE cpp-library ${Rapidjson_LIBRARIES} rapidjson)
    target_link_libraries(main PRIVATE cpp-library)

    target_compile_features(main PUBLIC cxx_std_20)
</code>```

/cpp-library/CMakeLists.txt

```<code>    cmake_minimum_required(VERSION 3.11-3.18)
    set(VCPKG_TARGET_TRIPLET "x64-windows" CACHE STRING "")

    project(cpp-library)

    #include_directories(C:/Aljosa/Development/Unity-Github/vcpkg/installed/x64-windows/include)
    #find_package(RapidJSON REQUIRED)
    #include_directories(C:/Aljosa/Development/Unity-Github/vcpkg/installed/x64-   windows/include/rapidjson)

    add_library(cpp-library
        src/testClass1.cpp
        src/testClass2.cpp
    )

    # find_package(Rapidjson CONFIG REQUIRED)
    # include_directories(${Rapidjson_INCLUDE_DIRS}) # is the same as below statement
    # include_directories(C:/Aljosa/Development/Unity-Github/AngioDiabetesRegulation/rapidjson)

    # PUBLIC needed to make both /include/*.h and /src/*.cpp available elsewhere in project
    target_include_directories(${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/include)

    # Tell compiler to use C++20 features. The code doesn't actually use any of them.
    target_compile_features(cpp-library PUBLIC cxx_std_20)
</code>```

Rapidjson headers CAN be accessed in the following directories:

/root/apps (main.cpp) without specifying any include_directories or linking any libraries in /apps/CMakeLists.txt

/root/cpp-library/src (testClass1.cpp and testClass2.cpp)

Rapidjson headers cannot be accessed in /root/cpp-library/include (testClass1.h and testClass2.h) even after specifically including the path to rapidjson's includes in the /root/cpp-library/CMakeLists.txt.

What should I do to make rapidjson headers accessible in root/cpp-library/include (that contains .h files) also?

EDIT #1: I am guessing that the /root/cpp-library/include/*.h files cannot access rapidjson, because they are not included in CMakeLists to the CMakeLists project. If you look at /root/cpp-library/CMakeLists.txt you can only see that only .cpp classes are added to the "project", whereas .h files are not included. Could that be the case?

Exact error: cannot open source file rapidjson/document.h (when trying to include #include <rapidjson/document.h> into testClass1.h or testClass2.h). Note that the above include works fine in testClass1.cpp and testClass2.cpp.

EDIT #2 I tried adding "include/testClass1.h" into the add_library function of /root/cpp-library/CMakeLists.txt, which resolved the error - rapidjson/document.h is now also found in testClass1.h. But I am wondering, is that good practice to add both .cpp and .h files into the add_library function?

The working /root/cpp-library/CMakeLists.txt then looks like:

```<code>cmake_minimum_required(VERSION 3.11-3.18)
set(VCPKG_TARGET_TRIPLET "x64-windows" CACHE STRING "")

project(cpp-library)

add_library(cpp-library
    src/testClass1.cpp
    src/testClass2.cpp
    "include/testClass1.h"
    "include/testClass2.h"
)

target_include_directories(${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/include)

target_compile_features(cpp-library PUBLIC cxx_std_20)
</code>```

I have tried to debug the issue for the past two days, following numerous StackOverflow suggestions, but with no success.

Some of the reviewed topics:

Make all files in a folder accessible to all projects (subdirectories)

How To Configure CMakeLists.txt To Make C++ Project?

Body:
I am trying to make #include <rapidjson/document.h> and other rapidjson headers available from all directories inside a C++ project. Rapidjson was installed successfully using vcpkg.

The project structure is as follows:

/root/
  + CMakeLists.txt
  + CMakePresets.json
  + apps/
      + CMakeLists.txt
      + main.cpp
  + cpp-library/
      + CMakeLists.txt
      + src/
          + testClass1.cpp
          + testClass2.cpp
          + ...
      + include/
          + testClass2.h
          + testClass2.h
          + ...

/root/CMakeLists.txt:

    cmake_minimum_required(VERSION 3.11-3.18)

    set(VCPKG_TARGET_TRIPLET "x64-windows" CACHE STRING "")
    find_package(Rapidjson CONFIG REQUIRED)

    project(
        AngioDiabetesRegulation
        VERSION 0.1
        DESCRIPTION "Small CMake example built with VSCode")

    include_directories(C:/Aljosa/Development/Unity-Github/vcpkg/installed/x64-windows/include)
    # Rapidjson_INCLUDE_DIRS loaded with find_package(Rapidjson) - checked that it loads correctly
    # this is the same as C:/Aljosa/Development/Unity-Github/vcpkg/installed/x64-windows/include
    include_directories(${Rapidjson_INCLUDE_DIRS})

    add_subdirectory(cpp-library)
    add_subdirectory(apps)

/apps/CMakeLists.txt

    cmake_minimum_required(VERSION 3.11-3.18)

    project(main)

    add_executable(main main.cpp)

    #find_package(Rapidjson CONFIG REQUIRED)
    #include_directories(${Rapidjson_INCLUDE_DIRS})
    #target_link_libraries(main PRIVATE cpp-library ${Rapidjson_LIBRARIES} rapidjson)
    target_link_libraries(main PRIVATE cpp-library)

    target_compile_features(main PUBLIC cxx_std_20)

/cpp-library/CMakeLists.txt

    cmake_minimum_required(VERSION 3.11-3.18)
    set(VCPKG_TARGET_TRIPLET "x64-windows" CACHE STRING "")

    project(cpp-library)

    #include_directories(C:/Aljosa/Development/Unity-Github/vcpkg/installed/x64-windows/include)
    #find_package(RapidJSON REQUIRED)
    #include_directories(C:/Aljosa/Development/Unity-Github/vcpkg/installed/x64-   windows/include/rapidjson)

    add_library(cpp-library
        src/testClass1.cpp
        src/testClass2.cpp
    )

    # find_package(Rapidjson CONFIG REQUIRED)
    # include_directories(${Rapidjson_INCLUDE_DIRS}) # is the same as below statement
    # include_directories(C:/Aljosa/Development/Unity-Github/AngioDiabetesRegulation/rapidjson)

    # PUBLIC needed to make both /include/*.h and /src/*.cpp available elsewhere in project
    target_include_directories(${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/include)

    # Tell compiler to use C++20 features. The code doesn't actually use any of them.
    target_compile_features(cpp-library PUBLIC cxx_std_20)

Rapidjson headers CAN be accessed in the following directories:

/root/apps (main.cpp) without specifying any include_directories or linking any libraries in /apps/CMakeLists.txt

/root/cpp-library/src (testClass1.cpp and testClass2.cpp)

Rapidjson headers cannot be accessed in /root/cpp-library/include (testClass1.h and testClass2.h) even after specifically including the path to rapidjson's includes in the /root/cpp-library/CMakeLists.txt.

What should I do to make rapidjson headers accessible in root/cpp-library/include (that contains .h files) also?

EDIT #1: I am guessing that the /root/cpp-library/include/*.h files cannot access rapidjson, because they are not included in CMakeLists to the CMakeLists project. If you look at /root/cpp-library/CMakeLists.txt you can only see that only .cpp classes are added to the "project", whereas .h files are not included. Could that be the case?

Exact error: cannot open source file rapidjson/document.h (when trying to include #include <rapidjson/document.h> into testClass1.h or testClass2.h). Note that the above include works fine in testClass1.cpp and testClass2.cpp.

EDIT #2 I tried adding "include/testClass1.h" into the add_library function of /root/cpp-library/CMakeLists.txt, which resolved the error - rapidjson/document.h is now also found in testClass1.h. But I am wondering, is that good practice to add both .cpp and .h files into the add_library function?

The working /root/cpp-library/CMakeLists.txt then looks like:

cmake_minimum_required(VERSION 3.11-3.18)
set(VCPKG_TARGET_TRIPLET "x64-windows" CACHE STRING "")

project(cpp-library)

add_library(cpp-library
    src/testClass1.cpp
    src/testClass2.cpp
    "include/testClass1.h"
    "include/testClass2.h"
)

target_include_directories(${PROJECT_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/include)

target_compile_features(cpp-library PUBLIC cxx_std_20)

I have tried to debug the issue for the past two days, following numerous StackOverflow suggestions, but with no success.

Some of the reviewed topics:

Make all files in a folder accessible to all projects (subdirectories)

How To Configure CMakeLists.txt To Make C++ Project?


问:
FFT on vector of vectors
I am trying to apply an FFT on 2 sets of data. They are organized in vectors of vectors

```<code> std::vector<std::vector<double>> template_data;
</code>```

I did look into it but I can not manage to clarify if the FFT of the template_data is the equivalent of the FFT applied on each sub-vector.

Title: FFT on vector of vectors

Body:
I am trying to apply an FFT on 2 sets of data. They are organized in vectors of vectors

 std::vector<std::vector<double>> template_data;

I did look into it but I can not manage to clarify if the FFT of the template_data is the equivalent of the FFT applied on each sub-vector.


问:
Flutter shows Animation only on Start
I created a FadeTransition so that every time the users gets to the HomeScreen he should see the Transition. As you can see in the Video: https://streamable.com/78zq3m it executes only on start up the Transition, not when I switch the Widgets in the NavBar or click when I navigate to a New screen and go back. In these cases, it ignores my Fade Transition. Does anybody know why?
For the NavBar I use a IndexedStack:

```<code>return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: selectedIdx,
        onTap: (idx) => setState(() {
          selectedIdx = idx;
        }),
        items: screens
            .map(
              (e) => BottomNavigationBarItem(
            label: e.label,
            icon: e.icon,
          ),
        )
            .toList(),
      ),
      body: ScrollConfiguration(
        behavior: MyBehavior(),
        child: IndexedStack(
          index: selectedIdx,
          children: [
            ...screens.map((e) => e.screen).toList(),
          ],
        ),
      ),
    );
</code>```

I think here is not the problem ...

For the MainWindow you see there I created an Animation and a Controller :
This is one of the 4 Windows, in all 4 I do it in the same way.

```<code>  late final AnimationController _controller = AnimationController(
    duration: const Duration(milliseconds: 370),
    vsync: this,
  );

  late final Animation<double> _animation = CurvedAnimation(
    parent: _controller,
    curve: Curves.easeIn,
  );
</code>```

and then I used it in the Widget build method:

```<code>  @override
  Widget build(BuildContext context) {
    _controller.forward();
    return  FadeTransition(
      opacity: _animation,
      child: CustomScrollView(
        physics: const ScrollPhysics(),
        slivers: [
          SliverAppBar(  [...]
</code>```

Does anybody see the problem?
Thank you!

Title: Flutter shows Animation only on Start

Body:
I created a FadeTransition so that every time the users gets to the HomeScreen he should see the Transition. As you can see in the Video: https://streamable.com/78zq3m it executes only on start up the Transition, not when I switch the Widgets in the NavBar or click when I navigate to a New screen and go back. In these cases, it ignores my Fade Transition. Does anybody know why?
For the NavBar I use a IndexedStack:

return Scaffold(
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: selectedIdx,
        onTap: (idx) => setState(() {
          selectedIdx = idx;
        }),
        items: screens
            .map(
              (e) => BottomNavigationBarItem(
            label: e.label,
            icon: e.icon,
          ),
        )
            .toList(),
      ),
      body: ScrollConfiguration(
        behavior: MyBehavior(),
        child: IndexedStack(
          index: selectedIdx,
          children: [
            ...screens.map((e) => e.screen).toList(),
          ],
        ),
      ),
    );

I think here is not the problem ...

For the MainWindow you see there I created an Animation and a Controller :
This is one of the 4 Windows, in all 4 I do it in the same way.

  late final AnimationController _controller = AnimationController(
    duration: const Duration(milliseconds: 370),
    vsync: this,
  );

  late final Animation<double> _animation = CurvedAnimation(
    parent: _controller,
    curve: Curves.easeIn,
  );

and then I used it in the Widget build method:

  @override
  Widget build(BuildContext context) {
    _controller.forward();
    return  FadeTransition(
      opacity: _animation,
      child: CustomScrollView(
        physics: const ScrollPhysics(),
        slivers: [
          SliverAppBar(  [...]

Does anybody see the problem?
Thank you!


问:
How to make a splash screen on Electron?
I'm new to Electron and I joined an existing project. I'm trying to add an image before the main screen of the app that will last 5 seconds. At first, I tried it with useState and setTimeone but I've realized I'm in the wrong place of the code.
After reading all kinds of solutions, and running the app - I now need your help.
This is some of the code in my main.ts file:

mainWindow = new BrowserWindow({
    show: false,
    width: 521,
    height: 712,
    icon: getAssetPath('icon.png'),
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: true,
      preload: app.isPackaged
        ? path.join(__dirname, 'preload.+212 662-122618 js')
        : path.join(__dirname, '../../.erb/dll/preload.js'),
    },
  });

  mainWindow.loadURL(resolveHtmlPath('index.html'));

  mainWindow.on('ready-to-show', () => {
    if (!mainWindow) {
      throw new Error('"mainWindow" is not defined');
    }
    if (process.env.START_MINIMIZED) {
      mainWindow.minimize();
    } else {
      mainWindow.show();
    }
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  const menuBuilder = new MenuBuilder(mainWindow);
  menuBuilder.buildMenu();
// Open urls in the user's browser
  mainWindow.webContents.setWindowOpenHandler((edata) => {
    shell.openExternal(edata.url);
    return { action: 'deny' };
  });

  // Remove this if your app does not use auto updates
  // eslint-disable-next-line
  new AppUpdater();
};

/**
 * Add event listeners...
 */

app.on('window-all-closed', () => {
  // Respect the OSX convention of having the application in memory even
  // after all windows have been closed
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app
  .whenReady()
  .then(() => {
    createWindow();
    app.on('activate', () => {
      // On macOS it's common to re-create a window in the app when the
      // dock icon is clicked and there are no other windows open.
      if (mainWindow === null) createWindow();
    });
  })
  .catch(console.log);

```


问:
Where should I store upcoming emails to send?
I develop a Laravel app and want to send out an email two days after some user interaction.

Where should I store this "to send emails"?

In a new table? Or in a queue?

Or somewhere else? What is considered to be "best practice"? Why?


问:
How to obtain the validated class with ConstraintValidatorContext
I am adding a custom annotation constraint at class level as follows:

```<code>@PasswordMatch(message = "Given passwords don't match")
public class RegistrationDto {

    private String password;
    private String passwordConfirmation;
    ...
</code>```

The PasswordMatchValidator looks like:

```<code>public class PasswordMatchValidator implements ConstraintValidator<PasswordMatch, Object> {

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {

        RegistrationDto registrationDto = (RegistrationDto) object;

        String password = registrationDto.getPassword();
        String passwordConfirmation = registrationDto.getPasswordConfirmation();

       return password.equals(passwordConfirmation);
    }
}
</code>```

This works fine, as long as I know that the class I am checking is of type RegistrationDto. My question is:

How can I generalize this annotation so that I can use it for other dtos as well?

My current approach is to use an interface:

```<code>@PasswordMatch(message = "Given passwords don't match")
public class RegistrationDto implements PasswordMatchCheckable {

    private String password;
    private String passwordConfirmation;
    ...
</code>```
```<code>public interface PasswordMatchCheckable {

    String getPassword();
    String getPasswordConfirmation();
}
</code>```
```<code>public class PasswordMatchValidator implements ConstraintValidator<PasswordMatch, PasswordMatchCkeckable> {

    @Override
    public boolean isValid(PasswordMatchCkeckable dto, ConstraintValidatorContext context) {

        String password = dto.getPassword();
        String passwordConfirmation = dto.getPasswordConfirmation();

       return password.equals(passwordConfirmation);
    }
}
</code>```

This seems to be a bit better, but I'm still not completely convinced.

Is there a better way to obtain the annotated class and check whether we can perform a password match validation? What can we do with the ConstraintValidatorContext? I couldn't come up with a cool solution, but I don't wanna give up until someone tells me that there is no better way.

Many thanks

Body:
I am adding a custom annotation constraint at class level as follows:

@PasswordMatch(message = "Given passwords don't match")
public class RegistrationDto {

    private String password;
    private String passwordConfirmation;
    ...

The PasswordMatchValidator looks like:

public class PasswordMatchValidator implements ConstraintValidator<PasswordMatch, Object> {

    @Override
    public boolean isValid(Object object, ConstraintValidatorContext context) {

        RegistrationDto registrationDto = (RegistrationDto) object;

        String password = registrationDto.getPassword();
        String passwordConfirmation = registrationDto.getPasswordConfirmation();

       return password.equals(passwordConfirmation);
    }
}

This works fine, as long as I know that the class I am checking is of type RegistrationDto. My question is:

How can I generalize this annotation so that I can use it for other dtos as well?

My current approach is to use an interface:

@PasswordMatch(message = "Given passwords don't match")
public class RegistrationDto implements PasswordMatchCheckable {

    private String password;
    private String passwordConfirmation;
    ...

public interface PasswordMatchCheckable {

    String getPassword();
    String getPasswordConfirmation();
}

public class PasswordMatchValidator implements ConstraintValidator<PasswordMatch, PasswordMatchCkeckable> {

    @Override
    public boolean isValid(PasswordMatchCkeckable dto, ConstraintValidatorContext context) {

        String password = dto.getPassword();
        String passwordConfirmation = dto.getPasswordConfirmation();

       return password.equals(passwordConfirmation);
    }
}

This seems to be a bit better, but I'm still not completely convinced.

Is there a better way to obtain the annotated class and check whether we can perform a password match validation? What can we do with the ConstraintValidatorContext? I couldn't come up with a cool solution, but I don't wanna give up until someone tells me that there is no better way.

Many thanks


问:
Cloning entities and resetting Id's and foreign keys in EF Core
I have a number of tables in my SQL database that link to each other via foreign keys.

The Id's are auto-increment identities.

My application allows the user to construct certain templates, and add them to the database.

To retrieve a full template I use this syntax (which I am not sure is entirely correct)

```<code>private Template GetFullTemplate(int Id)
    {
        using (var context = new DbContext())
        {
            return context.Templates
                .Where(template => template.Id == Id)
                .Include(lines => lines.TemplateLines)
                .ThenInclude(moi => moi.MethodOfInput)

                .Include(lines => lines.TemplateLines)
                .ThenInclude(unit => unit.UnitOfMeasure)

                .Include(lines => lines.TemplateLines)
                .ThenInclude(reading => reading.TemplateReadings)
                .ThenInclude(type => type.ReadingType)

                .Include(columns => columns.TemplateColumns)
                .FirstOrDefault();
        }
    }
</code>```

The users would like to clone a full template, then change a few details and save it to the database as a new template. Therein lies my problem.

The Problem:
The issue I have is that all of the related entities need their own Id's set to zero AND the foreign key Id's setting to zero before I can insert the new template.

The only way I can think of doing this is to manually go through each field, setting everything to zero like so...

```<code>    Template.Id = 0
    TemplateLine.Id = 0
    Templateline.TemplateId = 0

etc....
</code>```

As my database gets more tables I will need to keep adding more lines of this zeroing code.

I have scoured the internet to try to find anyone that may have handled this issue, but to no avail.

I was hoping there may be some elegant way of doing this rather than have to write lines and lines of code that sets all of these to zero. I don't think my situation is particularly unique, so I had hoped there would be a better way of achieving this.

Or maybe my approach is completely wrong? And advice greatly appreciated.

Body:
I have a number of tables in my SQL database that link to each other via foreign keys.

The Id's are auto-increment identities.

My application allows the user to construct certain templates, and add them to the database.

To retrieve a full template I use this syntax (which I am not sure is entirely correct)

private Template GetFullTemplate(int Id)
    {
        using (var context = new DbContext())
        {
            return context.Templates
                .Where(template => template.Id == Id)
                .Include(lines => lines.TemplateLines)
                .ThenInclude(moi => moi.MethodOfInput)

                .Include(lines => lines.TemplateLines)
                .ThenInclude(unit => unit.UnitOfMeasure)

                .Include(lines => lines.TemplateLines)
                .ThenInclude(reading => reading.TemplateReadings)
                .ThenInclude(type => type.ReadingType)

                .Include(columns => columns.TemplateColumns)
                .FirstOrDefault();
        }
    }

The users would like to clone a full template, then change a few details and save it to the database as a new template. Therein lies my problem.

The Problem:
The issue I have is that all of the related entities need their own Id's set to zero AND the foreign key Id's setting to zero before I can insert the new template.

The only way I can think of doing this is to manually go through each field, setting everything to zero like so...

    Template.Id = 0
    TemplateLine.Id = 0
    Templateline.TemplateId = 0

etc....

As my database gets more tables I will need to keep adding more lines of this zeroing code.

I have scoured the internet to try to find anyone that may have handled this issue, but to no avail.

I was hoping there may be some elegant way of doing this rather than have to write lines and lines of code that sets all of these to zero. I don't think my situation is particularly unique, so I had hoped there would be a better way of achieving this.

Or maybe my approach is completely wrong? And advice greatly appreciated.


问:
Spring Boot Graphql Remove duplicates from the Response
How to remove the duplicates from the response of Graphql automatically

Lets see the below graphql request I have.

```<code>query {
  test1(request:{
            userId: "test1@test.com"
  }) {
       id
       name
       product
  }
}
</code>```

And the Response is below:

```<code>{
    "data": {
        "test1": [{
                "id": 1,
                "name": "Test",
                "product": "ABCD"
            }, {
                "id": 1,
                "name": "Test",
                "product": "ABCD-2"
            },
        ]
    }
}
</code>```

Now if I remove the "product" in the query response field, the reponse looks like below. That is where the duplicates come.

```<code>{
    "data": {
        "test1": [{
                "id": 1,
                "name": "Test"
            }, {
                "id": 1,
                "name": "Test"
            },
        ]
    }
}
</code>```

Let me know if we have any library available to do this. We are using Spring Boot with below dependency.

```<code><dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-graphql</artifactId>
</dependency>
</code>```

Body:
How to remove the duplicates from the response of Graphql automatically

Lets see the below graphql request I have.

query {
  test1(request:{
            userId: "test1@test.com"
  }) {
       id
       name
       product
  }
}

And the Response is below:

{
    "data": {
        "test1": [{
                "id": 1,
                "name": "Test",
                "product": "ABCD"
            }, {
                "id": 1,
                "name": "Test",
                "product": "ABCD-2"
            },
        ]
    }
}

Now if I remove the "product" in the query response field, the reponse looks like below. That is where the duplicates come.

{
    "data": {
        "test1": [{
                "id": 1,
                "name": "Test"
            }, {
                "id": 1,
                "name": "Test"
            },
        ]
    }
}

Let me know if we have any library available to do this. We are using Spring Boot with below dependency.

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-graphql</artifactId>
</dependency>


问:
How to read a column in the format of dictionaty in a .csv file in Python?
I have a csv file, the second column is in the format of a dictionary (See the example below for a row in that column). I am trying to read the column as a dictionary type by following this tutorial, but the column is still in the object type.

{
    "cap": {
        "english": 0.8018818614025648,
        "universal": 0.5557322218336633
    },
    "display_scores": {
        "english": {
            "astroturf": 0.0,
            "fake_follower": 4.1,
            "financial": 1.5,
            "other": 4.7,
            "overall": 4.7,
            "self_declared": 3.2,
            "spammer": 2.8
        },
        "universal": {
            "astroturf": 0.3,
            "fake_follower": 3.2,
            "financial": 1.6,
            "other": 3.8,
            "overall": 3.8,
            "self_declared": 3.7,
            "spammer": 2.3
        }
    },
    "raw_scores": {
        "english": {
            "astroturf": 0.0,
            "fake_follower": 0.81,
            "financial": 0.3,
            "other": 0.94,
            "overall": 0.94,
            "self_declared": 0.63,
            "spammer": 0.57
        },
        "universal": {
            "astroturf": 0.06,
            "fake_follower": 0.64,
            "financial": 0.3133333333333333,
            "other": 0.76,
            "overall": 0.76,
            "self_declared": 0.74,
            "spammer": 0.47
        }
    },
    "user": {
        "majority_lang": "en",
        "user_data": {
            "id_str": "11330",
            "screen_name": "test_screen_name"
        }
    }
}

```
<p>This is what I did for now:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import ast
df = pd.read_csv(r"C:\Users\daiyaxin\Desktop\python_botometer\result_Dec_16.csv", dtype={'bot_score':object})
df['bot_score'] = df['bot_score'].apply(ast.literal_eval)
</code>```

Any suggestions? Thanks!

Body:
I have a csv file, the second column is in the format of a dictionary (See the example below for a row in that column). I am trying to read the column as a dictionary type by following this tutorial, but the column is still in the object type.

{
    "cap": {
        "english": 0.8018818614025648,
        "universal": 0.5557322218336633
    },
    "display_scores": {
        "english": {
            "astroturf": 0.0,
            "fake_follower": 4.1,
            "financial": 1.5,
            "other": 4.7,
            "overall": 4.7,
            "self_declared": 3.2,
            "spammer": 2.8
        },
        "universal": {
            "astroturf": 0.3,
            "fake_follower": 3.2,
            "financial": 1.6,
            "other": 3.8,
            "overall": 3.8,
            "self_declared": 3.7,
            "spammer": 2.3
        }
    },
    "raw_scores": {
        "english": {
            "astroturf": 0.0,
            "fake_follower": 0.81,
            "financial": 0.3,
            "other": 0.94,
            "overall": 0.94,
            "self_declared": 0.63,
            "spammer": 0.57
        },
        "universal": {
            "astroturf": 0.06,
            "fake_follower": 0.64,
            "financial": 0.3133333333333333,
            "other": 0.76,
            "overall": 0.76,
            "self_declared": 0.74,
            "spammer": 0.47
        }
    },
    "user": {
        "majority_lang": "en",
        "user_data": {
            "id_str": "11330",
            "screen_name": "test_screen_name"
        }
    }
}

This is what I did for now:

import pandas as pd
import ast
df = pd.read_csv(r"C:\Users\daiyaxin\Desktop\python_botometer\result_Dec_16.csv", dtype={'bot_score':object})
df['bot_score'] = df['bot_score'].apply(ast.literal_eval)

Any suggestions? Thanks!


问:
Pygame how to print a rect (with text) above everything?
I'm working in my first python project for a course of Introduction to Python.

It will be a short 2D game where you basically move a player through the map and when you click in certain tiles a rect with some dialogues will appear on the screen.

The issues is that the rect that appear on the screen is below the sprite that are composing the map, so the text it cannot be read.

So i was wondering if there is some way to draw this rect with text above everything else in the map!


问:
Inconsistent number of frame callbacks from Surfacetexture when used as target for MediaPlayer
I am trying to use android MediaPlayer to render frames to the display using a Surface.

I have created an android SurfaceTexture (from an OpenGL texture) and then using it create a Surface and set that Surface as render target for the MediaPlayer object.

I have setup a callback for the SurfaceTexture using setOnFrameAvailableListener() to listen to frames , so that whenever a frame is available I can draw it using my shader code.

Everything works perfect except that the number of onFrameAvailable() callbacks I get is inconsistent. First of all it doesnt match the number of frames in the video (it always seems to be more) and also the number of callbacks also varies from one to another invokation.

I guess the MediaPlayer tries to adjust the frame rate and pushes more frame (A wild guess though)

I need exact number of callbacks as there are frames in the video , as I am having some per frame data offline and match them with the frames.


问:
Maven error reguarding war files & pom.xml
```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.my.ssat</groupId>
    <artifactId>myssatProject</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>myweb</artifactId>
  <packaging>war</packaging>
  <name>myweb</name>
</project>
</code>```

Cannot access default field of properties

web.xml is missing and  is set to true.

I am getting these errors whenever I create maven module in (war) format

Body:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.my.ssat</groupId>
    <artifactId>myssatProject</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>myweb</artifactId>
  <packaging>war</packaging>
  <name>myweb</name>
</project>

Cannot access default field of properties

web.xml is missing and  is set to true.

I am getting these errors whenever I create maven module in (war) format


问:
Thank you page on opencart.com
Do you know if there is a default url address after completing a purchase in opencart.com websites?</p>

Title: Thank you page on opencart.com


问:
Check if user has specific program installed on PC
I made a program with Visual Studio and I managed to open it using an href in my Angular page, how can I know if the user has installed it when the page is trying to open it using href=program: ?
Im trying to alert the user by downloading the installer if is not installed.
I used:

```<code>window.location.href = "program:"+id;
</code>```

I see the popup asking to open my software, but I need to know if this popup appears or not so I can fire the download function. Any help?

Body:
I made a program with Visual Studio and I managed to open it using an href in my Angular page, how can I know if the user has installed it when the page is trying to open it using href=program: ?
Im trying to alert the user by downloading the installer if is not installed.
I used:

window.location.href = "program:"+id;

I see the popup asking to open my software, but I need to know if this popup appears or not so I can fire the download function. Any help?