问:
In the CPPTools extension for VS Code, is /** really recursive?
I just opened a folder (based on this setup) in VS Code (1.74) containing C code I would like to be handled by the CPPTools extension (1.13.8). Within the folder (.../rd-infra/arm-tf), there is an extensive amount of code in the tree. The default includePath for the folder/workspace includes "${workspaceFolder}/**". However, the second #include in the source (.../rd-infra/arm-tf/bl1/bl1_main.c):

```<code>#include <platform_def.h>
</code>```

shows squiggles and an error:

```<code>cannot open source file "platform_def.h"C/C++(1696)
</code>```

I tried right-clicking on the include to "Go to definition," but this failed.

Doing a search of the tree, I find about 74 versions of this file:

```<code>~/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf$ find . -name 'platform_def.h'
./plat/intel/soc/common/include/platform_def.h
./plat/st/stm32mp1/include/platform_def.h
./plat/hisilicon/poplar/include/platform_def.h
./plat/hisilicon/hikey960/include/platform_def.h
./plat/hisilicon/hikey/include/platform_def.h
./plat/mediatek/mt8186/include/platform_def.h
...
</code>```

I thought this made the error all the more odd, as I would expect a redundancy issue with so many to choose from. That's not what the error says, but I went ahead and added the specific compiler to .../rd-infra/arm-tf/.vscode/c_cpp_properties.json to see if that helped:

```<code>{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "linux-gcc-arm64"
        }
    ],
    "version": 4
}
</code>```

and nothing changed.

So, it appears to me that the ${workspaceFolder}/** is not being recursively searched.

Then I added the specific include directory for the version of the file that applies in my case:

```<code>{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/plat/arm/board/rdn2/include",
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "linux-gcc-arm64"
        }
    ],
    "version": 4
}
</code>```

And the squiggles disappeared. I right-clicked on the include to choose "Go to definition," which opened the platform_def.h header file, where there were includes with squiggles as well, showing the same error as before (1696).

So now I'm in the same boat with a new include line:

```<code>#include <lib/utils_def.h>
</code>```

Searching for that file:

```<code>~/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf$ find . -name 'utils_def.h'
./include/lib/utils_def.h
</code>```

So it looks like ${workspaceFolder}/** isn't even making it one level deep?

I also tried with the full path, both with and without using ${userHome}:

```<code>{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf/**"
            ],
            "defines": [],
            "compilerPath": "${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "linux-gcc-arm64"
        }
    ],
    "version": 4
}
</code>```

and it was back to unable to open platform_def.h (1696).

Am I misunderstanding the /** notation?

========= Edit 1 =========

Dumping predefined variables:

```<code>userHome:        /home/rtillery
workspaceFolder: /home/rtillery/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf
compiler path:   /home/rtillery/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc
</code>```

Verifying compiler path:

```<code>~/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf$ ll /home/rtillery/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc
-rwxr-xr-x 2 802 802 1213640 Feb  2  2022 /home/rtillery/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc*
</code>```

And possibly related to @n.m.'s comment, I do get the following error (twice):

```<code>cannot open source file "platform_def.h"C/C++(1696)
</code>```0

On the other hand, I don't actually see what the compiler output has to do with CPPTools recursively searching a path provided. (Adding compilerPath above was just a stab in the dark and probably muddied the waters around this question.) Maybe someone can explain if they are?

========= Edit 2 =========

Also, probably not related. In spite of the variable dump above (accomplished using the example at the bottom of this page), the editor shows a different expansion of the ${userHome} predefined variable, which includes the variable expansion and the variable name:

From c_cpp_properties.json:

```<code>cannot open source file "platform_def.h"C/C++(1696)
</code>```1

Error shown in the Problems tab, under the c_cpp_properties.json file:

```<code>cannot open source file "platform_def.h"C/C++(1696)
</code>```2

That's very strange.

Replacing the line with one based on the ${workspaceFolder} instead:

```<code>            "compilerPath": "${workspaceFolder}/../tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc",
</code>```

seems to work, as the error disappears.

========= Edit 3 =========

Filed a bug for the other issue mentioned above.

Body:
I just opened a folder (based on this setup) in VS Code (1.74) containing C code I would like to be handled by the CPPTools extension (1.13.8). Within the folder (.../rd-infra/arm-tf), there is an extensive amount of code in the tree. The default includePath for the folder/workspace includes "${workspaceFolder}/**". However, the second #include in the source (.../rd-infra/arm-tf/bl1/bl1_main.c):

#include <platform_def.h>

shows squiggles and an error:

cannot open source file "platform_def.h"C/C++(1696)

I tried right-clicking on the include to "Go to definition," but this failed.

Doing a search of the tree, I find about 74 versions of this file:

~/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf$ find . -name 'platform_def.h'
./plat/intel/soc/common/include/platform_def.h
./plat/st/stm32mp1/include/platform_def.h
./plat/hisilicon/poplar/include/platform_def.h
./plat/hisilicon/hikey960/include/platform_def.h
./plat/hisilicon/hikey/include/platform_def.h
./plat/mediatek/mt8186/include/platform_def.h
...

I thought this made the error all the more odd, as I would expect a redundancy issue with so many to choose from. That's not what the error says, but I went ahead and added the specific compiler to .../rd-infra/arm-tf/.vscode/c_cpp_properties.json to see if that helped:

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "linux-gcc-arm64"
        }
    ],
    "version": 4
}

and nothing changed.

So, it appears to me that the ${workspaceFolder}/** is not being recursively searched.

Then I added the specific include directory for the version of the file that applies in my case:

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${workspaceFolder}/plat/arm/board/rdn2/include",
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "compilerPath": "${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "linux-gcc-arm64"
        }
    ],
    "version": 4
}

And the squiggles disappeared. I right-clicked on the include to choose "Go to definition," which opened the platform_def.h header file, where there were includes with squiggles as well, showing the same error as before (1696).

So now I'm in the same boat with a new include line:

#include <lib/utils_def.h>

Searching for that file:

~/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf$ find . -name 'utils_def.h'
./include/lib/utils_def.h

So it looks like ${workspaceFolder}/** isn't even making it one level deep?

I also tried with the full path, both with and without using ${userHome}:

{
    "configurations": [
        {
            "name": "Linux",
            "includePath": [
                "${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf/**"
            ],
            "defines": [],
            "compilerPath": "${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc",
            "cStandard": "gnu17",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "linux-gcc-arm64"
        }
    ],
    "version": 4
}

and it was back to unable to open platform_def.h (1696).

Am I misunderstanding the /** notation?

========= Edit 1 =========

Dumping predefined variables:

userHome:        /home/rtillery
workspaceFolder: /home/rtillery/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf
compiler path:   /home/rtillery/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc

Verifying compiler path:

~/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf$ ll /home/rtillery/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc
-rwxr-xr-x 2 802 802 1213640 Feb  2  2022 /home/rtillery/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc*

And possibly related to @n.m.'s comment, I do get the following error (twice):

[12/20/2022, 10:47:36 AM] Unable to resolve configuration with compilerPath "${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc".  Using "/usr/bin/gcc" instead.

On the other hand, I don't actually see what the compiler output has to do with CPPTools recursively searching a path provided. (Adding compilerPath above was just a stab in the dark and probably muddied the waters around this question.) Maybe someone can explain if they are?

========= Edit 2 =========

Also, probably not related. In spite of the variable dump above (accomplished using the example at the bottom of this page), the editor shows a different expansion of the ${userHome} predefined variable, which includes the variable expansion and the variable name:

From c_cpp_properties.json:

            "compilerPath": "${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc",

Error shown in the Problems tab, under the c_cpp_properties.json file:

Cannot find "/home/rtillery/Projects/ARMFVPs/FVP_RD_N2/rd-infra/arm-tf/${userHome}/Projects/ARMFVPs/FVP_RD_N2/rd-infra/tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc".

That's very strange.

Replacing the line with one based on the ${workspaceFolder} instead:

            "compilerPath": "${workspaceFolder}/../tools/gcc/gcc-arm-11.2-2022.02-x86_64-aarch64-none-linux-gnu/bin/aarch64-none-linux-gnu-gcc",

seems to work, as the error disappears.

========= Edit 3 =========

Filed a bug for the other issue mentioned above.


来源: stackexchange

问:
How to do Semantic segmentation with detectron2
I'm using Detectron2 to do instance segmentation as in the tutorial. Below is the code:

```<code>from detectron2.config import CfgNode
import detectron2.data.transforms as T
from detectron2.data import build_detection_train_loader, DatasetMapper

os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)

transform_list = [
    # T.Resize(shape=(200,300)),
    T.RandomRotation(angle=90.0),
    # T.RandomContrast(intensity_min=0.75, intensity_max=1.25),
    # T.RandomBrightness(intensity_min=0.75, intensity_max=1.25),
    # T.RandomSaturation(intensity_min=0.75, intensity_max=1.25),
    # T.RandomLighting(scale=0.1),
    T.RandomFlip(),
    # T.RandomCrop(crop_type="absolute", crop_size=(180, 270))
]

# custom_mapper = get_custom_mapper(transfrom_list)
custom_mapper = DatasetMapper(
    cfg,
    is_train=True,
    augmentations=transform_list,
    use_instance_mask=True,
    instance_mask_format="bitmask",
    )

class CustomTrainer(DefaultTrainer):
    @classmethod
    def build_test_loader(cls, cfg: CfgNode, dataset_name):
        return build_detection_test_loader(cfg, dataset_name, mapper=custom_mapper)

    @classmethod
    def build_train_loader(cls, cfg: CfgNode):
        return build_detection_train_loader(cfg, mapper=custom_mapper)

cfg.INPUT.MASK_FORMAT = 'bitmask'
cfg.DATALOADER.FILTER_EMPTY_ANNOTATIONS = False

trainer = CustomTrainer(cfg)
# trainer = DefaultTrainer(cfg)

# trainer.resume_or_load(resume=False)
# trainer.train()
</code>```

However, in this case I don't care about instances and more like I want to do semantic segmentation but there is no tutorial or examples to do that nor I'm seeing a semantic model I can start with. Misc/semantic_R_50_FPN_1x.yaml throws an error saying there is no pretrained model available.

So instead I'm trying to use the SemSegEvaluator instead of COCO evaluator to give me metrics around semantic rather than instances. Below is the code:

```<code>from detectron2.evaluation import COCOEvaluator, inference_on_dataset, SemSegEvaluator
from detectron2.data import build_detection_test_loader
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.4
# evaluator = COCOEvaluator(val_dataset_name, output_dir=os.path.join(cfg.OUTPUT_DIR, 'val'), use_fast_impl=False, tasks=['segm'])
evaluator = SemSegEvaluator(val_dataset_name, output_dir=os.path.join(cfg.OUTPUT_DIR, 'val'))
val_loader = build_detection_test_loader(cfg, val_dataset_name)
eval_result = inference_on_dataset(predictor.model, val_loader, evaluator)
print(eval_result)
</code>```

However, this is failing with the following error:

```<code>[12/20 16:29:02 d2.data.datasets.coco]: Loaded 50 imagesss abdul in COCO format from /content/gdrive/MyDrive/SolarDetection/datasets/train8//val/labels.json
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-10-61bd5aaec8ea> in <module>
      3 cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.4
      4 # evaluator = COCOEvaluator(val_dataset_name, output_dir=os.path.join(cfg.OUTPUT_DIR, 'val'), use_fast_impl=False, tasks=['segm'])
----> 5 evaluator = SemSegEvaluator(val_dataset_name, output_dir=os.path.join(cfg.OUTPUT_DIR, 'val'))
      6 val_loader = build_detection_test_loader(cfg, val_dataset_name)
      7 # ipdb.set_trace(context=6)

1 frames
/content/gdrive/MyDrive/repos/detectron2/detectron2/evaluation/sem_seg_evaluation.py in <dictcomp>(.0)
     69
     70         self.input_file_to_gt_file = {
---> 71             dataset_record["file_name"]: dataset_record["sem_seg_file_name"]
     72             for dataset_record in DatasetCatalog.get(dataset_name)
     73         }

KeyError: 'sem_seg_file_name'
</code>```

Any idea or hint how I can setup and use the SemSegEvaluator?

ContentLicense: CC BY-SA 4.0

Body:
I'm using Detectron2 to do instance segmentation as in the tutorial. Below is the code:

from detectron2.config import CfgNode
import detectron2.data.transforms as T
from detectron2.data import build_detection_train_loader, DatasetMapper

os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)

transform_list = [
    # T.Resize(shape=(200,300)),
    T.RandomRotation(angle=90.0),
    # T.RandomContrast(intensity_min=0.75, intensity_max=1.25),
    # T.RandomBrightness(intensity_min=0.75, intensity_max=1.25),
    # T.RandomSaturation(intensity_min=0.75, intensity_max=1.25),
    # T.RandomLighting(scale=0.1),
    T.RandomFlip(),
    # T.RandomCrop(crop_type="absolute", crop_size=(180, 270))
]

# custom_mapper = get_custom_mapper(transfrom_list)
custom_mapper = DatasetMapper(
    cfg,
    is_train=True,
    augmentations=transform_list,
    use_instance_mask=True,
    instance_mask_format="bitmask",
    )

class CustomTrainer(DefaultTrainer):
    @classmethod
    def build_test_loader(cls, cfg: CfgNode, dataset_name):
        return build_detection_test_loader(cfg, dataset_name, mapper=custom_mapper)

    @classmethod
    def build_train_loader(cls, cfg: CfgNode):
        return build_detection_train_loader(cfg, mapper=custom_mapper)

cfg.INPUT.MASK_FORMAT = 'bitmask'
cfg.DATALOADER.FILTER_EMPTY_ANNOTATIONS = False

trainer = CustomTrainer(cfg)
# trainer = DefaultTrainer(cfg)

# trainer.resume_or_load(resume=False)
# trainer.train()

However, in this case I don't care about instances and more like I want to do semantic segmentation but there is no tutorial or examples to do that nor I'm seeing a semantic model I can start with. Misc/semantic_R_50_FPN_1x.yaml throws an error saying there is no pretrained model available.

So instead I'm trying to use the SemSegEvaluator instead of COCO evaluator to give me metrics around semantic rather than instances. Below is the code:

from detectron2.evaluation import COCOEvaluator, inference_on_dataset, SemSegEvaluator
from detectron2.data import build_detection_test_loader
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.4
# evaluator = COCOEvaluator(val_dataset_name, output_dir=os.path.join(cfg.OUTPUT_DIR, 'val'), use_fast_impl=False, tasks=['segm'])
evaluator = SemSegEvaluator(val_dataset_name, output_dir=os.path.join(cfg.OUTPUT_DIR, 'val'))
val_loader = build_detection_test_loader(cfg, val_dataset_name)
eval_result = inference_on_dataset(predictor.model, val_loader, evaluator)
print(eval_result)

However, this is failing with the following error:

[12/20 16:29:02 d2.data.datasets.coco]: Loaded 50 imagesss abdul in COCO format from /content/gdrive/MyDrive/SolarDetection/datasets/train8//val/labels.json
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-10-61bd5aaec8ea> in <module>
      3 cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.4
      4 # evaluator = COCOEvaluator(val_dataset_name, output_dir=os.path.join(cfg.OUTPUT_DIR, 'val'), use_fast_impl=False, tasks=['segm'])
----> 5 evaluator = SemSegEvaluator(val_dataset_name, output_dir=os.path.join(cfg.OUTPUT_DIR, 'val'))
      6 val_loader = build_detection_test_loader(cfg, val_dataset_name)
      7 # ipdb.set_trace(context=6)

1 frames
/content/gdrive/MyDrive/repos/detectron2/detectron2/evaluation/sem_seg_evaluation.py in <dictcomp>(.0)
     69
     70         self.input_file_to_gt_file = {
---> 71             dataset_record["file_name"]: dataset_record["sem_seg_file_name"]
     72             for dataset_record in DatasetCatalog.get(dataset_name)
     73         }

KeyError: 'sem_seg_file_name'

Any idea or hint how I can setup and use the SemSegEvaluator?


问:
React DnD - items keep flickering nonstop while dragging
When I drag an item to other position, the rest keep flickering and re-rendering.

Here is reproduce at codesandbox


问:
How do I unmock jquery globally in Jest after automocking?
I've used jest automock as I'm facing nested namespace issues for my unit testing of a jQuery application.

```<code>module.exports = {
                automock: true;
                 }
</code>```

I'm mostly there, used code from Jon G

```<code>
const jQ = jest.requireActual("jquery");

const get = jest.fn((path) => {
    return Promise.resolve(path);
});

const when = jest.fn((prom1, prom2, prom3, prom4) => {
    return Promise.resolve();
});

const jQuery = jQ;
jQuery.get = get;
jQuery.when = when;
exports.jQuery = jQuery;
</code>```

I need the .find functionality unmocked

Ideally i want to use the jest.spyOn() feature to mock internal anonymous function calls which otherwise return as undefined, so I've ended up using babel-plugin-rewire to allow me to import the functions unaccessible to spyOn()

The function looks like

```<code>var XYZ = XYZ || {};
XYZ.Utils = (function () {
var functionName = function (blahblahblah) {
var x = XYZ.OtherNameSpace.usefulFunction(blahblahblah)
return x
}
</code>```

And is called by

```<code>XYZ.Utils.functionName(blahblahblah)
</code>```

I want to mock var x = XYZ.OtherNameSpace.usefulFunction(blahblahblah)
because jest can't see it and returns undefined.
Thus automocking, please help, I didn't write it this poorly coupled.

Body:
I've used jest automock as I'm facing nested namespace issues for my unit testing of a jQuery application.

module.exports = {
                automock: true;
                 }

I'm mostly there, used code from Jon G

const jQ = jest.requireActual("jquery");

const get = jest.fn((path) => {
    return Promise.resolve(path);
});

const when = jest.fn((prom1, prom2, prom3, prom4) => {
    return Promise.resolve();
});

const jQuery = jQ;
jQuery.get = get;
jQuery.when = when;
exports.jQuery = jQuery;

I need the .find functionality unmocked

Ideally i want to use the jest.spyOn() feature to mock internal anonymous function calls which otherwise return as undefined, so I've ended up using babel-plugin-rewire to allow me to import the functions unaccessible to spyOn()

The function looks like

var XYZ = XYZ || {};
XYZ.Utils = (function () {
var functionName = function (blahblahblah) {
var x = XYZ.OtherNameSpace.usefulFunction(blahblahblah)
return x
}

And is called by

XYZ.Utils.functionName(blahblahblah)

I want to mock var x = XYZ.OtherNameSpace.usefulFunction(blahblahblah)
because jest can't see it and returns undefined.
Thus automocking, please help, I didn't write it this poorly coupled.


问:
How to move one directory up in VS Code
How do I move one directory up while using url in css in VS Code ? For example I´m in C:\Blah\Blah\Blah and I need a picture that is in C:\Blah\Blah
How do I do that ?
Thanks</p>
<p>                                </p>

Title: How to move one directory up in VS Code


问:
Drawer menu blocked by fragment menu
So, I have an app that are using drawer menu and some fragments. But, when the fragment i'am on a fragment that have a menu, it completely blocked my drawer menu even if the burger icon is still visible.

But, when i press the back button and exit current Fragment with its own menu, the drawer menu works again. It seems like the menu from fragment are blocking the drawer menu. Here is my code for adding menu provider into fragment :

```<code>val menuHost: MenuHost = requireActivity()
    menuHost.addMenuProvider(
        this,
        viewLifecycleOwner,
        Lifecycle.State.RESUMED
    )
</code>```

And here is my code for inflating the menu :

```<code>menuInflater.inflate(R.menu.main_menu, menu)
    val myActionMenuItem = menu.findItem(R.id.btn_search_menu)
    val searchView = myActionMenuItem.actionView as SearchView?
    searchView?.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String?): Boolean {
            (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
                .hideSoftInputFromWindow(view?.windowToken, 0)

            return true
        }

        override fun onQueryTextChange(newText: String?): Boolean = false
    })
</code>```

Title: Drawer menu blocked by fragment menu

Body:
So, I have an app that are using drawer menu and some fragments. But, when the fragment i'am on a fragment that have a menu, it completely blocked my drawer menu even if the burger icon is still visible.

But, when i press the back button and exit current Fragment with its own menu, the drawer menu works again. It seems like the menu from fragment are blocking the drawer menu. Here is my code for adding menu provider into fragment :

val menuHost: MenuHost = requireActivity()
    menuHost.addMenuProvider(
        this,
        viewLifecycleOwner,
        Lifecycle.State.RESUMED
    )

And here is my code for inflating the menu :

menuInflater.inflate(R.menu.main_menu, menu)
    val myActionMenuItem = menu.findItem(R.id.btn_search_menu)
    val searchView = myActionMenuItem.actionView as SearchView?
    searchView?.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String?): Boolean {
            (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
                .hideSoftInputFromWindow(view?.windowToken, 0)

            return true
        }

        override fun onQueryTextChange(newText: String?): Boolean = false
    })


问:
errors in laravel files
I just installed laravel for the first time
andi have php 8.1

I haven't touched anything yet and I have the following errors

I don't understand these errors without having touched a single line of code.

I tried to find solutions but I don't know what to do

Title: errors in laravel files


问:
How to turn individual points into a kernel density map?
I am trying to recreate in Python a map I made in Tableau. I'm pretty sure it's called a kernel density map (just "density" map in Tableau). Each point is just a single point and doesn't correspond with any kind of value.

I have plotted my points on a map, but am unable to figure out how to give them the contour appearance in the Tableau map. I see some examples that include np.meshgrid or matplotlib's contourf function, but I'm unable to apply it to my data because I don't have a Z coordinate (from what I can tell). Below is what I have currently:

```<code>import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from datetime import timedelta, date
import matplotlib
from pandas import Series, DataFrame

import geopandas as gpd
from geopandas import GeoDataFrame
from shapely.geometry import Point, mapping

# import data
df = pd.read_csv('./Data/complete.csv', on_bad_lines='skip') # csv had some bad data, had to skip

# drop unneccessary columns
df = df[['datetime', 'latitude', 'longitude']]

# convert 'datetime' to YYYY-MM-DD
df['datetime'] = pd.to_datetime(df['datetime'], dayfirst=True)

# clean the data
# remove values that contain '/' and 'q'
df = df.drop(df[df.latitude.str.contains(r'[/q]')].index)

# convert lat/long to float
df['latitude'] = df.latitude.astype('float')
df['longitude'] = df.longitude.astype('float')

# create GDF from lat/long
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.longitude, df.latitude)).set_crs('EPSG:4326')

# import shapefile
us_map = gpd.read_file(r'./Data/USA_States_(Generalized)/USA_States_Generalized.shp')

#remove AK and HI
us_map = us_map[~us_map['STATE_NAME'].isin(['Alaska', 'Hawaii'])]

# plotting only 2012 sightings
sightings2012 = df[(df['datetime'] > '12/31/2011') & (df['datetime'] < '01/01/2013')]

# create GDF for 2012 sightings
gdf2012 = gpd.GeoDataFrame(sightings2012,
                           geometry=gpd.points_from_xy(sightings2012.longitude,
                                                       sightings2012.latitude)).set_crs('EPSG:4326')

# clip the sightings data
us_sightings_2012 = gpd.clip(gdf2012, us_map)

cmap = matplotlib.cm.get_cmap('plasma')

# plot
fig, ax = plt.subplots(1, 1)
us_map.plot(ax=ax)
us_sightings_2012.plot(ax=ax, cmap=cmap)

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

And here is my output:

Body:
I am trying to recreate in Python a map I made in Tableau. I'm pretty sure it's called a kernel density map (just "density" map in Tableau). Each point is just a single point and doesn't correspond with any kind of value.

I have plotted my points on a map, but am unable to figure out how to give them the contour appearance in the Tableau map. I see some examples that include np.meshgrid or matplotlib's contourf function, but I'm unable to apply it to my data because I don't have a Z coordinate (from what I can tell). Below is what I have currently:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from datetime import timedelta, date
import matplotlib
from pandas import Series, DataFrame

import geopandas as gpd
from geopandas import GeoDataFrame
from shapely.geometry import Point, mapping

# import data
df = pd.read_csv('./Data/complete.csv', on_bad_lines='skip') # csv had some bad data, had to skip

# drop unneccessary columns
df = df[['datetime', 'latitude', 'longitude']]

# convert 'datetime' to YYYY-MM-DD
df['datetime'] = pd.to_datetime(df['datetime'], dayfirst=True)

# clean the data
# remove values that contain '/' and 'q'
df = df.drop(df[df.latitude.str.contains(r'[/q]')].index)

# convert lat/long to float
df['latitude'] = df.latitude.astype('float')
df['longitude'] = df.longitude.astype('float')

# create GDF from lat/long
gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.longitude, df.latitude)).set_crs('EPSG:4326')

# import shapefile
us_map = gpd.read_file(r'./Data/USA_States_(Generalized)/USA_States_Generalized.shp')

#remove AK and HI
us_map = us_map[~us_map['STATE_NAME'].isin(['Alaska', 'Hawaii'])]

# plotting only 2012 sightings
sightings2012 = df[(df['datetime'] > '12/31/2011') & (df['datetime'] < '01/01/2013')]

# create GDF for 2012 sightings
gdf2012 = gpd.GeoDataFrame(sightings2012,
                           geometry=gpd.points_from_xy(sightings2012.longitude,
                                                       sightings2012.latitude)).set_crs('EPSG:4326')

# clip the sightings data
us_sightings_2012 = gpd.clip(gdf2012, us_map)

cmap = matplotlib.cm.get_cmap('plasma')

# plot
fig, ax = plt.subplots(1, 1)
us_map.plot(ax=ax)
us_sightings_2012.plot(ax=ax, cmap=cmap)

plt.show()

And here is my output:


问:
Why am I getting 401 unauthorised when making calls from client to my API
I created simple react  + express app for fetching data from Strava.

Authorization is done by passport.js and there aren't any problems when I run it locally (on separate ports client/server: 3000/8080 or using only server to provide production build) although when deployed the app on render.com I'm getting 401 unauthorised when making calls to my API.

I have two environments:

(client) static site for react app: https://statz.onrender.com

(server) web service for my express API: https://statz-api.onrender.com

For instance - to get logged athlete data client makes request to the server and then server is requesting that data from Strava API and returns the data to the client.

For now I have only two endpoints and both throw error 401 when called from client side.

Authentication is done server side and at the end the user is redirected back to the client. After all every request from client to API throws 401 but when calling endpoint directly from the browser eg: (https://statz-api.onrender.com/api/athlete) I'm getting complete data. Demo: https://share.getcloudapp.com/NQu4J7YL
Probably it's worth to mention there is no cookie in the request headers when calling from client.
I had some CORS errors first but probably I sorted them out since there is nothing about it on the console.

I would be grateful if somebody could look at this and show me what I'm still missing in my configs.

Link to github: https://github.com/PatrykJamroz/StravaStats/tree/deploy-1

server:

```<code>const express = require("express");
const passport = require("passport");
const cors = require("cors");
const logger = require("morgan");
const StravaStrategy = require("passport-strava-oauth2").Strategy;
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const cookieSession = require("cookie-session");

const app = express();

app.use(
  cors({
    credentials: true,
    origin: "https://statz.onrender.com",
    exposedHeaders: ["Set-Cookie"],
  })
);

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Credentials", true);
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

require("dotenv").config();

const fetch = (...args) =>
  import("node-fetch").then(({ default: _fetch }) => _fetch(...args));

const STRAVA_CLIENT_ID = process.env.STRAVA_CLIENT_ID;
const STRAVA_CLIENT_SECRET = process.env.STRAVA_CLIENT_SECRET;

passport.serializeUser(function (user, done) {
  done(null, user);
});

passport.deserializeUser(function (obj, done) {
  done(null, obj);
});

passport.use(
  new StravaStrategy(
    {
      clientID: STRAVA_CLIENT_ID,
      clientSecret: STRAVA_CLIENT_SECRET,
      callbackURL: "/auth/strava/callback",
    },
    function (accessToken, refreshToken, profile, done) {
      process.nextTick(function () {
        return done(null, profile);
      });
    }
  )
);

app.use(logger("combined"));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.methodOverride());
app.use(cookieSession({ secret: "keyboard cat" }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

const SCOPES = "read,activity:read_all,read_all";

app.get(
  "/auth/strava",
  passport.authenticate("strava", { scope: SCOPES }),
  function (req, res) {
    // The request will be redirected to Strava for authentication, so this
    // function will not be called.
  }
);

app.get(
  "/auth/strava/callback",
  passport.authenticate("strava", {
    scope: SCOPES,
    failureRedirect: "/login",
  }),
  function (req, res) {
    res.redirect("https://statz.onrender.com");
  }
);

app.get("/api/athlete", async (req, res) => {
  fetch(
    `https://www.strava.com/api/v3/athlete?access_token=${
      req.user?.token ?? ""
    }`
  )
    .then((response) => {
      if (response.ok) {
        return response.json();
      }
      res.status(response.status).json({ error: response.statusText });
      throw new Error(`${response.status} - ${response.statusText}`);
    })
    .then((data) => res.json(data))
    .catch((error) => console.error({ error }));
});

app.get("/api/activities", async function (req, res) {
  if (!req.user) {
    res.json({ error: "Not authenticated" });
  }

  let page = 1;
  let activities = [];

  while (true) {
    const activitiesPromise = await fetch(
      `https://www.strava.com/api/v3/athlete/activities?per_page=30&page=${page}&access_token=${req.user.token}`
    );
    const activitiesData = await activitiesPromise.json();
    page += 1;
    activities = [...activities, ...activitiesData];
    logger({ page });
    if (activitiesData.length < 30) {
      return res.json(activities);
    }
  }
});

app.get("/api/ping", function (req, res) {
  res.send("pong");
});

const listener = app.listen(process.env.PORT || 8080, () => {
  console.log(`Your app is listening on port ${listener.address().port}`);
});
</code>```

Client API calls:

```<code>import axios from 'axios';
import { Activity, Athlete } from '../models/Strava';

const BASE_URL = 'https://statz-api.onrender.com';

export const getAthlete = async (): Promise<Athlete> => {
  return axios.get(`${BASE_URL}/api/athlete`, { withCredentials: true }).then(({ data }) => data);
};

export const getActivities = async (): Promise<Activity[]> => {
  return axios
    .get(`${BASE_URL}/api/activities`, { withCredentials: true })
    .then(({ data }) => data);
};

</code>```

Authorization component:

```<code>export function Authorization() {
  const login = () => {
    window.open('https://statz-api.onrender.com/auth/strava', '_self');
  };
  return (
    <Button onClick={login} variant="outlined">
      <img alt="authorize" src="/btn_strava_auth.png" />
    </Button>
  );
}
</code>```

Body:
I created simple react  + express app for fetching data from Strava.

Authorization is done by passport.js and there aren't any problems when I run it locally (on separate ports client/server: 3000/8080 or using only server to provide production build) although when deployed the app on render.com I'm getting 401 unauthorised when making calls to my API.

I have two environments:

(client) static site for react app: https://statz.onrender.com

(server) web service for my express API: https://statz-api.onrender.com

For instance - to get logged athlete data client makes request to the server and then server is requesting that data from Strava API and returns the data to the client.

For now I have only two endpoints and both throw error 401 when called from client side.

Authentication is done server side and at the end the user is redirected back to the client. After all every request from client to API throws 401 but when calling endpoint directly from the browser eg: (https://statz-api.onrender.com/api/athlete) I'm getting complete data. Demo: https://share.getcloudapp.com/NQu4J7YL
Probably it's worth to mention there is no cookie in the request headers when calling from client.
I had some CORS errors first but probably I sorted them out since there is nothing about it on the console.

I would be grateful if somebody could look at this and show me what I'm still missing in my configs.

Link to github: https://github.com/PatrykJamroz/StravaStats/tree/deploy-1

server:

const express = require("express");
const passport = require("passport");
const cors = require("cors");
const logger = require("morgan");
const StravaStrategy = require("passport-strava-oauth2").Strategy;
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const cookieSession = require("cookie-session");

const app = express();

app.use(
  cors({
    credentials: true,
    origin: "https://statz.onrender.com",
    exposedHeaders: ["Set-Cookie"],
  })
);

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Credentials", true);
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

require("dotenv").config();

const fetch = (...args) =>
  import("node-fetch").then(({ default: _fetch }) => _fetch(...args));

const STRAVA_CLIENT_ID = process.env.STRAVA_CLIENT_ID;
const STRAVA_CLIENT_SECRET = process.env.STRAVA_CLIENT_SECRET;

passport.serializeUser(function (user, done) {
  done(null, user);
});

passport.deserializeUser(function (obj, done) {
  done(null, obj);
});

passport.use(
  new StravaStrategy(
    {
      clientID: STRAVA_CLIENT_ID,
      clientSecret: STRAVA_CLIENT_SECRET,
      callbackURL: "/auth/strava/callback",
    },
    function (accessToken, refreshToken, profile, done) {
      process.nextTick(function () {
        return done(null, profile);
      });
    }
  )
);

app.use(logger("combined"));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.methodOverride());
app.use(cookieSession({ secret: "keyboard cat" }));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);

const SCOPES = "read,activity:read_all,read_all";

app.get(
  "/auth/strava",
  passport.authenticate("strava", { scope: SCOPES }),
  function (req, res) {
    // The request will be redirected to Strava for authentication, so this
    // function will not be called.
  }
);

app.get(
  "/auth/strava/callback",
  passport.authenticate("strava", {
    scope: SCOPES,
    failureRedirect: "/login",
  }),
  function (req, res) {
    res.redirect("https://statz.onrender.com");
  }
);

app.get("/api/athlete", async (req, res) => {
  fetch(
    `https://www.strava.com/api/v3/athlete?access_token=${
      req.user?.token ?? ""
    }`
  )
    .then((response) => {
      if (response.ok) {
        return response.json();
      }
      res.status(response.status).json({ error: response.statusText });
      throw new Error(`${response.status} - ${response.statusText}`);
    })
    .then((data) => res.json(data))
    .catch((error) => console.error({ error }));
});

app.get("/api/activities", async function (req, res) {
  if (!req.user) {
    res.json({ error: "Not authenticated" });
  }

  let page = 1;
  let activities = [];

  while (true) {
    const activitiesPromise = await fetch(
      `https://www.strava.com/api/v3/athlete/activities?per_page=30&page=${page}&access_token=${req.user.token}`
    );
    const activitiesData = await activitiesPromise.json();
    page += 1;
    activities = [...activities, ...activitiesData];
    logger({ page });
    if (activitiesData.length < 30) {
      return res.json(activities);
    }
  }
});

app.get("/api/ping", function (req, res) {
  res.send("pong");
});

const listener = app.listen(process.env.PORT || 8080, () => {
  console.log(`Your app is listening on port ${listener.address().port}`);
});

Client API calls:

import axios from 'axios';
import { Activity, Athlete } from '../models/Strava';

const BASE_URL = 'https://statz-api.onrender.com';

export const getAthlete = async (): Promise<Athlete> => {
  return axios.get(`${BASE_URL}/api/athlete`, { withCredentials: true }).then(({ data }) => data);
};

export const getActivities = async (): Promise<Activity[]> => {
  return axios
    .get(`${BASE_URL}/api/activities`, { withCredentials: true })
    .then(({ data }) => data);
};

Authorization component:

export function Authorization() {
  const login = () => {
    window.open('https://statz-api.onrender.com/auth/strava', '_self');
  };
  return (
    <Button onClick={login} variant="outlined">

    </Button>
  );
}


问:
Python lru_cache nested decorator
I want to basically ignore a dict parameter in a method that want to decorate with functools.lru_cache.

This is the code I have written so far:

import functools

class BlackBox:
    """All BlackBoxes are the same."""
    def __init__(self, contents):
        self._contents = contents

    @property
    def contents(self):
        return self._contents

    def __eq__(self, other):
        return isinstance(other, type(self))

    def __hash__(self):
        return hash(type(self))

def lru_cache_ignore(func):
    lru_decorator = functools.lru_cache(maxsize=2048)

    @functools.wraps(func)
    def wrapper_decorator(self, arg1, *args, **kwargs):

        @lru_decorator
        def helper(arg1_w: BlackBox, *args, **kwargs):
            print(f"Cache miss {arg1_w} {args} {kwargs}")
            # unpack the first argument from Blackbox
            original_arg = arg1_w.contents
            # Invoke the user function seamlessly
            return func(self, original_arg, *args, **kwargs)

        boxed_arg = BlackBox(arg1)
        print(helper)
        print(helper.__wrapped__)
        return helper(boxed_arg, *args, **kwargs)

    return wrapper_decorator
```
<p>The intention of the usage is clear in the unit tests as follow:</p>
<pre class="lang-py prettyprint-override"><code>def test_actual_function_is_called():
    my_mock = MagicMock()

    class A:
        @lru_cache_ignore
        def my_fun(self, dict_arg, str_arg):
            my_mock.call_fun(dict_arg, str_arg)

    A().my_fun({}, 'test')
    my_mock.call_fun.assert_called_once_with({}, 'test')

def test_second_call_is_cached():
    my_mock = MagicMock()
    my_mock.call_fun.return_value = [1]

    class A:
        @lru_cache_ignore
        def my_fun(self, dict_arg, str_arg):
            return my_mock.call_fun(dict_arg, str_arg)
    a = A()
    first_result = a.my_fun({}, 'test')
    second_result = a.my_fun({}, 'test')

    my_mock.call_fun.assert_called_once_with({}, 'test')

    assert first_result == second_result
</code>```

The issue is that the second test does not pass. The decorated function is called twice even though the input is the same.

This is the pytest output:

[CPython38-test] msg = "Expected 'call_fun' to be called once. Called 2 times.\nCalls: [call({}, 'test'), call({}, 'test')]."
[CPython38-test]
[CPython38-test]     def assert_called_once_with(_mock_self, *args, **kwargs):
[CPython38-test]         """assert that the mock was called exactly once and that that call was
[CPython38-test]         with the specified arguments."""
[CPython38-test]         self = _mock_self
[CPython38-test]         if not self.call_count == 1:
[CPython38-test]             msg = ("Expected '%s' to be called once. Called %s times.%s"
[CPython38-test]                    % (self._mock_name or 'mock',
[CPython38-test]                       self.call_count,
[CPython38-test]                       self._calls_repr()))
[CPython38-test] >           raise AssertionError(msg)
[CPython38-test] E           AssertionError: Expected 'call_fun' to be called once. Called 2 times.
[CPython38-test] E           Calls: [call({}, 'test'), call({}, 'test')].
[CPython38-test]
[CPython38-test] /.../mock.py:956: AssertionError
[CPython38-test] ----------------------------- Captured stdout call -----------------------------
[CPython38-test] <functools._lru_cache_wrapper object at 0x7f8eacf31430>
[CPython38-test] <function lru_cache_ignore.<locals>.wrapper_decorator.<locals>.helper at 0x7f8eacf27e50>
[CPython38-test] Cache miss <ads.adapter.rule_engine.lru_utils.BlackBox object at 0x7f8eacb7e8e0> ('test',) {}
[CPython38-test] <functools._lru_cache_wrapper object at 0x7f8eacf31430>
[CPython38-test] <function lru_cache_ignore.<locals>.wrapper_decorator.<locals>.helper at 0x7f8eacf27e50>
[CPython38-test] Cache miss <ads.adapter.rule_engine.lru_utils.BlackBox object at 0x7f8eacb7e8e0> ('test',) {}
```

I can see that the functions that are invoked in the decorator are the same. What am I missing here?
I have adapted the answer from this other post

Thank you!

Title: Python lru_cache nested decorator

Body:
I want to basically ignore a dict parameter in a method that want to decorate with functools.lru_cache.

This is the code I have written so far:

import functools

class BlackBox:
    """All BlackBoxes are the same."""
    def __init__(self, contents):
        self._contents = contents

    @property
    def contents(self):
        return self._contents

    def __eq__(self, other):
        return isinstance(other, type(self))

    def __hash__(self):
        return hash(type(self))

def lru_cache_ignore(func):
    lru_decorator = functools.lru_cache(maxsize=2048)

    @functools.wraps(func)
    def wrapper_decorator(self, arg1, *args, **kwargs):

        @lru_decorator
        def helper(arg1_w: BlackBox, *args, **kwargs):
            print(f"Cache miss {arg1_w} {args} {kwargs}")
            # unpack the first argument from Blackbox
            original_arg = arg1_w.contents
            # Invoke the user function seamlessly
            return func(self, original_arg, *args, **kwargs)

        boxed_arg = BlackBox(arg1)
        print(helper)
        print(helper.__wrapped__)
        return helper(boxed_arg, *args, **kwargs)

    return wrapper_decorator

The intention of the usage is clear in the unit tests as follow:

def test_actual_function_is_called():
    my_mock = MagicMock()

    class A:
        @lru_cache_ignore
        def my_fun(self, dict_arg, str_arg):
            my_mock.call_fun(dict_arg, str_arg)

    A().my_fun({}, 'test')
    my_mock.call_fun.assert_called_once_with({}, 'test')

def test_second_call_is_cached():
    my_mock = MagicMock()
    my_mock.call_fun.return_value = [1]

    class A:
        @lru_cache_ignore
        def my_fun(self, dict_arg, str_arg):
            return my_mock.call_fun(dict_arg, str_arg)
    a = A()
    first_result = a.my_fun({}, 'test')
    second_result = a.my_fun({}, 'test')

    my_mock.call_fun.assert_called_once_with({}, 'test')

    assert first_result == second_result

The issue is that the second test does not pass. The decorated function is called twice even though the input is the same.

This is the pytest output:

[CPython38-test] msg = "Expected 'call_fun' to be called once. Called 2 times.\nCalls: [call({}, 'test'), call({}, 'test')]."
[CPython38-test]
[CPython38-test]     def assert_called_once_with(_mock_self, *args, **kwargs):
[CPython38-test]         """assert that the mock was called exactly once and that that call was
[CPython38-test]         with the specified arguments."""
[CPython38-test]         self = _mock_self
[CPython38-test]         if not self.call_count == 1:
[CPython38-test]             msg = ("Expected '%s' to be called once. Called %s times.%s"
[CPython38-test]                    % (self._mock_name or 'mock',
[CPython38-test]                       self.call_count,
[CPython38-test]                       self._calls_repr()))
[CPython38-test] >           raise AssertionError(msg)
[CPython38-test] E           AssertionError: Expected 'call_fun' to be called once. Called 2 times.
[CPython38-test] E           Calls: [call({}, 'test'), call({}, 'test')].
[CPython38-test]
[CPython38-test] /.../mock.py:956: AssertionError
[CPython38-test] ----------------------------- Captured stdout call -----------------------------
[CPython38-test] <functools._lru_cache_wrapper object at 0x7f8eacf31430>
[CPython38-test] <function lru_cache_ignore.<locals>.wrapper_decorator.<locals>.helper at 0x7f8eacf27e50>
[CPython38-test] Cache miss <ads.adapter.rule_engine.lru_utils.BlackBox object at 0x7f8eacb7e8e0> ('test',) {}
[CPython38-test] <functools._lru_cache_wrapper object at 0x7f8eacf31430>
[CPython38-test] <function lru_cache_ignore.<locals>.wrapper_decorator.<locals>.helper at 0x7f8eacf27e50>
[CPython38-test] Cache miss <ads.adapter.rule_engine.lru_utils.BlackBox object at 0x7f8eacb7e8e0> ('test',) {}

I can see that the functions that are invoked in the decorator are the same. What am I missing here?
I have adapted the answer from this other post

Thank you!


问:
Is it possible to setup unmanaged DLL to generate memory dump files?
I have a Console C# application that's calling into an unmanaged C DLL to perform calculations. The C DLL generates Access Violation exceptions at times and I want to capture the memory dumps.  I use the code below to setup the C DLL to generate the memory dump files.  My problem is that the SolverExceptionHandler function never gets called.  Do I need to setup the memory dump files' generation in the C# .EXE or am I doing something wrong in the C code below?</p>
```<code>#include <windows.h>
#include <minidumpapiset.h>
#include <errhandlingapi.h>
#include <ExtStruct.h>
#include <string.h>
#include <fileapi.h>
#include <processthreadsapi.h>
#include <stdio.h>

static const WCHAR MemoryDumpFileDirectory[] = L"\\MemoryDumpFiles";

LONG WINAPI SolverExceptionHandler(EXCEPTION_POINTERS* ExceptionInfo)
{
    printf("Entered SolverExceptionHandler\n");

    WCHAR memoryDumpFileName[MAX_PATH_LEN + 1];
    wcscpy_s(memoryDumpFileName, MAX_PATH_LEN, MemoryDumpFileDirectory);
    wcscat_s(memoryDumpFileName, MAX_PATH_LEN, L"\\");
    wcscat_s(memoryDumpFileName, MAX_PATH_LEN, L"DumpFileXXXXXX");

    HANDLE hFile = CreateFile(
        (LPCWSTR) memoryDumpFileName,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    MINIDUMP_EXCEPTION_INFORMATION mei;
    mei.ThreadId = GetCurrentThreadId();
    mei.ClientPointers = TRUE;
    mei.ExceptionPointers = ExceptionInfo;
    bool success = MiniDumpWriteDump(
        GetCurrentProcess(),
        GetCurrentProcessId(),
        hFile,
        MiniDumpNormal,
        &mei,
        NULL,
        NULL);

    wprintf(L"SolverExceptionHandler saved Memory Dump into the [%] file. Success: %s", memoryDumpFileName, success ? "True" : "False");

    return EXCEPTION_EXECUTE_HANDLER;
}

BOOL WINAPI DllMain(HINSTANCE hDllInstance, DWORD dwReason, LPVOID lpReserved)
{
    switch (dwReason)
    {
        case DLL_PROCESS_ATTACH:
            printf("Attaching the SolverExceptionHandler\n");
            SetLastError(0);
            SetUnhandledExceptionFilter(SolverExceptionHandler);
            printf("Did attach the SolverExceptionHandler. GetLastError: %d\n", GetLastError());
            break;
        default:
            break;
    }

    return TRUE;
}
</code>```

Body:
I have a Console C# application that's calling into an unmanaged C DLL to perform calculations. The C DLL generates Access Violation exceptions at times and I want to capture the memory dumps.  I use the code below to setup the C DLL to generate the memory dump files.  My problem is that the SolverExceptionHandler function never gets called.  Do I need to setup the memory dump files' generation in the C# .EXE or am I doing something wrong in the C code below?

#include <windows.h>
#include <minidumpapiset.h>
#include <errhandlingapi.h>
#include <ExtStruct.h>
#include <string.h>
#include <fileapi.h>
#include <processthreadsapi.h>
#include <stdio.h>

static const WCHAR MemoryDumpFileDirectory[] = L"\\MemoryDumpFiles";

LONG WINAPI SolverExceptionHandler(EXCEPTION_POINTERS* ExceptionInfo)
{
    printf("Entered SolverExceptionHandler\n");

    WCHAR memoryDumpFileName[MAX_PATH_LEN + 1];
    wcscpy_s(memoryDumpFileName, MAX_PATH_LEN, MemoryDumpFileDirectory);
    wcscat_s(memoryDumpFileName, MAX_PATH_LEN, L"\\");
    wcscat_s(memoryDumpFileName, MAX_PATH_LEN, L"DumpFileXXXXXX");

    HANDLE hFile = CreateFile(
        (LPCWSTR) memoryDumpFileName,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    MINIDUMP_EXCEPTION_INFORMATION mei;
    mei.ThreadId = GetCurrentThreadId();
    mei.ClientPointers = TRUE;
    mei.ExceptionPointers = ExceptionInfo;
    bool success = MiniDumpWriteDump(
        GetCurrentProcess(),
        GetCurrentProcessId(),
        hFile,
        MiniDumpNormal,
        &mei,
        NULL,
        NULL);

    wprintf(L"SolverExceptionHandler saved Memory Dump into the [%] file. Success: %s", memoryDumpFileName, success ? "True" : "False");

    return EXCEPTION_EXECUTE_HANDLER;
}

BOOL WINAPI DllMain(HINSTANCE hDllInstance, DWORD dwReason, LPVOID lpReserved)
{
    switch (dwReason)
    {
        case DLL_PROCESS_ATTACH:
            printf("Attaching the SolverExceptionHandler\n");
            SetLastError(0);
            SetUnhandledExceptionFilter(SolverExceptionHandler);
            printf("Did attach the SolverExceptionHandler. GetLastError: %d\n", GetLastError());
            break;
        default:
            break;
    }

    return TRUE;
}


问:
Can't access a dotnet API due to an SPA Proxy
I'm serving a React app through dotnet's UseStaticFiles. this allows the front-end to communicate with the front-end by simply fetching to localhost. Now I would like to deploy a 2nd front-end outside this close-loop, problem is, I can't access the underlying backend since all requests are being handled by its front-end.

Say I would like to access /users, then the front-end would try to match that route, if it doesn't find it, then it will display a 404 error page.

I tried mapping the controller routes under api like so.

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "api/{controller}/{action=Index}/{id?}"
    );
});
```

BUt I am still unable to access the API under the /api base path.

Body:
I'm serving a React app through dotnet's UseStaticFiles. this allows the front-end to communicate with the front-end by simply fetching to localhost. Now I would like to deploy a 2nd front-end outside this close-loop, problem is, I can't access the underlying backend since all requests are being handled by its front-end.

Say I would like to access /users, then the front-end would try to match that route, if it doesn't find it, then it will display a 404 error page.

I tried mapping the controller routes under api like so.

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "api/{controller}/{action=Index}/{id?}"
    );
});

BUt I am still unable to access the API under the /api base path.


问:
How to save grouped multiple checkboxes into database in asp.net core

how can I save values of checkboxes for each user as against the many checked boxes


问:
Ninja build system: refer to multiple targets with a variable
I have the following build.ninja file

```<code>$ cat build.ninja
rule mycmd
  command = echo $in

build target1: mycmd
build target2: mycmd

build target3: mycmd target1 target2

targets = target1 target2
build target4: mycmd $targets
</code>```

ninja target3 works correctly. However,  ninja target4 raises error

```<code>$ ninja target4
ninja: error: 'target1 target2', needed by 'target4', missing and no known rule to make it
</code>```

Looks like it thinks target1 target2 is a single target name, rather than two separate targets.

How should I solve this problem?

Body:
I have the following build.ninja file

$ cat build.ninja
rule mycmd
  command = echo $in

build target1: mycmd
build target2: mycmd

build target3: mycmd target1 target2

targets = target1 target2
build target4: mycmd $targets

ninja target3 works correctly. However,  ninja target4 raises error

$ ninja target4
ninja: error: 'target1 target2', needed by 'target4', missing and no known rule to make it

Looks like it thinks target1 target2 is a single target name, rather than two separate targets.

How should I solve this problem?


问:
Discord py boost embed
I have this code, but I want it to be sent in a specific channel and to be an embed instead of a simple message, solutions? (sorry for the bad english I'm spanish)

@client.event
async def on_message(message):
    if "MessageType.premium_guild" in str(message.type):
        await message.channel.send("Gracias por boostear")
```

Title: Discord py boost embed


问:
Rolling average and slope using Pandas
I have a data table with three columns: Minutes, Group, Reading

```<code>Minutes,Group,Reading
10,A,1
20,A,9
30,A,30
40,A,40
50,A,42
60,A,44
70,A,45
10,B,1
20,B,8
30,B,23
40,B,32
50,B,41
60,B,46
70,B,50
80,A,0.9
90,A,2.4
100,A,8
110,A,15
80,B,20
90,B,21
100,B,20
</code>```

My goal is to calculate a rolling average for minutes and reading, and rolling slope. I should be able to specify the window size and step size.

This is what I have so far:

```<code>
def calc_slope(x):
    slope = np.polyfit(range(len(x)), x, 1)[0]
    return slope

result2 = df.groupby('Group', sort=True).rolling(window=10, center=True, on='Minutes',  min_periods=2).apply(calc_slope)
</code>```

The output should look something like this table:

```<code>Group,Avg Minutes,Avg Reading, Slope
A,20,21,1.2
A,30,25,2.1
....
</code>```

It would be great if I could also plot all those points so that each point will be plotted as X=avg minutes, Y=avg reading, and a line with a slope equal to the rolling slope at that point with the length equal to the window size.

Thank you for any help!

Title: Rolling average and slope using Pandas

Body:
I have a data table with three columns: Minutes, Group, Reading

Minutes,Group,Reading
10,A,1
20,A,9
30,A,30
40,A,40
50,A,42
60,A,44
70,A,45
10,B,1
20,B,8
30,B,23
40,B,32
50,B,41
60,B,46
70,B,50
80,A,0.9
90,A,2.4
100,A,8
110,A,15
80,B,20
90,B,21
100,B,20

My goal is to calculate a rolling average for minutes and reading, and rolling slope. I should be able to specify the window size and step size.

This is what I have so far:

def calc_slope(x):
    slope = np.polyfit(range(len(x)), x, 1)[0]
    return slope

result2 = df.groupby('Group', sort=True).rolling(window=10, center=True, on='Minutes',  min_periods=2).apply(calc_slope)

The output should look something like this table:

Group,Avg Minutes,Avg Reading, Slope
A,20,21,1.2
A,30,25,2.1
....

It would be great if I could also plot all those points so that each point will be plotted as X=avg minutes, Y=avg reading, and a line with a slope equal to the rolling slope at that point with the length equal to the window size.

Thank you for any help!


问:
Navbar Tabs Not Stacking Vertically in Mobile-Size Screen
I'm brand new to CSS so please forgive me if I'm missing something obvious. I've spent several hours on this and searched this website and have not been able to resolve my issue.

I have a Shiny (R) app that I am trying to add some custom styling to using CSS. I have been making change to the Navbar, which I am happy with so far. However, something in my CSS is causing undesirable behavior in mobile-sized screens, where the tabs of the navbar do not stack vertically and overlap with the main content:

Compared to the default, which is what I would like:

I know this is something related to my CSS because when I disable it this issue is resolved. I have tried many things and nothing so far has helped, I was wondering if someone might be able to point out in my CSS where I have introduced this problem and how I might resolve it.

Thanks in advance. CSS:

```<code>/*=============NAVBAR STYLING=============*/
/*Entire navbar*/
.navbar.navbar-default.navbar-static-top{
  background-color:white;
  height:60px;
  /*margin: 10px;*/
  margin:0px;
}

/*All navbar tabs*/
.navbar-default .navbar-nav>li>a {
  /*Sets consistent height for navbar tabs, must be !important*/
  height:60px !important;
  justify-content:center;
  align-items:center;
  display:flex;
}

/*Style the *active* navbar tab*/
.navbar-default .navbar-nav>.active>a{
  /*Make the active tab darker in color w/ white text*/
  background-color:#676767!important;
  color:white!important;
  border-radius: 10% / 50%;
}

.nav-link {
  position:absolute;
}

/*======Screen-width specific styling=======*/
@media (min-width:1276), (max-width: 1426px) {
  .navbar.navbar-default .navbar-nav > li > a {
    font-size: 12px;
  }
  h2 {
    font-size:26px;
  }
  .hometext {
    font-size: 18px !important;
  }
  ol {
    font-size: 18px !important;
  }
}

@media only screen and (min-width:768px) and (max-width:1275px) {
  .navbar.navbar-default .navbar-nav > li > a {
    font-size: 11px !important;
    margin-top:10px !important;
  }
  h2 {
    font-size:24px;
  }
  .hometext {
    font-size: 16px !important;
  }
  ol {
    font-size: 16px !important;
    }
  }
    /* Next two classes keeps the navbar tabs on the same line in smaller windows */
  .min-width{
      overflow-x:auto
    }
  ul.nav{
    display:inline-flex
  }
}

@media only screen and (min-width:1px) and (max-width:767px) {
  .navbar-default .navbar-collapse > li{
    display: block!important;
  }
  .navbar-default .navbar-collapse > li > a {
    float: none!important;
  /*Removes grey line above tabs (overlaps with logo)*/
  .navbar-default .navbar-collapse{
    border-color:transparent;
  }
}

</code>```

Body:
I'm brand new to CSS so please forgive me if I'm missing something obvious. I've spent several hours on this and searched this website and have not been able to resolve my issue.

I have a Shiny (R) app that I am trying to add some custom styling to using CSS. I have been making change to the Navbar, which I am happy with so far. However, something in my CSS is causing undesirable behavior in mobile-sized screens, where the tabs of the navbar do not stack vertically and overlap with the main content:

Compared to the default, which is what I would like:

I know this is something related to my CSS because when I disable it this issue is resolved. I have tried many things and nothing so far has helped, I was wondering if someone might be able to point out in my CSS where I have introduced this problem and how I might resolve it.

Thanks in advance. CSS:

/*=============NAVBAR STYLING=============*/
/*Entire navbar*/
.navbar.navbar-default.navbar-static-top{
  background-color:white;
  height:60px;
  /*margin: 10px;*/
  margin:0px;
}

/*All navbar tabs*/
.navbar-default .navbar-nav>li>a {
  /*Sets consistent height for navbar tabs, must be !important*/
  height:60px !important;
  justify-content:center;
  align-items:center;
  display:flex;
}

/*Style the *active* navbar tab*/
.navbar-default .navbar-nav>.active>a{
  /*Make the active tab darker in color w/ white text*/
  background-color:#676767!important;
  color:white!important;
  border-radius: 10% / 50%;
}

.nav-link {
  position:absolute;
}

/*======Screen-width specific styling=======*/
@media (min-width:1276), (max-width: 1426px) {
  .navbar.navbar-default .navbar-nav > li > a {
    font-size: 12px;
  }
  h2 {
    font-size:26px;
  }
  .hometext {
    font-size: 18px !important;
  }
  ol {
    font-size: 18px !important;
  }
}

@media only screen and (min-width:768px) and (max-width:1275px) {
  .navbar.navbar-default .navbar-nav > li > a {
    font-size: 11px !important;
    margin-top:10px !important;
  }
  h2 {
    font-size:24px;
  }
  .hometext {
    font-size: 16px !important;
  }
  ol {
    font-size: 16px !important;
    }
  }
    /* Next two classes keeps the navbar tabs on the same line in smaller windows */
  .min-width{
      overflow-x:auto
    }
  ul.nav{
    display:inline-flex
  }
}

@media only screen and (min-width:1px) and (max-width:767px) {
  .navbar-default .navbar-collapse > li{
    display: block!important;
  }
  .navbar-default .navbar-collapse > li > a {
    float: none!important;
  /*Removes grey line above tabs (overlaps with logo)*/
  .navbar-default .navbar-collapse{
    border-color:transparent;
  }
}


问:
Searchkick reindexing not picking up queued changes
I'm following along with the Queuing section of the README which seems to work fine until I begin a re-index operation. I'm noticing that I don't seem to get new changes that have happened after the re-index is started. For example if I have a model Product:

class Product < ApplicationRecord
  searchkick callbacks: :queue
end
```

Product.reindex(mode: :async)

While the index is still reindexing:

new_product = Product.create

Searchkick::ProcessQueueJob.perform_now(class_name: "Product")

new_product is not included in the new index

What is the best way to handle this so that new_product will be included in the new index?

Body:
I'm following along with the Queuing section of the README which seems to work fine until I begin a re-index operation. I'm noticing that I don't seem to get new changes that have happened after the re-index is started. For example if I have a model Product:

class Product < ApplicationRecord
  searchkick callbacks: :queue
end

Product.reindex(mode: :async)

While the index is still reindexing:

new_product = Product.create

Searchkick::ProcessQueueJob.perform_now(class_name: "Product")

new_product is not included in the new index

What is the best way to handle this so that new_product will be included in the new index?


问:
trying to run a 3axes gantry in sequence mode similar to the sequence of serial data sent
i want to run my 3 axes gantry(stm32) in sequence similar to the sequence of serial data sent from the pc but this is not happening. no data is lost as all the axes perform their task but in wrong sequence.

this is the recieve complete callback loop

```<code>`void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{

    if(r != ',')
    {
        Rx[i++] = r;
    }
    else
    {
        strncpy(s1,Rx,i);
        Home = strrchr(s1, 'H');
        StringX = strrchr(s1, 'X');
        StringY = strrchr(s1, 'Y');
        StringZ = strrchr(s1, 'Z');
        StringW = strrchr(s1, 'W');

        if(Home[0] == 'H' && Home[1] == 'O' && Home[2] == 'M' && Home[3] == 'E')
        {
            homeValue = 1;
        }

        if(StringX[0] == 'X')
        {
            MoveX= substr(StringX,1,8);
            MoveXvalue =  (atol(MoveX))/100;
            SpeedX = substr(StringX,8,12);
            SpeedXvalue = atol(SpeedX);
            insertintoQueue_X(MoveXvalue, SpeedXvalue);
            insertintoSequenceQueue (1);

        }

        if(StringY[0] == 'Y')
        {
            MoveY= substr(StringY,1,8);
            MoveYvalue =  (atol(MoveY))/100;
            SpeedY = substr(StringY,8,12);
            SpeedYvalue = atol(SpeedY);
            insertintoQueue_Y(MoveYvalue, SpeedYvalue);
            insertintoSequenceQueue (2);
///goes on for other axes
/

        i = 0;

    }
}`
</code>```

i tried sequencing these received cmds with below loop(posting only for one axis)

```<code>`void insertintoQueue_X (int j, int l)
{
    uint8_t queuefull[] = "XFULL";
    if(countXmove == 256 || countXspeed == 256 )
    {
        HAL_UART_Transmit_IT (&huart1, queuefull, sizeof (queuefull));
    }

    Xmovequeue[countXmove] = j ;
    countXmove++;
    Xspeedqueue[countXspeed] = l;
    countXspeed++;

}

void removefromQueue_X()
{
    //uint8_t queueEmpty[] = "XEMPTY";
    /*if(countXmove == 0 || countXspeed == 0)
       {
           HAL_UART_Transmit_IT (&huart2, queueEmpty, sizeof (queueEmpty));
       }*/
     currentXmoveelement = Xmovequeue[0];
     currentXspeedelement = Xspeedqueue[0];

     for(int i = 0; i < countXmove - 1; i++)
     {
         Xmovequeue[i] = Xmovequeue[i+1];
         Xspeedqueue[i] = Xspeedqueue[i+1];
     }
}`
</code>```

while loop is as below

```<code>`  removefromSequenceQueue();//only called once in while loop

        for(int p = 0; p < countXmove  ; p++)
        {
            if(currentSequence == 1)
            {

            removefromQueue_X();
            if(currentXmoveelement >0)
            {

            //uint8_t Xmovvestatus[] = "XMMM";

              if(CurrentXposition != currentXmoveelement)
              {

                  if(CurrentXposition > currentXmoveelement )
                  {
                      currentmoveX = CurrentXposition - currentXmoveelement;
                    motorMoveTo(currentmoveX,0,currentXspeedelement,20,SMSPR_X,SMS_X,SMDPR_X,SMD_X);

                  }
                  else if(CurrentXposition < currentXmoveelement )
                  {
                      // HAL_UART_Transmit_IT (&huart1, Xmovvestatus, sizeof (Xmovvestatus));
                     currentmoveX = currentXmoveelement - CurrentXposition ;
                      motorMoveTo(currentmoveX,1,currentXspeedelement,20,SMSPR_X,SMS_X,SMDPR_X,SMD_X);

                  }

                 CurrentXposition = currentXmoveelement;
                 currentXmoveelement = 0;
                 currentmoveX = 0;
                 MoveXvalue=0;
              }
            }
            }
          }
</code>```

Body:
i want to run my 3 axes gantry(stm32) in sequence similar to the sequence of serial data sent from the pc but this is not happening. no data is lost as all the axes perform their task but in wrong sequence.

this is the recieve complete callback loop

`void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{

    if(r != ',')
    {
        Rx[i++] = r;
    }
    else
    {
        strncpy(s1,Rx,i);
        Home = strrchr(s1, 'H');
        StringX = strrchr(s1, 'X');
        StringY = strrchr(s1, 'Y');
        StringZ = strrchr(s1, 'Z');
        StringW = strrchr(s1, 'W');

        if(Home[0] == 'H' && Home[1] == 'O' && Home[2] == 'M' && Home[3] == 'E')
        {
            homeValue = 1;
        }

        if(StringX[0] == 'X')
        {
            MoveX= substr(StringX,1,8);
            MoveXvalue =  (atol(MoveX))/100;
            SpeedX = substr(StringX,8,12);
            SpeedXvalue = atol(SpeedX);
            insertintoQueue_X(MoveXvalue, SpeedXvalue);
            insertintoSequenceQueue (1);

        }

        if(StringY[0] == 'Y')
        {
            MoveY= substr(StringY,1,8);
            MoveYvalue =  (atol(MoveY))/100;
            SpeedY = substr(StringY,8,12);
            SpeedYvalue = atol(SpeedY);
            insertintoQueue_Y(MoveYvalue, SpeedYvalue);
            insertintoSequenceQueue (2);
///goes on for other axes
/

        i = 0;

    }
}`

i tried sequencing these received cmds with below loop(posting only for one axis)

`void insertintoQueue_X (int j, int l)
{
    uint8_t queuefull[] = "XFULL";
    if(countXmove == 256 || countXspeed == 256 )
    {
        HAL_UART_Transmit_IT (&huart1, queuefull, sizeof (queuefull));
    }

    Xmovequeue[countXmove] = j ;
    countXmove++;
    Xspeedqueue[countXspeed] = l;
    countXspeed++;

}

void removefromQueue_X()
{
    //uint8_t queueEmpty[] = "XEMPTY";
    /*if(countXmove == 0 || countXspeed == 0)
       {
           HAL_UART_Transmit_IT (&huart2, queueEmpty, sizeof (queueEmpty));
       }*/
     currentXmoveelement = Xmovequeue[0];
     currentXspeedelement = Xspeedqueue[0];

     for(int i = 0; i < countXmove - 1; i++)
     {
         Xmovequeue[i] = Xmovequeue[i+1];
         Xspeedqueue[i] = Xspeedqueue[i+1];
     }
}`

while loop is as below

`  removefromSequenceQueue();//only called once in while loop

        for(int p = 0; p < countXmove  ; p++)
        {
            if(currentSequence == 1)
            {

            removefromQueue_X();
            if(currentXmoveelement >0)
            {

            //uint8_t Xmovvestatus[] = "XMMM";

              if(CurrentXposition != currentXmoveelement)
              {

                  if(CurrentXposition > currentXmoveelement )
                  {
                      currentmoveX = CurrentXposition - currentXmoveelement;
                    motorMoveTo(currentmoveX,0,currentXspeedelement,20,SMSPR_X,SMS_X,SMDPR_X,SMD_X);

                  }
                  else if(CurrentXposition < currentXmoveelement )
                  {
                      // HAL_UART_Transmit_IT (&huart1, Xmovvestatus, sizeof (Xmovvestatus));
                     currentmoveX = currentXmoveelement - CurrentXposition ;
                      motorMoveTo(currentmoveX,1,currentXspeedelement,20,SMSPR_X,SMS_X,SMDPR_X,SMD_X);

                  }

                 CurrentXposition = currentXmoveelement;
                 currentXmoveelement = 0;
                 currentmoveX = 0;
                 MoveXvalue=0;
              }
            }
            }
          }


问:
How to resolve Default parser issue?
Hi i am getting the following error when trying to run a post req. Are there any dependencies that are missing ?

Exception in thread "main" java.lang.IllegalStateException: Cannot invoke the path method because no content-type was present in the response and no default parser has been set.

You can specify a default parser using e.g.:
RestAssured.defaultParser = Parser.JSON;

```<code>     String a= "80820221";
        String body= "{\n" +
                "    \"request\": {\n" +
                "        \"id\": \"" + a + "\",\n" +
                "        \"id2\": \"800002400434\",\n" +
                "        \"id3\": \"\",\n" +
                "        \"id4\": \"WEB\"\n" +
                "    }\n" +
                "}";
        RequestSpecBuilder reqBuilder = new RequestSpecBuilder();
        // Setting Base URI
        reqBuilder.setBaseUri(base);
        // Setting Base Path
        reqBuilder.setBasePath(basePath");
           reqBuilder.setContentType(ContentType.JSON);

        // Getting RequestSpecification reference using builder() method
        RequestSpecification reqSpec = reqBuilder.build();
        Response response = RestAssured.given(reqSpec).body(body).log().all().when().post().then().log().all().extract().response();
int status = response.getStatusCode();
System.out.println(status);
**String successMessage = response.getBody().path("response.status")**;
System.out.println(successMessage);

it is giving errror in the above line

i am expecting 200 response. In postman it is giving 200 but in script it is returning 400 and unable to get the response body
</code>```

Title: How to resolve Default parser issue?

Body:
Hi i am getting the following error when trying to run a post req. Are there any dependencies that are missing ?

Exception in thread "main" java.lang.IllegalStateException: Cannot invoke the path method because no content-type was present in the response and no default parser has been set.

You can specify a default parser using e.g.:
RestAssured.defaultParser = Parser.JSON;

     String a= "80820221";
        String body= "{\n" +
                "    \"request\": {\n" +
                "        \"id\": \"" + a + "\",\n" +
                "        \"id2\": \"800002400434\",\n" +
                "        \"id3\": \"\",\n" +
                "        \"id4\": \"WEB\"\n" +
                "    }\n" +
                "}";
        RequestSpecBuilder reqBuilder = new RequestSpecBuilder();
        // Setting Base URI
        reqBuilder.setBaseUri(base);
        // Setting Base Path
        reqBuilder.setBasePath(basePath");
           reqBuilder.setContentType(ContentType.JSON);

        // Getting RequestSpecification reference using builder() method
        RequestSpecification reqSpec = reqBuilder.build();
        Response response = RestAssured.given(reqSpec).body(body).log().all().when().post().then().log().all().extract().response();
int status = response.getStatusCode();
System.out.println(status);
**String successMessage = response.getBody().path("response.status")**;
System.out.println(successMessage);

it is giving errror in the above line

i am expecting 200 response. In postman it is giving 200 but in script it is returning 400 and unable to get the response body


问:
Blazor Devextreme control grid validation
I have a blazor grid control at which I'm trying to add a special validation for to prevent a person from entering a value in a particular column where a row already has that value.
I cannot use a general data annotation because those only apply against values of that particular instance.

I have tried examples from their edit row validation samples. https://demos.devexpress.com/blazor/Grid/EditData/EditRowValidation but have had no luck.
I tried the  but it seems like it over-rides the data annotations.


问:
How to Mute/UnMute using Teams in-Meetings app
does Toggling incoming audio feature still in preview state ?
I was tring to to build Teams meeting app according to this documentation

https://learn.microsoft.com/en-us/microsoftteams/platform/apps-in-teams-meetings/meeting-apps-apis?tabs=dotnet#toggle-incoming-audio

But App didn't work for one of Tenant which was Teams Developer preview enabled one


问:
how to insert @client.event in @client.command just new to discord py program i hava a question about this followingcode

is it possiple to insert client.event on client.command

this is my code please explain this issue and add your code for future reference

```<code>import discord
from discord.ext import commands
import random
import asyncio
from random import randint
import aiohttp
from discord.ext.commands.core import command

client = commands.Bot(command_prefix = '')
client.remove_command('help')

@client.event
async def on_ready():
print('we are logged in {0.user}'.format(client))

@client.command()
async def say(ctx, *, args):
    embed=discord.Embed(title= args, color=0x3700ff)
    await ctx.send(embed=embed)

@client.event
async def on_message(message):
  if message.content.startswith('stop'):
      await message.channel.send('start')

@client.run("my token")

</code>```

am try to understand why @client.event on_message will not working on @client.command

disclimer:- am noob on code so need a professionals help so thank about the helper

Body:
is it possiple to insert client.event on client.command

this is my code please explain this issue and add your code for future reference

import discord
from discord.ext import commands
import random
import asyncio
from random import randint
import aiohttp
from discord.ext.commands.core import command

client = commands.Bot(command_prefix = '')
client.remove_command('help')

@client.event
async def on_ready():
print('we are logged in {0.user}'.format(client))

@client.command()
async def say(ctx, *, args):
    embed=discord.Embed(title= args, color=0x3700ff)
    await ctx.send(embed=embed)

@client.event
async def on_message(message):
  if message.content.startswith('stop'):
      await message.channel.send('start')

@client.run("my token")

am try to understand why @client.event on_message will not working on @client.command

disclimer:- am noob on code so need a professionals help so thank about the helper


问:
I was creating a virtual mouse and I keep getting this error. I have tried with autopy and with pyautogui but in both cases it gives me same error
This is the error I'm getting right now and I just can't figure out what the problem is.

```<code>INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
Traceback (most recent call last):
  File "C:\AIproject\virMouse.py", line 18, in <module>
    lmList, bbox = detector.findPosition(img)
ValueError: not enough values to unpack (expected 2, got 0)

Process finished with exit code 1
</code>```

Here is my code for the virtual mouse program that I have written so far.

```<code>import cv2
import numpy as np
import time
import HTmodule as htm
import autopy

wCam, hCam = 640, 480

cap = cv2.VideoCapture(0)
cap.set(3, wCam)
cap.set(4, hCam)
pTime = 0
detector = htm.handDetector(maxHands=1)

while True:
     success, img = cap.read()
     img = detector.findHands(img)
     lmList, bbox = detector.findPosition(img)

     cTime = time.time()
     fps = 1 / (cTime - pTime)
     pTime = cTime
     cv2.putText(img, f'FPS:{(int(fps))}', (5, 30), cv2.FONT_HERSHEY_DUPLEX, 1, (204, 0, 0), 2)
     cv2.imshow("Image", img)
     cv2.waitKey(1)
</code>```

And here is the code for the hand tracking module that I wrote.

```<code>import cv2
import mediapipe as mp
import time

class handDetector():
    def __init__(self, mode=False, maxHands=2,modelC=1, detectionCon=0.5, trackCon=0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.modelC = modelC
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.modelC, self.detectionCon, self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

    def findHands(self, img, draw=True):
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(imgRGB)
        # print(result.multi_hand_landmarks)

        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)

        return img
    def findPosition(self, img, handNo=0, draw=True):
        lmList=[]
        if self.results.multi_hand_landmarks:
            myHand = self.results.multi_hand_landmarks[handNo]
            for id, lm in enumerate(myHand.landmark):
                # print(id,lm)
                h, w, c = img.shape
                cx, cy = int(lm.x * w), int(lm.y * h)
                # print(id, cx, cy)
                lmList.append([id, cx, cy])
                # if id == 0:
                if draw:
                    cv2.circle(img, (cx, cy), 3, (229, 25, 66), cv2.FILLED)
        return lmList

def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()
    while True:
        success, img = cap.read()
        img = detector.findHands(img)
        lmList = detector.findPosition(img, draw=False)
        # print(lmList) # PRINTS THE LIST OF LANDMARKS
        if len(lmList) != 0:
            print(lmList[4])
        cTime = time.time()
        fps = 1 / (cTime - pTime)
        pTime = cTime

        cv2.putText(img, f'FPS:{(int(fps))}', (5, 30), cv2.FONT_HERSHEY_DUPLEX, 1, (9, 9, 255), 1)

        cv2.imshow("Image", img)
        cv2.waitKey(1)

if __name__ == "__main__":
    main()
</code>```

I don't think it has anything to do with autopy I think it has something to do with findPosition() function but I can't figure out what it is. I just started studying computer vision with python and decided to make this project for my practice but this error I can't seem to debug. Any kind of help would be greatly appreciated. Thankyou very much.

Body:
This is the error I'm getting right now and I just can't figure out what the problem is.

INFO: Created TensorFlow Lite XNNPACK delegate for CPU.
Traceback (most recent call last):
  File "C:\AIproject\virMouse.py", line 18, in <module>
    lmList, bbox = detector.findPosition(img)
ValueError: not enough values to unpack (expected 2, got 0)

Process finished with exit code 1

Here is my code for the virtual mouse program that I have written so far.

import cv2
import numpy as np
import time
import HTmodule as htm
import autopy

wCam, hCam = 640, 480

cap = cv2.VideoCapture(0)
cap.set(3, wCam)
cap.set(4, hCam)
pTime = 0
detector = htm.handDetector(maxHands=1)

while True:
     success, img = cap.read()
     img = detector.findHands(img)
     lmList, bbox = detector.findPosition(img)

     cTime = time.time()
     fps = 1 / (cTime - pTime)
     pTime = cTime
     cv2.putText(img, f'FPS:{(int(fps))}', (5, 30), cv2.FONT_HERSHEY_DUPLEX, 1, (204, 0, 0), 2)
     cv2.imshow("Image", img)
     cv2.waitKey(1)

And here is the code for the hand tracking module that I wrote.

import cv2
import mediapipe as mp
import time

class handDetector():
    def __init__(self, mode=False, maxHands=2,modelC=1, detectionCon=0.5, trackCon=0.5):
        self.mode = mode
        self.maxHands = maxHands
        self.modelC = modelC
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands
        self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.modelC, self.detectionCon, self.trackCon)
        self.mpDraw = mp.solutions.drawing_utils

    def findHands(self, img, draw=True):
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.hands.process(imgRGB)
        # print(result.multi_hand_landmarks)

        if self.results.multi_hand_landmarks:
            for handLms in self.results.multi_hand_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS)

        return img
    def findPosition(self, img, handNo=0, draw=True):
        lmList=[]
        if self.results.multi_hand_landmarks:
            myHand = self.results.multi_hand_landmarks[handNo]
            for id, lm in enumerate(myHand.landmark):
                # print(id,lm)
                h, w, c = img.shape
                cx, cy = int(lm.x * w), int(lm.y * h)
                # print(id, cx, cy)
                lmList.append([id, cx, cy])
                # if id == 0:
                if draw:
                    cv2.circle(img, (cx, cy), 3, (229, 25, 66), cv2.FILLED)
        return lmList

def main():
    pTime = 0
    cTime = 0
    cap = cv2.VideoCapture(0)
    detector = handDetector()
    while True:
        success, img = cap.read()
        img = detector.findHands(img)
        lmList = detector.findPosition(img, draw=False)
        # print(lmList) # PRINTS THE LIST OF LANDMARKS
        if len(lmList) != 0:
            print(lmList[4])
        cTime = time.time()
        fps = 1 / (cTime - pTime)
        pTime = cTime

        cv2.putText(img, f'FPS:{(int(fps))}', (5, 30), cv2.FONT_HERSHEY_DUPLEX, 1, (9, 9, 255), 1)

        cv2.imshow("Image", img)
        cv2.waitKey(1)

if __name__ == "__main__":
    main()

I don't think it has anything to do with autopy I think it has something to do with findPosition() function but I can't figure out what it is. I just started studying computer vision with python and decided to make this project for my practice but this error I can't seem to debug. Any kind of help would be greatly appreciated. Thankyou very much.


问:
How to make too bold text in jetpack compose?
While using Jetpack Compose Text() I am not able to change the fontWeight more than FontWeight.W600 and FontWeight.W500. Others than these two none gets applied like FontWeight.W700, FontWeight.Bold , FontWeight(550) etc. I was trying to create text  with too dark but not able to achieve at all. Note: I am using Roboto font from google downloadable font and material theme 3.

One example of text code:-

```<code>Text(
   modifier = Modifier.padding(top = 4.dp),
   text = "This should be too bold",
   style = MaterialTheme.typography.titleSmall,
   fontWeight = FontWeight.Black,
)
</code>```

Body:
While using Jetpack Compose Text() I am not able to change the fontWeight more than FontWeight.W600 and FontWeight.W500. Others than these two none gets applied like FontWeight.W700, FontWeight.Bold , FontWeight(550) etc. I was trying to create text  with too dark but not able to achieve at all. Note: I am using Roboto font from google downloadable font and material theme 3.

One example of text code:-

Text(
   modifier = Modifier.padding(top = 4.dp),
   text = "This should be too bold",
   style = MaterialTheme.typography.titleSmall,
   fontWeight = FontWeight.Black,
)


问:
How to access the each string characters from TextEditingController and provide the values to each characters in Flutter?
I want to access the each characters of TextEditing Controller and provide values to each characters in Flutter. For example, I had written Everest in Textediting field, I want to access each characters E,v,e,r,e,s,t and provide E=1, v=1, e=1, r=1, e=1, s=1, t=1. I want to assign the values like this and do some calculation?

I tried by doing controller.text[0] which provide me the value of first index but when i try to assign value (controller.text[0]=1.toString()) the [0] shows error and can't assign the value?


问:
No Implementation for the org.camunda.bpm.engine.rest.spi.ProcessEngineProvider spi found on classpath
I have implemented a sample Camunda Springboot application. It works fine with Internet connection. But when deployed into VDI without internet, The application is not coming up. It shows the error while startup as below

"No Implementation for the org.camunda.bpm.engine.rest.api.ProcessEngineProvider spi found on classpath"

Camunda-Springboot and BOM version-7.17.0
Springboot version-2.6.7

I have tried to implement the interface and creating service for Java service loader. Still no luck.


问:
How to store pdf resume files in the file system and save link in mysql in a laravel project
I am working on a project in laravel that stores the query and informations about organisation staffs. For that, I need to store their photo and resume in pdf format. I am using Image Intervention package to store the photo of the staff. But Don't know how to store the pdf file in the database. So is there any packages to store the pdf into the database with laravel? Or any other way of storing in the FS and store the name or link of it into the DB?

```<code>I wrote a function that will store all the information in the database.
But the program throughs an error of 302. And I looked into the Intervention documentation and it says that it doesn't saves '.pdf' documents.

public function addStaff(Request $request){
        $request->validate([
            'staff_name'=>['required'],
            'post'=>['required'],
            'email'=>['required'],
            'birthDate'=>['required','date'],
            'birth_Mark'=>['string'],
            'perm_address'=>['required'],
            'address'=>['required'],
            'contact'=>['required'],
            'alt_contact'=>['required'],
            'service_status'=>['required'],
            'joining_date'=>['required','date'],
            'NID'=>['required','string'],
            'passport'=>['string'],
            'resume'=>['required','string'],
            'photo'=>['required','string'],
            'gender'=>['required'],
        ]);

        // photo part starts

        if($request->resume){
            $resume = $request->file('resume');
            $resumeName = rand().".".$resume->getClientOriginalExtension();
            $resumeLocation = public_path("backend/imageStore/staff/resume/".$resumeName);
            File::make($resume)->save($resumeLocation);

            if($request->photo){
                $picture = $request->file('photo');
                $pcustomname = rand().".".$picture->getClientOriginalExtension();
                $location = public_path("backend/imageStore/staff/photo/".$pcustomname);
                Image::make($picture)->save($location);

                Staff::create([
                    'staff_name' =>$request->staff_name,
                    'post' =>$request->post,
                    'email' =>$request->email,
                    'birthDate' =>$request->birthDate,
                    'birth_Mark' =>$request->birth_Mark,
                    'perm_address' =>$request->perm_address,
                    'address' =>$request->address,
                    'contact' =>$request->contact,
                    'alt_contact' =>$request->alt_contact,
                    'service_status' =>$request->service_status,
                    'joining_date' =>$request->joining_date,
                    'NID' =>$request->NID,
                    'passport' =>$request->passport,
                    'resume' =>$resumeName,
                    'photo' =>$pcustomname,
                    'gender' =>$request->gender,
                ]);
                return back();
            }

        }

        // return back();
    }
</code>```

Body:
I am working on a project in laravel that stores the query and informations about organisation staffs. For that, I need to store their photo and resume in pdf format. I am using Image Intervention package to store the photo of the staff. But Don't know how to store the pdf file in the database. So is there any packages to store the pdf into the database with laravel? Or any other way of storing in the FS and store the name or link of it into the DB?

I wrote a function that will store all the information in the database.
But the program throughs an error of 302. And I looked into the Intervention documentation and it says that it doesn't saves '.pdf' documents.

public function addStaff(Request $request){
        $request->validate([
            'staff_name'=>['required'],
            'post'=>['required'],
            'email'=>['required'],
            'birthDate'=>['required','date'],
            'birth_Mark'=>['string'],
            'perm_address'=>['required'],
            'address'=>['required'],
            'contact'=>['required'],
            'alt_contact'=>['required'],
            'service_status'=>['required'],
            'joining_date'=>['required','date'],
            'NID'=>['required','string'],
            'passport'=>['string'],
            'resume'=>['required','string'],
            'photo'=>['required','string'],
            'gender'=>['required'],
        ]);

        // photo part starts

        if($request->resume){
            $resume = $request->file('resume');
            $resumeName = rand().".".$resume->getClientOriginalExtension();
            $resumeLocation = public_path("backend/imageStore/staff/resume/".$resumeName);
            File::make($resume)->save($resumeLocation);

            if($request->photo){
                $picture = $request->file('photo');
                $pcustomname = rand().".".$picture->getClientOriginalExtension();
                $location = public_path("backend/imageStore/staff/photo/".$pcustomname);
                Image::make($picture)->save($location);

                Staff::create([
                    'staff_name' =>$request->staff_name,
                    'post' =>$request->post,
                    'email' =>$request->email,
                    'birthDate' =>$request->birthDate,
                    'birth_Mark' =>$request->birth_Mark,
                    'perm_address' =>$request->perm_address,
                    'address' =>$request->address,
                    'contact' =>$request->contact,
                    'alt_contact' =>$request->alt_contact,
                    'service_status' =>$request->service_status,
                    'joining_date' =>$request->joining_date,
                    'NID' =>$request->NID,
                    'passport' =>$request->passport,
                    'resume' =>$resumeName,
                    'photo' =>$pcustomname,
                    'gender' =>$request->gender,
                ]);
                return back();
            }

        }

        // return back();
    }


问:
Use ngx-webcam on http application
As per the Prerequisites available in the site, ngx-webcam can only be used using https:// or on localhost. I have an intranet based application which will be running on local IP and no https will be used. For capturing the webcam image, I have used ngx-webcam module and now it is not working on http://IP:PORT

Important: Your app must be served on a secure context using https://
or on localhost, for modern browsers to permit WebRTC/UserMedia
access.

It will be really helpful if someone can suggest any other module to capture the webcam image as data image url or if possible ngx-webcam can be used in http mode for Angular 12 application

Title: Use ngx-webcam on http application