问:
Tensorflow gpu training fails with OOM when the exact code runs on an older computer with no issues
I recently got a new laptop with an inbuilt graphics card from Intel and one extra from Nvidia.
I installed cuda and drivers of this version
| NVIDIA-SMI 510.39.01    Driver Version: 510.39.01    CUDA Version: 11.6

I also have Tensorflow 2.7.
I am trying to run a network that was working perfectly on my old computer, more or less being taken from this repository:

https://github.com/zhixuhao/unet.git

but I get the following warning when i initiate the model:

```<code>2022-02-02 14:47:03.039319: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:939] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
</code>```

and when i actually try to train the model it runs OOM without training at all. (Error message simplified for character limit)

```<code>2022-02-02 14:50:00.390958: W tensorflow/core/common_runtime/bfc_allocator.cc:275] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.02GiB with freed_by_count=0. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available.
2022-02-02 14:50:00.391000: W tensorflow/core/common_runtime/bfc_allocator.cc:275] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.02GiB with freed_by_count=0. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available.
2022-02-02 14:50:02.218748: W tensorflow/core/common_runtime/bfc_allocator.cc:275]
2022-02-02 14:50:12.687857: I tensorflow/core/common_runtime/bfc_allocator.cc:1066] InUse at 7f16daade200 of size 524288 next 155
2022-02-02 14:50:12.687865: I tensorflow/core/common_runtime/bfc_allocator.cc:1066] InUse at 7f16dab5e200 of size 1179648 next 157
2022-02-02 14:50:12.688670: I tensorflow/core/common_runtime/bfc_allocator.cc:1078] Sum Total of in-use chunks: 5.17GiB
2022-02-02 14:50:12.688678: I tensorflow/core/common_runtime/bfc_allocator.cc:1080] total_region_allocated_bytes_: 6427901952 memory_limit_: 6427901952 available bytes: 0 curr_region_allocation_bytes_: 12855803904
2022-02-02 14:50:12.688695: I tensorflow/core/common_runtime/bfc_allocator.cc:1086] Stats:
Limit:                      6427901952
InUse:                      5546784512
MaxInUse:                   6126439680
NumAllocs:                         645
MaxAllocSize:               3716153344
Reserved:                            0
PeakReserved:                        0
LargestFreeBlock:                    0

2022-02-02 14:50:12.688718: W tensorflow/core/common_runtime/bfc_allocator.cc:474] **********************************************************_____******************************_______
2022-02-02 14:50:12.688819: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at conv_grad_input_ops.cc:335 : RESOURCE_EXHAUSTED: OOM when allocating tensor with shape[1,128,1024,1024] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
---------------------------------------------------------------------------
ResourceExhaustedError                    Traceback (most recent call last)
Input In [7], in <module>
----> 1 model.fit_generator(myGene,steps_per_epoch=300,epochs=10,callbacks=[model_checkpoint])

File ~/.local/lib/python3.8/site-packages/keras/engine/training.py:2016, in Model.fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   2005 """Fits the model on data yielded batch-by-batch by a Python generator.
   2006
   2007 DEPRECATED:
   2008   `Model.fit` now supports generators, so there is no longer any need to use
   2009   this endpoint.
   2010 """
   2011 warnings.warn(
   2012     '`Model.fit_generator` is deprecated and '
   2013     'will be removed in a future version. '
   2014     'Please use `Model.fit`, which supports generators.',
   2015     stacklevel=2)
-> 2016 return self.fit(
   2017     generator,
   2018     steps_per_epoch=steps_per_epoch,
   2019     epochs=epochs,
   2020     verbose=verbose,
   2021     callbacks=callbacks,
   2022     validation_data=validation_data,
   2023     validation_steps=validation_steps,
   2024     validation_freq=validation_freq,
   2025     class_weight=class_weight,
   2026     max_queue_size=max_queue_size,
   2027     workers=workers,
   2028     use_multiprocessing=use_multiprocessing,
   2029     shuffle=shuffle,
   2030     initial_epoch=initial_epoch)

File ~/.local/lib/python3.8/site-packages/keras/utils/traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e:  # pylint: disable=broad-except
     66   filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67   raise e.with_traceback(filtered_tb) from None
     68 finally:
     69   del filtered_tb

File ~/.local/lib/python3.8/site-packages/tensorflow/python/eager/execute.py:58, in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     56 try:
     57   ctx.ensure_initialized()
---> 58   tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
     59                                       inputs, attrs, num_outputs)
     60 except core._NotOkStatusException as e:
     61   if name is not None:

ResourceExhaustedError:  OOM when allocating tensor with shape[1,128,1024,1024] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
         [[node gradient_tape/model/conv2d_20/Conv2D/Conv2DBackpropInput
 (defined at /home/john/.local/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py:464)
]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. This isn't available when running in Eager mode.
 [Op:__inference_train_function_3020]

Errors may have originated from an input operation.
Input Source operations connected to node gradient_tape/model/conv2d_20/Conv2D/Conv2DBackpropInput:
In[0] gradient_tape/model/conv2d_20/Conv2D/ShapeN:
In[1] model/conv2d_20/Conv2D/ReadVariableOp (defined at /home/john/.local/lib/python3.8/site-packages/keras/layers/convolutional/base_conv.py:224)
In[2] gradient_tape/model/conv2d_20/ReluGrad:

Operation defined at: (most recent call last)
>>>   File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
>>>     return _run_code(code, main_globals, None,
>>>
>>>   File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
>>>     exec(code, run_globals)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel_launcher.py", line 16, in <module>
>>>     app.launch_new_instance()
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/traitlets/config/application.py", line 846, in launch_instance
>>>     app.start()
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/kernelapp.py", line 677, in start
>>>     self.io_loop.start()
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/tornado/platform/asyncio.py", line 199, in start
>>>     self.asyncio_loop.run_forever()
>>>
>>>   File "/usr/lib/python3.8/asyncio/base_events.py", line 570, in run_forever
>>>     self._run_once()
>>>
>>>   File "/usr/lib/python3.8/asyncio/base_events.py", line 1859, in _run_once
>>>     handle._run()
>>>
>>>   File "/usr/lib/python3.8/asyncio/events.py", line 81, in _run
>>>     self._context.run(self._callback, *self._args)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 461, in dispatch_queue
>>>     await self.process_one()
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 450, in process_one
>>>     await dispatch(*args)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 357, in dispatch_shell
>>>     await result
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 652, in execute_request
>>>     reply_content = await reply_content
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/ipkernel.py", line 353, in do_execute
>>>     res = shell.run_cell(code, store_history=store_history, silent=silent)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/zmqshell.py", line 532, in run_cell
>>>     return super().run_cell(*args, **kwargs)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 2768, in run_cell
>>>     result = self._run_cell(
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 2814, in _run_cell
>>>     return runner(coro)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/async_helpers.py", line 129, in _pseudo_sync_runner
>>>     coro.send(None)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3012, in run_cell_async
>>>     has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3191, in run_ast_nodes
>>>     if await self.run_code(code, result, async_=asy):
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3251, in run_code
>>>     exec(code_obj, self.user_global_ns, self.user_ns)
>>>
>>>   File "/tmp/ipykernel_20858/1898079364.py", line 1, in <module>
>>>     model.fit_generator(myGene,steps_per_epoch=300,epochs=10,callbacks=[model_checkpoint])
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 2016, in fit_generator
>>>     return self.fit(
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 64, in error_handler
>>>     return fn(*args, **kwargs)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 1216, in fit
>>>     tmp_logs = self.train_function(iterator)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 878, in train_function
>>>     return step_function(self, iterator)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 867, in step_function
>>>     outputs = model.distribute_strategy.run(run_step, args=(data,))
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 860, in run_step
>>>     outputs = model.train_step(data)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 816, in train_step
>>>     self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py", line 530, in minimize
>>>     grads_and_vars = self._compute_gradients(
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py", line 583, in _compute_gradients
>>>     grads_and_vars = self._get_gradients(tape, loss, var_list, grad_loss)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py", line 464, in _get_gradients
>>>     grads = tape.gradient(loss, var_list, grad_loss)
>>>

</code>```

Does anyone have any ideas what could have caused this/how to resolve it?
best

答:
Try setting a hard limit on the total GPU memory as shown in this guide and let us know if it works.

```<code>import tensorflow as tf
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.compat.v1.Session(config=config)
</code>```

also check here

Body:
I recently got a new laptop with an inbuilt graphics card from Intel and one extra from Nvidia.
I installed cuda and drivers of this version
| NVIDIA-SMI 510.39.01    Driver Version: 510.39.01    CUDA Version: 11.6

I also have Tensorflow 2.7.
I am trying to run a network that was working perfectly on my old computer, more or less being taken from this repository:

https://github.com/zhixuhao/unet.git

but I get the following warning when i initiate the model:

2022-02-02 14:47:03.039319: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:939] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero

and when i actually try to train the model it runs OOM without training at all. (Error message simplified for character limit)

2022-02-02 14:50:00.390958: W tensorflow/core/common_runtime/bfc_allocator.cc:275] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.02GiB with freed_by_count=0. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available.
2022-02-02 14:50:00.391000: W tensorflow/core/common_runtime/bfc_allocator.cc:275] Allocator (GPU_0_bfc) ran out of memory trying to allocate 2.02GiB with freed_by_count=0. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available.
2022-02-02 14:50:02.218748: W tensorflow/core/common_runtime/bfc_allocator.cc:275]
2022-02-02 14:50:12.687857: I tensorflow/core/common_runtime/bfc_allocator.cc:1066] InUse at 7f16daade200 of size 524288 next 155
2022-02-02 14:50:12.687865: I tensorflow/core/common_runtime/bfc_allocator.cc:1066] InUse at 7f16dab5e200 of size 1179648 next 157
2022-02-02 14:50:12.688670: I tensorflow/core/common_runtime/bfc_allocator.cc:1078] Sum Total of in-use chunks: 5.17GiB
2022-02-02 14:50:12.688678: I tensorflow/core/common_runtime/bfc_allocator.cc:1080] total_region_allocated_bytes_: 6427901952 memory_limit_: 6427901952 available bytes: 0 curr_region_allocation_bytes_: 12855803904
2022-02-02 14:50:12.688695: I tensorflow/core/common_runtime/bfc_allocator.cc:1086] Stats:
Limit:                      6427901952
InUse:                      5546784512
MaxInUse:                   6126439680
NumAllocs:                         645
MaxAllocSize:               3716153344
Reserved:                            0
PeakReserved:                        0
LargestFreeBlock:                    0

2022-02-02 14:50:12.688718: W tensorflow/core/common_runtime/bfc_allocator.cc:474] **********************************************************_____******************************_______
2022-02-02 14:50:12.688819: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at conv_grad_input_ops.cc:335 : RESOURCE_EXHAUSTED: OOM when allocating tensor with shape[1,128,1024,1024] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
---------------------------------------------------------------------------
ResourceExhaustedError                    Traceback (most recent call last)
Input In [7], in <module>
----> 1 model.fit_generator(myGene,steps_per_epoch=300,epochs=10,callbacks=[model_checkpoint])

File ~/.local/lib/python3.8/site-packages/keras/engine/training.py:2016, in Model.fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, validation_freq, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   2005 """Fits the model on data yielded batch-by-batch by a Python generator.
   2006
   2007 DEPRECATED:
   2008   `Model.fit` now supports generators, so there is no longer any need to use
   2009   this endpoint.
   2010 """
   2011 warnings.warn(
   2012     '`Model.fit_generator` is deprecated and '
   2013     'will be removed in a future version. '
   2014     'Please use `Model.fit`, which supports generators.',
   2015     stacklevel=2)
-> 2016 return self.fit(
   2017     generator,
   2018     steps_per_epoch=steps_per_epoch,
   2019     epochs=epochs,
   2020     verbose=verbose,
   2021     callbacks=callbacks,
   2022     validation_data=validation_data,
   2023     validation_steps=validation_steps,
   2024     validation_freq=validation_freq,
   2025     class_weight=class_weight,
   2026     max_queue_size=max_queue_size,
   2027     workers=workers,
   2028     use_multiprocessing=use_multiprocessing,
   2029     shuffle=shuffle,
   2030     initial_epoch=initial_epoch)

File ~/.local/lib/python3.8/site-packages/keras/utils/traceback_utils.py:67, in filter_traceback.<locals>.error_handler(*args, **kwargs)
     65 except Exception as e:  # pylint: disable=broad-except
     66   filtered_tb = _process_traceback_frames(e.__traceback__)
---> 67   raise e.with_traceback(filtered_tb) from None
     68 finally:
     69   del filtered_tb

File ~/.local/lib/python3.8/site-packages/tensorflow/python/eager/execute.py:58, in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
     56 try:
     57   ctx.ensure_initialized()
---> 58   tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
     59                                       inputs, attrs, num_outputs)
     60 except core._NotOkStatusException as e:
     61   if name is not None:

ResourceExhaustedError:  OOM when allocating tensor with shape[1,128,1024,1024] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
         [[node gradient_tape/model/conv2d_20/Conv2D/Conv2DBackpropInput
 (defined at /home/john/.local/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py:464)
]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. This isn't available when running in Eager mode.
 [Op:__inference_train_function_3020]

Errors may have originated from an input operation.
Input Source operations connected to node gradient_tape/model/conv2d_20/Conv2D/Conv2DBackpropInput:
In[0] gradient_tape/model/conv2d_20/Conv2D/ShapeN:
In[1] model/conv2d_20/Conv2D/ReadVariableOp (defined at /home/john/.local/lib/python3.8/site-packages/keras/layers/convolutional/base_conv.py:224)
In[2] gradient_tape/model/conv2d_20/ReluGrad:

Operation defined at: (most recent call last)
>>>   File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
>>>     return _run_code(code, main_globals, None,
>>>
>>>   File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
>>>     exec(code, run_globals)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel_launcher.py", line 16, in <module>
>>>     app.launch_new_instance()
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/traitlets/config/application.py", line 846, in launch_instance
>>>     app.start()
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/kernelapp.py", line 677, in start
>>>     self.io_loop.start()
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/tornado/platform/asyncio.py", line 199, in start
>>>     self.asyncio_loop.run_forever()
>>>
>>>   File "/usr/lib/python3.8/asyncio/base_events.py", line 570, in run_forever
>>>     self._run_once()
>>>
>>>   File "/usr/lib/python3.8/asyncio/base_events.py", line 1859, in _run_once
>>>     handle._run()
>>>
>>>   File "/usr/lib/python3.8/asyncio/events.py", line 81, in _run
>>>     self._context.run(self._callback, *self._args)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 461, in dispatch_queue
>>>     await self.process_one()
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 450, in process_one
>>>     await dispatch(*args)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 357, in dispatch_shell
>>>     await result
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py", line 652, in execute_request
>>>     reply_content = await reply_content
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/ipkernel.py", line 353, in do_execute
>>>     res = shell.run_cell(code, store_history=store_history, silent=silent)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/ipykernel/zmqshell.py", line 532, in run_cell
>>>     return super().run_cell(*args, **kwargs)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 2768, in run_cell
>>>     result = self._run_cell(
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 2814, in _run_cell
>>>     return runner(coro)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/async_helpers.py", line 129, in _pseudo_sync_runner
>>>     coro.send(None)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3012, in run_cell_async
>>>     has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3191, in run_ast_nodes
>>>     if await self.run_code(code, result, async_=asy):
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3251, in run_code
>>>     exec(code_obj, self.user_global_ns, self.user_ns)
>>>
>>>   File "/tmp/ipykernel_20858/1898079364.py", line 1, in <module>
>>>     model.fit_generator(myGene,steps_per_epoch=300,epochs=10,callbacks=[model_checkpoint])
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 2016, in fit_generator
>>>     return self.fit(
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/utils/traceback_utils.py", line 64, in error_handler
>>>     return fn(*args, **kwargs)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 1216, in fit
>>>     tmp_logs = self.train_function(iterator)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 878, in train_function
>>>     return step_function(self, iterator)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 867, in step_function
>>>     outputs = model.distribute_strategy.run(run_step, args=(data,))
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 860, in run_step
>>>     outputs = model.train_step(data)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/engine/training.py", line 816, in train_step
>>>     self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py", line 530, in minimize
>>>     grads_and_vars = self._compute_gradients(
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py", line 583, in _compute_gradients
>>>     grads_and_vars = self._get_gradients(tape, loss, var_list, grad_loss)
>>>
>>>   File "/home/john/.local/lib/python3.8/site-packages/keras/optimizer_v2/optimizer_v2.py", line 464, in _get_gradients
>>>     grads = tape.gradient(loss, var_list, grad_loss)
>>>

Does anyone have any ideas what could have caused this/how to resolve it?
best

Body:
Try setting a hard limit on the total GPU memory as shown in this guide and let us know if it works.

import tensorflow as tf
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.compat.v1.Session(config=config)

also check here


来源: stackexchange

问:
ReactJS w/ Inertia - calling onClick function multiple times

Problem

I am attempting to make a dynamic content box to incrementally fill in a form in ReactJS. As part of this, I simply want a box/area that changes its content when the user clicks 'Next' or 'Prev'.

The problem I appear to be facing is that the onClick method is getting called multiple times (obviously - I've only clicked it once).

I have a MWE below to demonstrate the problem I'm facing.

```<code>import React, {useEffect, useState} from 'react';

export default function Test () {

    const [section, setSection] = useState(1);
    const [sectionContent, setSectionContent] = useState();

    useEffect( ()=>{
        console.log("ENTRY useEffect");
        if (section == 1) {
            setSectionContent(<div>Details</div>);
        }
        else if(section == 2){
            setSectionContent(<div>Advanced Details</div>);
        }
        else if(section == 3){
            setSectionContent(<div>Super Advanced Details</div>);
        }
        console.log("EXIT useEffect");
    },[section]);

    function gotoPrevSection(){
        console.log("ENTRY gotoPrevSection");
        if(section == 1){
            setSection(1);
        }
        else if(section == 2){
            setSection(2);
        }
        console.log("EXIT gotoPrevSection");
    }

    function gotoNextSection(){
        console.log("ENTRY gotoNextSection");
        if (section == 1) {
            setSection(2);
        }else if(section == 2){
            setSection(3);
        }
        console.log("EXIT gotoNextSection");
    }

    return (
        <>
            {sectionContent}
            <div>
                <button onClick={() => gotoPrevSection()}>
                    Prev
                </button>
                <button onClick={() => gotoNextSection()}>
                    Next
                </button>
            </div>
        </>
    );
}
</code>```

Opening the page, we have 'Details' and the 'Prev' and 'Next' buttons. When I click 'Next' I skip all the way to the 'Super Advanced Details' section - skipping the middle section !
The console log looks like this:

```<code>[Log] ENTRY gotoNextSection
[Log] EXIT gotoNextSection
[Log] ENTRY useEffect
[Log] EXIT useEffect
[Log] ENTRY gotoNextSection
[Log] EXIT gotoNextSection
[Log] ENTRY useEffect
[Log] EXIT useEffect
[Log] ENTRY gotoNextSection
[Log] EXIT gotoNextSection
</code>```

You can clearly see that the 'gotoNextSection' method is called three times even though it's only clicked once. What am I doing wrong ?

What I've tried

I am aware of the need for the onClick portion to look like onClick={() => function()} rather than just onClick=function(). This isn't the problem - the method isn't getting called straight away otherwise the details page wouldn't be static and stable - it's only when clicking this occurs.

I am React 17.0.2.

The Inertia init looks like:

```<code>createInertiaApp({
  title: title => `${title} - ${appName}`,
  resolve: name => require(`./Pages/Test.js`),
  setup({ el, App, props }) {
    return render(<App {...props} />, el);
  },
});
</code>```

What is going on here? Is this a React bug in the newer version ?

答:
I've updated your functions as below, and introduce a totalSection constant.

In addition, you should be using useMemo instead of useEffect for your type of use (you save one additional render).

Codesandbox

```<code>import React, { useEffect, useState, useMemo } from "react";

const totalSections = 3;
export default function Test() {
  const [section, setSection] = useState(1);

  const sectionContent = useMemo(() => {
    if (section == 1) {
      return(<div>Details</div>);
    } else if (section == 2) {
      return(<div>Advanced Details</div>);
    } else if (section == 3) {
      return(<div>Super Advanced Details</div>);
    }

  },[section])

  function gotoPrevSection() {
    console.log("ENTRY gotoPrevSection");

    setSection((prev) => (prev === 1 ? totalSections : prev - 1));
    console.log("EXIT gotoPrevSection");
  }

  function gotoNextSection() {
    console.log("ENTRY gotoNextSection");
    setSection((prev) => (prev === totalSections ? 1 : prev + 1));

    console.log("EXIT gotoNextSection");
  }

  return (
    <>
      {sectionContent}
      <div>
        <button onClick={() => gotoPrevSection()}>Prev</button>
        <button onClick={() => gotoNextSection()}>Next</button>
      </div>
    </>
  );
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Problem

I am attempting to make a dynamic content box to incrementally fill in a form in ReactJS. As part of this, I simply want a box/area that changes its content when the user clicks 'Next' or 'Prev'.

The problem I appear to be facing is that the onClick method is getting called multiple times (obviously - I've only clicked it once).

I have a MWE below to demonstrate the problem I'm facing.

import React, {useEffect, useState} from 'react';

export default function Test () {

    const [section, setSection] = useState(1);
    const [sectionContent, setSectionContent] = useState();

    useEffect( ()=>{
        console.log("ENTRY useEffect");
        if (section == 1) {
            setSectionContent(
Details
);
        }
        else if(section == 2){
            setSectionContent(
Advanced Details
);
        }
        else if(section == 3){
            setSectionContent(
Super Advanced Details
);
        }
        console.log("EXIT useEffect");
    },[section]);

    function gotoPrevSection(){
        console.log("ENTRY gotoPrevSection");
        if(section == 1){
            setSection(1);
        }
        else if(section == 2){
            setSection(2);
        }
        console.log("EXIT gotoPrevSection");
    }

    function gotoNextSection(){
        console.log("ENTRY gotoNextSection");
        if (section == 1) {
            setSection(2);
        }else if(section == 2){
            setSection(3);
        }
        console.log("EXIT gotoNextSection");
    }

    return (
        <>
            {sectionContent}

                <button onClick={() => gotoPrevSection()}>
                    Prev
                </button>
                <button onClick={() => gotoNextSection()}>
                    Next
                </button>

        </>
    );
}

Opening the page, we have 'Details' and the 'Prev' and 'Next' buttons. When I click 'Next' I skip all the way to the 'Super Advanced Details' section - skipping the middle section !
The console log looks like this:

[Log] ENTRY gotoNextSection
[Log] EXIT gotoNextSection
[Log] ENTRY useEffect
[Log] EXIT useEffect
[Log] ENTRY gotoNextSection
[Log] EXIT gotoNextSection
[Log] ENTRY useEffect
[Log] EXIT useEffect
[Log] ENTRY gotoNextSection
[Log] EXIT gotoNextSection

You can clearly see that the 'gotoNextSection' method is called three times even though it's only clicked once. What am I doing wrong ?

What I've tried

I am aware of the need for the onClick portion to look like onClick={() => function()} rather than just onClick=function(). This isn't the problem - the method isn't getting called straight away otherwise the details page wouldn't be static and stable - it's only when clicking this occurs.

I am React 17.0.2.

The Inertia init looks like:

createInertiaApp({
  title: title => `${title} - ${appName}`,
  resolve: name => require(`./Pages/Test.js`),
  setup({ el, App, props }) {
    return render(<App {...props} />, el);
  },
});

What is going on here? Is this a React bug in the newer version ?

Body:
I've updated your functions as below, and introduce a totalSection constant.

In addition, you should be using useMemo instead of useEffect for your type of use (you save one additional render).

Codesandbox

import React, { useEffect, useState, useMemo } from "react";

const totalSections = 3;
export default function Test() {
  const [section, setSection] = useState(1);

  const sectionContent = useMemo(() => {
    if (section == 1) {
      return(<div>Details</div>);
    } else if (section == 2) {
      return(<div>Advanced Details</div>);
    } else if (section == 3) {
      return(<div>Super Advanced Details</div>);
    }

  },[section])

  function gotoPrevSection() {
    console.log("ENTRY gotoPrevSection");

    setSection((prev) => (prev === 1 ? totalSections : prev - 1));
    console.log("EXIT gotoPrevSection");
  }

  function gotoNextSection() {
    console.log("ENTRY gotoNextSection");
    setSection((prev) => (prev === totalSections ? 1 : prev + 1));

    console.log("EXIT gotoNextSection");
  }

  return (
    <>
      {sectionContent}
      <div>
        <button onClick={() => gotoPrevSection()}>Prev</button>
        <button onClick={() => gotoNextSection()}>Next</button>
      </div>
    </>
  );
}


问:
Why is Tomcat doubling my log lines in the catalina.out logfile?
Every time I look at Tomcat's catalina.out log file, I see double lines for every log entry.  Why is this happening?  Has this happen before to any Java (Tomcat) users?

答:
It most likely has something to do with the order the jars are loaded.  On an older project I was on, this would happen all the time, the solution was to reorder the jars in the "perfect" order and things would fix themselves.

It might not just be multiple log4j's, but commons-logging, slf4j, etc.  Try rearranging them, but without seeing your classpath ordering, it's hard to help any further.

OwnerDisplayName: Geo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eddie

OwnerDisplayName: Greg Noe


问:
Proper use of `MockedProvider` on searching query
How to solve this error? when I run yarn test I receive this error:

Invariant Violation: Could not find "client" in the context or passed
in as an option. Wrap the root component in an , or
pass an ApolloClientApolloClient instance in via options.

gql

```<code>export const GETLOCATIONNAME = gql`
  query FindLocationByAddress($placeSearch: InputEsriGeoCode!) {
    findLocationByAddress(placeSearch: $placeSearch) {
      name
      address {
        street1
        street2
        city
        state
        zipCode
        country
      }
      geoCode {
        longitude
        latitude
      }
    }
  }
`;
</code>```

location.test.js

```<code>it('should render location', async () => {
  const location = {
    request: {
      query: GETLOCATIONNAME,
      variables: {
        placeSearch: {
          address: inputString,
        },
      },
    },
    result: {
      data: {"data":{"findLocationByAddress":[{"name":"Manila, First District NCR, National Capital Region, PHL","address":{"street1":"","street2":"","city":"Manila","state":"National Capital Region","zipCode":"","country":"PHL"},"geoCode":{"longitude":14.604870000000062,"latitude":120.9862700000001}}]}}
    },
  };

  const component = TestRenderer.create(
    <MockedProvider mocks={[location]} addTypename={false}>
      <LocationSearch name="Manila, First District NCR, National Capital Region, PHL" />
    </MockedProvider>,
  );

  await new Promise(resolve => setTimeout(resolve, 0));

  const p = component.root.findByType('p');
  expect(p.children.join('')).toContain('Location');
});
</code>```

resources https://www.apollographql.com/docs/react/development-testing/testing/

答:
Intended outcome:

Test a graphql component with MockedProvider

Actual outcome:

The first test with Loading works. The second where the result should be
hello world
 does not.

How to reproduce the issue:

Usual create-react-app with the following test in jest

import React from 'react'
import { mount } from 'enzyme'
import { MockedProvider } from 'react-apollo/test-utils'
import gql from 'graphql-tag'
import { graphql } from 'react-apollo'

const query = gql`
  query hello{
    hello
  }
`

const TestComp = props => {
  const { loading, hello } = props.data
  if (loading) {
    return
Loading

  }

  return
Hello {hello}

}

const TestCompHoc = graphql(query)(TestComp)

it('will render loading', () => {
  const mocks = [{ request: { query } }]
  const wrapper = mount(
    <MockedProvider mocks={mocks}>
      <TestCompHoc />
    </MockedProvider>
  )
  expect(wrapper).toContainReact(
Loading
)
})

it('will render data', async () => {
  const mocks = [
    {
      request: { query },
      result: { data: { hello: 'world' } }
    }
  ]
  const wrapper = mount(
    <MockedProvider mocks={mocks}>
      <TestCompHoc />
    </MockedProvider>
  )
  await new Promise(resolve => setTimeout(resolve))
  wrapper.update()
  expect(wrapper).toContainReact(
Hello world
)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

For More Information Click Here

Body:
How to solve this error? when I run yarn test I receive this error:

Invariant Violation: Could not find "client" in the context or passed
in as an option. Wrap the root component in an , or
pass an ApolloClientApolloClient instance in via options.

gql

export const GETLOCATIONNAME = gql`
  query FindLocationByAddress($placeSearch: InputEsriGeoCode!) {
    findLocationByAddress(placeSearch: $placeSearch) {
      name
      address {
        street1
        street2
        city
        state
        zipCode
        country
      }
      geoCode {
        longitude
        latitude
      }
    }
  }
`;

location.test.js

it('should render location', async () => {
  const location = {
    request: {
      query: GETLOCATIONNAME,
      variables: {
        placeSearch: {
          address: inputString,
        },
      },
    },
    result: {
      data: {"data":{"findLocationByAddress":[{"name":"Manila, First District NCR, National Capital Region, PHL","address":{"street1":"","street2":"","city":"Manila","state":"National Capital Region","zipCode":"","country":"PHL"},"geoCode":{"longitude":14.604870000000062,"latitude":120.9862700000001}}]}}
    },
  };

  const component = TestRenderer.create(
    <MockedProvider mocks={[location]} addTypename={false}>
      <LocationSearch name="Manila, First District NCR, National Capital Region, PHL" />
    </MockedProvider>,
  );

  await new Promise(resolve => setTimeout(resolve, 0));

  const p = component.root.findByType('p');
  expect(p.children.join('')).toContain('Location');
});

resources https://www.apollographql.com/docs/react/development-testing/testing/

Body:
Intended outcome:

Test a graphql component with MockedProvider

Actual outcome:

The first test with Loading works. The second where the result should be <h1>hello world<h1> does not.

How to reproduce the issue:

Usual create-react-app with the following test in jest

import React from 'react'
import { mount } from 'enzyme'
import { MockedProvider } from 'react-apollo/test-utils'
import gql from 'graphql-tag'
import { graphql } from 'react-apollo'

const query = gql`
  query hello{
    hello
  }
`

const TestComp = props => {
  const { loading, hello } = props.data
  if (loading) {
    return <h1>Loading</h1>
  }

  return <h1>Hello {hello}</h1>
}

const TestCompHoc = graphql(query)(TestComp)

it('will render loading', () => {
  const mocks = [{ request: { query } }]
  const wrapper = mount(
    <MockedProvider mocks={mocks}>
      <TestCompHoc />
    </MockedProvider>
  )
  expect(wrapper).toContainReact(<h1>Loading</h1>)
})

it('will render data', async () => {
  const mocks = [
    {
      request: { query },
      result: { data: { hello: 'world' } }
    }
  ]
  const wrapper = mount(
    <MockedProvider mocks={mocks}>
      <TestCompHoc />
    </MockedProvider>
  )
  await new Promise(resolve => setTimeout(resolve))
  wrapper.update()
  expect(wrapper).toContainReact(<h1>Hello world</h1>)
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

For More Information Click Here


问:
Testcafe tests are not executed on MacBook Big Sur with UnableToAccessScreenRecordingAPIError:
Testcafe basic test execution failed with an error on MachBook Air 11.6.3 (20G405) even after setting the permission for screen recording.

Steps to reproduce

Create a basic test

Run the test from the command line

testcafe chrome -e test_suite/tests/temp_test.ts

It prompts for permission to record the screen

4. Provide the required permission

Following error is thrown even after giving the permission.

```<code>Using locally installed version of TestCafe.
TestCafe requires permission to record the screen. Open 'System Preferences > Security & Privacy > Privacy > Screen Recording' and check 'TestCafe Browser Tools' in the application list.

Press any key to retry.
ERROR UnableToAccessScreenRecordingAPIError: The find-window process cannot access the Screen Recording API.

</code>```

答:
Try removing the .testcafe-browser-tools folder from your home directory. If this does not help, try executing the following command:

```<code>chmod +x "/Users/{user}/.testcafe-browser-tools/TestCafe Browser Tools.app/Contents/MacOS/testcafe-browser-tools"
</code>```

Also, if you are using the M1 chip, try installing Rosetta 2. If the problem still persists,  i suggest you create an issue in the TestCafe GitHub repository and add a sample project and a video to demonstrate how you reproduce it. Make sure that the callstack with the problem is also visible.

Body:
Testcafe basic test execution failed with an error on MachBook Air 11.6.3 (20G405) even after setting the permission for screen recording.

Steps to reproduce

Create a basic test

Run the test from the command line

testcafe chrome -e test_suite/tests/temp_test.ts

It prompts for permission to record the screen

4. Provide the required permission

Following error is thrown even after giving the permission.

Using locally installed version of TestCafe.
TestCafe requires permission to record the screen. Open 'System Preferences > Security & Privacy > Privacy > Screen Recording' and check 'TestCafe Browser Tools' in the application list.

Press any key to retry.
ERROR UnableToAccessScreenRecordingAPIError: The find-window process cannot access the Screen Recording API.

Body:
Try removing the .testcafe-browser-tools folder from your home directory. If this does not help, try executing the following command:

chmod +x "/Users/{user}/.testcafe-browser-tools/TestCafe Browser Tools.app/Contents/MacOS/testcafe-browser-tools"

Also, if you are using the M1 chip, try installing Rosetta 2. If the problem still persists,  i suggest you create an issue in the TestCafe GitHub repository and add a sample project and a video to demonstrate how you reproduce it. Make sure that the callstack with the problem is also visible.


问:
Exporting Pandas dataframe into SQL Server
I am trying to export a Pandas dataframe to SQL Server using the following code:

```<code>import pyodbc
import sqlalchemy
from sqlalchemy import engine

DB={'servername':'NAME', 'database':'dbname','driver':'driver={SQL Native Client 11.0}'
}

engine=create_engine('mssql+pyodbc://'+'DB['servername']+'/'+['database']+'/'+['driver'])

df.to_sql(con=engine,'test')
</code>```

The error that it shows is

Datasource name not specified and no default driver specified

The df has 1 column and 90k-100k rows
How can I overcome this issue in order to export the dataframe (df) into SQL Server?

答:
Pandas uses SQLAlchemy to connect to databases, which in turn can use PyODBC. Microsoft recommends using PyODBC to connect to SQL Server.

The SQLAlchemy docs for SQL Server show that the connection string should have the form:

```<code>"mssql+pyodbc://user:password@myhost:port/databasename?driver=ODBC+Driver+17+for+SQL+Server"
</code>```

ie

```<code>engine = create_engine("mssql+pyodbc://user:password@myhost:port/databasename?driver=ODBC+Driver+17+for+SQL+Server")
</code>```

You can also use an ODBC connection string:

```<code>from sqlalchemy.engine import URL
connection_string = "DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password"
connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string})

engine = create_engine(connection_url)
</code>```

You'll have to install PyODBC and the correct SQL Server ODBC driver for your operating system. The SQL Server docs on Python link to the appropriate drivers for Windows, various Linux distros and MacOS

If you have trouble saving to SQL Server, try the SQL Server PyODBC Getting Started tutorial to ensure you can connect to the database

Body:
I am trying to export a Pandas dataframe to SQL Server using the following code:

import pyodbc
import sqlalchemy
from sqlalchemy import engine

DB={'servername':'NAME', 'database':'dbname','driver':'driver={SQL Native Client 11.0}'
}

engine=create_engine('mssql+pyodbc://'+'DB['servername']+'/'+['database']+'/'+['driver'])

df.to_sql(con=engine,'test')

The error that it shows is

Datasource name not specified and no default driver specified

The df has 1 column and 90k-100k rows
How can I overcome this issue in order to export the dataframe (df) into SQL Server?

Body:
Pandas uses SQLAlchemy to connect to databases, which in turn can use PyODBC. Microsoft recommends using PyODBC to connect to SQL Server.

The SQLAlchemy docs for SQL Server show that the connection string should have the form:

"mssql+pyodbc://user:password@myhost:port/databasename?driver=ODBC+Driver+17+for+SQL+Server"

ie

engine = create_engine("mssql+pyodbc://user:password@myhost:port/databasename?driver=ODBC+Driver+17+for+SQL+Server")

You can also use an ODBC connection string:

from sqlalchemy.engine import URL
connection_string = "DRIVER={SQL Server Native Client 10.0};SERVER=dagger;DATABASE=test;UID=user;PWD=password"
connection_url = URL.create("mssql+pyodbc", query={"odbc_connect": connection_string})

engine = create_engine(connection_url)

You'll have to install PyODBC and the correct SQL Server ODBC driver for your operating system. The SQL Server docs on Python link to the appropriate drivers for Windows, various Linux distros and MacOS

If you have trouble saving to SQL Server, try the SQL Server PyODBC Getting Started tutorial to ensure you can connect to the database


问:
3D plot of cube in python
I'm completely new to python and I have to create a 3D plot that has the shape of a cube like the image:

I have never programmed in python so I'm not even sure what library to use. Can this be solved in matplotlib?

I have to define a function box3d(n) that generates a list of coordinates (3 x n array). The points should be placed along the 12 edges and each line should have n points between -0.5 and 0.5.

答:
You can use 3D Scatter Plot from matplotlib, like in the following snippet. Just change the xs, ys, zs arrays with the coordinates of the points that you want to represent.

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

# Fixing random state for reproducibility
np.random.seed(19680801)

def randrange(n, vmin, vmax):
    """
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    """
    return (vmax - vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

n = 100

# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, marker=m)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

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

The result of this would be this:

Title: 3D plot of cube in python

Body:
You can use 3D Scatter Plot from matplotlib, like in the following snippet. Just change the xs, ys, zs arrays with the coordinates of the points that you want to represent.

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19680801)

def randrange(n, vmin, vmax):
    """
    Helper function to make an array of random numbers having shape (n, )
    with each number distributed Uniform(vmin, vmax).
    """
    return (vmax - vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(projection='3d')

n = 100

# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for m, zlow, zhigh in [('o', -50, -25), ('^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zlow, zhigh)
    ax.scatter(xs, ys, zs, marker=m)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

The result of this would be this:


问:
Uncaught Error: Objects are not valid as a React child . If you meant to render a collection of children, use an array instead
i am not getting it can any one tell me whats my error.and also I am not getting it console in console errors(react-dom.development.js:13231 Uncaught Error: Objects are not valid as a React child (found: [object HTMLDivElement]). If you meant to render a collection of children, use an array instead.)

it's my app.js component

```<code>import { commerce } from './lib/commerce';
import { useState,useEffect } from 'react';
import './App.css';
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
import Products from './Components/Products';
const App=()=> {
  const [products,setProducts]=useState([]);
  const fetchProducts = async () => {
    const response = await commerce.products.list();
    setProducts((response && response.data) || []);
  };
  useEffect(() => {
    fetchProducts();
  }, []);

  return (
    <BrowserRouter>
    <Routes>
      <Route path="/" element={<Products products={products} />}>

        </Route>
    </Routes>
  </BrowserRouter>,
    document.getElementById("root")
  );
}

export default App;
</code>```

its my index.js component

```<code>import React from 'react';

const Products=({products})=> {
    console.log('products===',products)
    return (
        <div>
            {products.map(product=>{
               return <h1>{product.name}</h1>
            })}
        </div>
    );
}

export default Products;
</code>```

its my commerce.js file

```<code>import Commerce from "@chec/commerce.js";
export const commerce=new Commerce(
    'pk_test_3545707b2e0c86f543293995b654f1d27dae48f368716',
    true
)
</code>```

答:
You can console.log(products) to debug.

My assume is that your products didn't finish fetched before you rendering your route.

So you can go like

```<code>{ products ? products.map(product => {return <h1>{product.name}</h1>}) : ""}
</code>```

Body:
i am not getting it can any one tell me whats my error.and also I am not getting it console in console errors(react-dom.development.js:13231 Uncaught Error: Objects are not valid as a React child (found: [object HTMLDivElement]). If you meant to render a collection of children, use an array instead.)

it's my app.js component

import { commerce } from './lib/commerce';
import { useState,useEffect } from 'react';
import './App.css';
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
import Products from './Components/Products';
const App=()=> {
  const [products,setProducts]=useState([]);
  const fetchProducts = async () => {
    const response = await commerce.products.list();
    setProducts((response && response.data) || []);
  };
  useEffect(() => {
    fetchProducts();
  }, []);

  return (
    <BrowserRouter>
    <Routes>
      <Route path="/" element={<Products products={products} />}>

        </Route>
    </Routes>
  </BrowserRouter>,
    document.getElementById("root")
  );
}

export default App;

its my index.js component

import React from 'react';

const Products=({products})=> {
    console.log('products===',products)
    return (

            {products.map(product=>{
               return
{product.name}

            })}

    );
}

export default Products;

its my commerce.js file

import Commerce from "@chec/commerce.js";
export const commerce=new Commerce(
    'pk_test_3545707b2e0c86f543293995b654f1d27dae48f368716',
    true
)

Body:
You can console.log(products) to debug.

My assume is that your products didn't finish fetched before you rendering your route.

So you can go like

{ products ? products.map(product => {return <h1>{product.name}</h1>}) : ""}


问:
I have a problem with if statement and numbers
my problem is I want to make the elif statement work on numbers only but the elif statement work on any datatype, is there any way i can separate the numbers in string type from the other data types

The Code

```<code>```address_book = {'1111': 'Amal', '2222': 'Mohammed', '3333': "Khadijah", '4444': 'Abdullah'}

def enter():
    i = input('Please Enter The number: ')
    if len(i) != 4:
        print('This is invalid number')
    elif i in list(address_book):
        print(address_book[i])
    elif i in list(address_book.values()):
        print(list(address_book.keys())[list(address_book.values()).index(i)])
    **elif i.isdigit() not in list(address_book.keys()):
        print('Sorry, the number is not found')
        m = input('do you want to add new number? ')
        if m == 'yes':
            d = input('Please Enter The new number: ')
            w = input('Please Enter the number owner name: ')
            address_book[d] = w
            f = input('Do yo want to see address book: ')
            if f == 'yes':
                print(address_book)
            else:
                pass**
        else:
            pass
    else:
        print('This is invalid number')

enter()```
</code>```

OutPut

```<code>```Please Enter The number: sdaa
Sorry, the number is not found
do you want to add new number? yes
Please Enter The new number: 3333
Please Enter the number owner name: Waleed
Do yo want to see address book: yes
{'1111': 'Amal', '2222': 'Mohammed', '3333': 'Waleed', '4444': 'Abdullah'}

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

答:
You can use and for this:

```<code>elif i.isdigit() and i not in address_book:
</code>```

Note that you can use in to check if a key in the dictionary, so you don't need to call .keys() or convert it to a list for that.

Body:
my problem is I want to make the elif statement work on numbers only but the elif statement work on any datatype, is there any way i can separate the numbers in string type from the other data types

The Code

```address_book = {'1111': 'Amal', '2222': 'Mohammed', '3333': "Khadijah", '4444': 'Abdullah'}

def enter():
    i = input('Please Enter The number: ')
    if len(i) != 4:
        print('This is invalid number')
    elif i in list(address_book):
        print(address_book[i])
    elif i in list(address_book.values()):
        print(list(address_book.keys())[list(address_book.values()).index(i)])
    **elif i.isdigit() not in list(address_book.keys()):
        print('Sorry, the number is not found')
        m = input('do you want to add new number? ')
        if m == 'yes':
            d = input('Please Enter The new number: ')
            w = input('Please Enter the number owner name: ')
            address_book[d] = w
            f = input('Do yo want to see address book: ')
            if f == 'yes':
                print(address_book)
            else:
                pass**
        else:
            pass
    else:
        print('This is invalid number')

enter()```

OutPut

```Please Enter The number: sdaa
Sorry, the number is not found
do you want to add new number? yes
Please Enter The new number: 3333
Please Enter the number owner name: Waleed
Do yo want to see address book: yes
{'1111': 'Amal', '2222': 'Mohammed', '3333': 'Waleed', '4444': 'Abdullah'}

Process finished with exit code 0```

Body:
You can use and for this:

elif i.isdigit() and i not in address_book:

Note that you can use in to check if a key in the dictionary, so you don't need to call .keys() or convert it to a list for that.


问:
How do i close a old window each time a new window is oppened in tkinter
I have a simplified code below of 2 separate screens. How do I have it so that when one screen is opened the old one is then closed?

Whilst i don't have multiple screens in this example i would like to be able to to this for 6-9 screens dependent upon GUI design.

any help on the subject would be greatly appreciated.

```<code>from tkinter import *
import os
import time
from tkinter import simpledialog

def login():
    global screen2
    screen2 = Toplevel(screen)
    screen2.title("Login")
    screen2.geometry("530x290")
    Label(screen2, text = "please enter details below to login").pack()
    Label(screen2, text = "").pack()

    calibration1 = StringVar()
    calibration2 = StringVar()
    calibration3 = StringVar()

    global calibration1_entry
    global calibration2_entry
    global calibration3_entry

    calibration1_entry= Entry(screen2, textvariable = calibration1).place(x=350, y=70)
    calibration2_entry = Entry(screen2, textvariable = calibration2).place(x=350, y=120)
    calibration3_entry = Entry(screen2, textvariable = calibration3).place(x=350, y=170)

def main_screen():
    global screen
    screen = Tk()
    screen.geometry("530x290")
    screen.title("Remote Monitoring Site 1")
    Label(text = "Remote Monitoring Site 1", bg = "grey", width = "300", height = "2", font = ("Calibri", 13)).pack()
    Label(text = "").pack()
    Button(text = "Login", width = "30", height = "2", command = login).pack()
    Label(text = "").pack()

    screen.mainloop()

main_screen()
</code>```

答:
You can make more then one script for example to code login screen in one script, main menu in other, etc. Then you can use import os to close and open scripts. Function would be something like:

```<code>def login():
    if username == "admin" and password == "admin":
        file = 'python3 main_menu.py' # or you can do it
        root.destroy()                # proper way with db
        os.system(file)
</code>```

Body:
I have a simplified code below of 2 separate screens. How do I have it so that when one screen is opened the old one is then closed?

Whilst i don't have multiple screens in this example i would like to be able to to this for 6-9 screens dependent upon GUI design.

any help on the subject would be greatly appreciated.

from tkinter import *
import os
import time
from tkinter import simpledialog

def login():
    global screen2
    screen2 = Toplevel(screen)
    screen2.title("Login")
    screen2.geometry("530x290")
    Label(screen2, text = "please enter details below to login").pack()
    Label(screen2, text = "").pack()

    calibration1 = StringVar()
    calibration2 = StringVar()
    calibration3 = StringVar()

    global calibration1_entry
    global calibration2_entry
    global calibration3_entry

    calibration1_entry= Entry(screen2, textvariable = calibration1).place(x=350, y=70)
    calibration2_entry = Entry(screen2, textvariable = calibration2).place(x=350, y=120)
    calibration3_entry = Entry(screen2, textvariable = calibration3).place(x=350, y=170)

def main_screen():
    global screen
    screen = Tk()
    screen.geometry("530x290")
    screen.title("Remote Monitoring Site 1")
    Label(text = "Remote Monitoring Site 1", bg = "grey", width = "300", height = "2", font = ("Calibri", 13)).pack()
    Label(text = "").pack()
    Button(text = "Login", width = "30", height = "2", command = login).pack()
    Label(text = "").pack()

    screen.mainloop()

main_screen()

Body:
You can make more then one script for example to code login screen in one script, main menu in other, etc. Then you can use import os to close and open scripts. Function would be something like:

def login():
    if username == "admin" and password == "admin":
        file = 'python3 main_menu.py' # or you can do it
        root.destroy()                # proper way with db
        os.system(file)


答:
That's because the data you need to render the products page is being fetched and at that time is not available for your component to render so you kinda supplied null as a products param.

What you can do

Add a loading spinner or loading widget and in your routes file since that's where the products are being fetched do what's below.

Create a loading spinner component

<Route path="/" element={products.length < 1 : <SpinnerComponent /> : <Products products={products} />}>

This will show a loading spinner when the products array is empty and after a successful API call, it will show your products list

Title: Uncaught Error: Objects are not valid as a React child . If you meant to render a collection of children, use an array instead


问:
How make flexible vertical tags with CSS
What style should I give to the following tags so that all three are placed vertically on top of each other and by changing the height of the browser, the first and third tags remain fixed, but the second tag changes its height?

```<code>    <div class="flex-container">
      <div class="flex1">1</div>
      <div class="flex2">2</div>
      <div class="flex3">3</div>
    </div>
</code>```

Any help will be appriciated

答:
Change $breakpoint and $height according to your sizes and units.
You can also use max-height instead of min-height</p>
```<code>@media (min-height: $breakpoint) {
   .flex2 {
      height: $height !important;
   }
}
</code>```

Body:
What style should I give to the following tags so that all three are placed vertically on top of each other and by changing the height of the browser, the first and third tags remain fixed, but the second tag changes its height?

1

2

3

Any help will be appriciated

Body:
Change $breakpoint and $height according to your sizes and units.
You can also use max-height instead of min-height

@media (min-height: $breakpoint) {
   .flex2 {
      height: $height !important;
   }
}


问:
How to get value out of mono
I'm trying to extract a String out out Mono.

Mono method:

```<code>public Mono<String> getVal() {
    return webClient.get()
        .uri("/service")
        .retrieve()
        .bodyToMono(String.class);
}
</code>```

Calling getVal():

```<code>String val = getVal().block();
</code>```

I tried using block() but it returns the following error:

```<code>java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking,
which is not supported in thread reactor-http-nio-3
</code>```

I suppose I would have to use a non-blocking method like subscribe() which I'm not to sure how to.

答:
Ghokun has a better answer. But if anyone wants to use a blocking method:

I modified my getVal() method:

```<code>public String getVal() {
    String response = "";

        try {
            response = webClient.get()
                .uri("/service")
                .retrieve()
                .bodyToMono(String.class)
                .toFuture()
                .get();

        } catch (Exception e)
        {
            System.out.println(e.getMessage());

        }

        return response;
}
</code>```

Title: How to get value out of mono

Body:
I'm trying to extract a String out out Mono.

Mono method:

public Mono<String> getVal() {
    return webClient.get()
        .uri("/service")
        .retrieve()
        .bodyToMono(String.class);
}

Calling getVal():

String val = getVal().block();

I tried using block() but it returns the following error:

java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking,
which is not supported in thread reactor-http-nio-3

I suppose I would have to use a non-blocking method like subscribe() which I'm not to sure how to.

Body:
Ghokun has a better answer. But if anyone wants to use a blocking method:

I modified my getVal() method:

public String getVal() {
    String response = "";

        try {
            response = webClient.get()
                .uri("/service")
                .retrieve()
                .bodyToMono(String.class)
                .toFuture()
                .get();

        } catch (Exception e)
        {
            System.out.println(e.getMessage());

        }

        return response;
}


问:
How to style ButtonGroup with variant='text' in Material UI?
I am trying to change the colour of my Buttons nested inside a ButtonGroup. I want to change the text colour as well as the "|" lines in between the buttons. I have tried overriding every class that I could find using the developer's console through styled but none of them had any effect.

```<code>const SortOptionButtonGroup = styled(ButtonGroup)({
  '& .MuiButtonGroup-root': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonGroup-text': { color: pageColor, borderColor: pageColor },
});

const SortOptionButton = styled(Button)({
  '& .MuiButton-root': { color: pageColor, borderColor: pageColor },
  '& .MuiButton-text': { color: pageColor, borderColor: pageColor },
  '& .MuiButton-textPrimary': { color: pageColor, borderColor: pageColor },
  '& .MuiButton-sizeMedium': { color: pageColor, borderColor: pageColor },
  '& .MuiButton-textSizeMedium': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonBase-root': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonGroup-grouped': { color: pageColor, borderRight: pageColor },
  '& .MuiButtonGroup-groupedHorizontal ': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonGroup-groupedText': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonGroup-groupedTextHorizontal': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonGroup-groupedTextPrimary': { color: pageColor, borderColor: pageColor },
});
</code>```

I am using v5.4.1.

答:
You can change inner button styles (color, background-color, etc) directly through styled:

```<code>const StyledButton = styled(Button)({
  color: '#ff0000',
  backgroundColor: '#00ff00'
})
</code>```

The divider line between buttons is implemented as buttons' border, so to change it, you should style button border inside ButtonGroup. You can do something like this:

```<code>const StyledButtonGroup = styled(ButtonGroup)({
  "& .MuiButtonGroup-grouped:not(:last-of-type)": {
    borderColor: "#ebc200"
  }
});
</code>```

Here's an example sandbox

Body:
I am trying to change the colour of my Buttons nested inside a ButtonGroup. I want to change the text colour as well as the "|" lines in between the buttons. I have tried overriding every class that I could find using the developer's console through styled but none of them had any effect.

const SortOptionButtonGroup = styled(ButtonGroup)({
  '& .MuiButtonGroup-root': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonGroup-text': { color: pageColor, borderColor: pageColor },
});

const SortOptionButton = styled(Button)({
  '& .MuiButton-root': { color: pageColor, borderColor: pageColor },
  '& .MuiButton-text': { color: pageColor, borderColor: pageColor },
  '& .MuiButton-textPrimary': { color: pageColor, borderColor: pageColor },
  '& .MuiButton-sizeMedium': { color: pageColor, borderColor: pageColor },
  '& .MuiButton-textSizeMedium': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonBase-root': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonGroup-grouped': { color: pageColor, borderRight: pageColor },
  '& .MuiButtonGroup-groupedHorizontal ': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonGroup-groupedText': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonGroup-groupedTextHorizontal': { color: pageColor, borderColor: pageColor },
  '& .MuiButtonGroup-groupedTextPrimary': { color: pageColor, borderColor: pageColor },
});

I am using v5.4.1.

Body:
You can change inner button styles (color, background-color, etc) directly through styled:

const StyledButton = styled(Button)({
  color: '#ff0000',
  backgroundColor: '#00ff00'
})

The divider line between buttons is implemented as buttons' border, so to change it, you should style button border inside ButtonGroup. You can do something like this:

const StyledButtonGroup = styled(ButtonGroup)({
  "& .MuiButtonGroup-grouped:not(:last-of-type)": {
    borderColor: "#ebc200"
  }
});

Here's an example sandbox


问:
GAS: PropertiesService with token is null for PropertiesService
What is the correct way to use the OAuth token with Google App Script to use PropertiesService?

I build an application with slack and work well if I don't use this source code.

If I try to use this then result token is null:

```<code>const token = PropertiesService.getScriptProperties().getProperty('xoxb-slack-token');
Logger.log(token)
...
Info    null
</code>```

答:
Apps Script's PropertiesService can be used to store and retrieve data on your script.

If you don't first store them (for example, via setProperty(key,value)), you cannot retrieve them.

So, in this case, you should first get whatever data is coming from Slack and store it as Apps Script properties, if you want to retrieve them later in your script, using this service.

Reference:

Properties Service

Body:
What is the correct way to use the OAuth token with Google App Script to use PropertiesService?

I build an application with slack and work well if I don't use this source code.

If I try to use this then result token is null:

const token = PropertiesService.getScriptProperties().getProperty('xoxb-slack-token');
Logger.log(token)
...
Info    null


问:
VBA problem with object in get date from pivot
I wanted to get data from a pivot table using the getdate pivot function. However, I get "Application - definied or object - definied error" . I want to take "Suma końcowa" and paste it in the E20 field.

```<code>Dim ptAs PivotTable
Set pt = wbMe.Sheets("RES_MAT").PivotTables("Tabela przestawna")
wbMe.Sheets("RES_MAT").Range("E20") = pt.GetPivotData("Suma z WYCENA_PLN", "Suma końcowa").Value
</code>```

答:
If you just specify the name of the field, that should return the total,,,</p>
```<code>Range("E20")=pt.GetPivotData("Etykiety wierszy")
</code>```

Body:
I wanted to get data from a pivot table using the getdate pivot function. However, I get "Application - definied or object - definied error" . I want to take "Suma końcowa" and paste it in the E20 field.

Dim ptAs PivotTable
Set pt = wbMe.Sheets("RES_MAT").PivotTables("Tabela przestawna")
wbMe.Sheets("RES_MAT").Range("E20") = pt.GetPivotData("Suma z WYCENA_PLN", "Suma końcowa").Value

Body:
If you just specify the name of the field, that should return the total,,,

Range("E20")=pt.GetPivotData("Etykiety wierszy")


问:
How can I determine the limit on Vertex Shader outputs?
I'm trying to introduce multiple shadow casters, and in the process I'm passing a transformed position for each light in the VS output. The shader compiler reports errors as a result of the output size exceeding some internal limit, but I've been thus far unable to determine what the limit actually is (or how to find it).

The output structure is as follows:

```<code>out VS_OUT
{
    vec3 FragPos;
    vec3 Normal;
    vec3 Colour;
    vec2 TexCoord;
    vec4[MAX_SHADOW_CASTERS] LightSpaceFragPos;
} vso;
</code>```

Compilation has failed at MAX_SHADOW_CASTERS value 64 and 32, at the very least.

Additionally, any suggestions around improving the capacity of the array would be appreciated. These values are naturally per fragment, so a universal texture/buffer would be impractical as far as I understand.

答: The maximum number of varying vector variables (that's what the interface between the vertex and fragment shader stages are called - and in earlier GLSL versions those actually had the keyword varying instead of in/out) can be queryied via glGetIntegerv with GL_MAX_VARYING_VECTORS as the pname parameter argument.

Body:
I'm trying to introduce multiple shadow casters, and in the process I'm passing a transformed position for each light in the VS output. The shader compiler reports errors as a result of the output size exceeding some internal limit, but I've been thus far unable to determine what the limit actually is (or how to find it).

The output structure is as follows:

out VS_OUT
{
    vec3 FragPos;
    vec3 Normal;
    vec3 Colour;
    vec2 TexCoord;
    vec4[MAX_SHADOW_CASTERS] LightSpaceFragPos;
} vso;

Compilation has failed at MAX_SHADOW_CASTERS value 64 and 32, at the very least.

Additionally, any suggestions around improving the capacity of the array would be appreciated. These values are naturally per fragment, so a universal texture/buffer would be impractical as far as I understand.


问:
Gitlab-ci image with docker and java/gradle
I'm including an integration test into my application using library "https://www.testcontainers.org/".

This library need a docker environment to run "gradlew test" command.

How would you use a docker image (which include docker and Gradle) in a gitlab-ci.yml?

答:
That looks like what Christos Sotiriou described in "Your Private CI/CD using self-hosted GitLab and Docker" in 2020.

It involves a GitLab runner:

A GitLab runner has many modes it can operate, which represent how the build will be performed. Among other modes, there is support for spawning Kubernetes pods, or Docker containers to perform builds.

For the sake of simplicity, we will use the plain docker mode, which will spawn a new container with an image of your choice (determined by your Dockerfile)

Run the following to your terminal:

docker run -d --name gitlab-runner --restart always \
 -v /srv/gitlab-runner/config:/etc/gitlab-runner \
 -v /var/run/docker.sock:/var/run/docker.sock \
 gitlab/gitlab-runner:latest
```

And:

You can configure your runner to use the host's docker when executing the Dockerfile commands.

You can do that by configuring the gitlab-runner configuration to use the host docker.

That involves some security risk, but check if this option would allow you to use the image you want, while using docker commands in your gitlab-ci.yml.

Body:
That looks like what Christos Sotiriou described in "Your Private CI/CD using self-hosted GitLab and Docker" in 2020.

It involves a GitLab runner:

A GitLab runner has many modes it can operate, which represent how the build will be performed. Among other modes, there is support for spawning Kubernetes pods, or Docker containers to perform builds.

For the sake of simplicity, we will use the plain docker mode, which will spawn a new container with an image of your choice (determined by your Dockerfile)

Run the following to your terminal:

docker run -d --name gitlab-runner --restart always \
 -v /srv/gitlab-runner/config:/etc/gitlab-runner \
 -v /var/run/docker.sock:/var/run/docker.sock \
 gitlab/gitlab-runner:latest

And:

You can configure your runner to use the host's docker when executing the Dockerfile commands.

You can do that by configuring the gitlab-runner configuration to use the host docker.

That involves some security risk, but check if this option would allow you to use the image you want, while using docker commands in your gitlab-ci.yml.


问:
How to approximate the size of a text file containing a matrix, written by Fortran?
I have written an N*N matrix to a formatted text file using Fortran. The Fortran output format was N(3X,E17.8), where N is the matrix size.

Example of one matrix element:    0.19860753E-08 i.e. "(three spaces)0.19860753E-08".

A 558x558 Matrix has a file size of 5.294.302 Bytes.

How could I approximate the file size for an N*N matrix for any value of N?

答:
Rather than calculating the size of the file from the details of the code and the file format, it may be simpler to write out files containing matrices with (at least) three different values of N. You can then fit the file size S as a function of N, as

```<code>S = a*N^2 + b*N + c
</code>```

where a, b and c are constants which you will get from the fit.

The a*N^2 term comes from the representation of the numbers in the matrix.

The b*N term comes from line endings, and any value separators you might be using.

The c term comes from file metadata, and any spare characters you might have in your file.

Body:
Rather than calculating the size of the file from the details of the code and the file format, it may be simpler to write out files containing matrices with (at least) three different values of N. You can then fit the file size S as a function of N, as

S = a*N^2 + b*N + c

where a, b and c are constants which you will get from the fit.

The a*N^2 term comes from the representation of the numbers in the matrix.

The b*N term comes from line endings, and any value separators you might be using.

The c term comes from file metadata, and any spare characters you might have in your file.


问:
ibmcom/db2 docker image fails on m1
I'm having trouble setting up DB2 on macOS via Docker on my M1-Max MacBook Pro (32 GB RAM). I already had a look at this question, which might be related, however there is not a lot of information and I cannot exactly say, if it is about the exact same thing.
I set up following docker-compose.yml:

```
version: '3.8'

services:
  db2:
    image: ibmcom/db2
    platform: linux/amd64
    container_name: db2-test
    privileged: true
    environment:
      LICENSE: "accept"
      DB2INSTANCE: "db2dude"
      DB2INST1_PASSWORD: "db2pw"
      DBNAME: "RC1DBA"
      BLU: "false"
      ENABLE_ORACLE_COMPATIBILITY: "false"
      UPDATEVAIL: "NO"
      TO_CREATE_SAMPLEDB: "false"
      REPODB: "false"
      IS_OSXFS: "true"
      PERSISTENT_HOME: "true"
      HADR_ENABLED: "false"
      ETCD_ENDPOINT: ""
      ETCD_USERNAME: ""
      ETCD_PASSWORD: ""
    volumes:
       - ~/workspace/docker/db2-error/db2/database:/database
       - ~/workspace/docker/db2-error/db2/db2_data:/db2_data
    ports:
      - 50000:50000
```

on my Intel-MacBook, this spins up without any issue, on my M1-MacBook however I see after Task #4 finished, I see following portion inside of the STDOUT:

```
DBI1446I  The db2icrt command is running.

DBI1070I  Program db2icrt completed successfully.

(*) Fixing /etc/services file for DB2 ...
/bin/bash: db2stop: command not found
```

From what I could figure out, the presence of (*) Fixing /etc/services file for DB2 ...  already seems to be wrong (since it does not appear in my intel log and does not sound like everything's fine) and the /bin/bash: db2stop: command not found appears due to line 81 of /var/db2_setup/include/db2_common_functions, which states su - ${DB2INSTANCE?} -c 'db2stop force'.
As far as I understand, su - should run with the path of the target user. In every single .profile or .bashrc in the home directory, the ~/sqllib/db2profile is being sourced (via . /database/config/db2dude/sqllib/db2profile).

However, when as root inside of the container (docker exec -it db2-test bash), calling su - db2dude -c 'echo $PATH', it prints /usr/local/bin:/bin:/usr/bin. Therefore, the PATH obviously is not as expected.

Maybe someone can figure out, what's happening at this point. I also tried running Docker with "new Virtualization framework", which did not change anything. I assume, Dockers compatibility magic might not be perfect, however I'm looking forward to find some kind of workaround, maybe by building an image upon ibmcom/db2.

I highly appreciate your time and advice. Thanks a lot in advance.

答:
As stated in @mshabou's answer, there is no support yet. One way you can still make it work is by prepending your Docker command with DOCKER_DEFAULT_PLATFORM=linux/amd64 or executing export DOCKER_DEFAULT_PLATFORM=linux/amd64 in your shell before starting the container.

Alternatively, you can also use colima. Install colima as described on their GitHub page and then start it in emulated mode like colima start --arch x86_64. Now you will be able to use your ibmcom/db2 image the way you're used to (albeit with decreased performance).

Title: ibmcom/db2 docker image fails on m1

Body:
I'm having trouble setting up DB2 on macOS via Docker on my M1-Max MacBook Pro (32 GB RAM). I already had a look at this question, which might be related, however there is not a lot of information and I cannot exactly say, if it is about the exact same thing.
I set up following docker-compose.yml:

version: '3.8'

services:
  db2:
    image: ibmcom/db2
    platform: linux/amd64
    container_name: db2-test
    privileged: true
    environment:
      LICENSE: "accept"
      DB2INSTANCE: "db2dude"
      DB2INST1_PASSWORD: "db2pw"
      DBNAME: "RC1DBA"
      BLU: "false"
      ENABLE_ORACLE_COMPATIBILITY: "false"
      UPDATEVAIL: "NO"
      TO_CREATE_SAMPLEDB: "false"
      REPODB: "false"
      IS_OSXFS: "true"
      PERSISTENT_HOME: "true"
      HADR_ENABLED: "false"
      ETCD_ENDPOINT: ""
      ETCD_USERNAME: ""
      ETCD_PASSWORD: ""
    volumes:
       - ~/workspace/docker/db2-error/db2/database:/database
       - ~/workspace/docker/db2-error/db2/db2_data:/db2_data
    ports:
      - 50000:50000

on my Intel-MacBook, this spins up without any issue, on my M1-MacBook however I see after Task #4 finished, I see following portion inside of the STDOUT:

DBI1446I  The db2icrt command is running.

DBI1070I  Program db2icrt completed successfully.

(*) Fixing /etc/services file for DB2 ...
/bin/bash: db2stop: command not found

From what I could figure out, the presence of (*) Fixing /etc/services file for DB2 ...  already seems to be wrong (since it does not appear in my intel log and does not sound like everything's fine) and the /bin/bash: db2stop: command not found appears due to line 81 of /var/db2_setup/include/db2_common_functions, which states su - ${DB2INSTANCE?} -c 'db2stop force'.
As far as I understand, su - should run with the path of the target user. In every single .profile or .bashrc in the home directory, the ~/sqllib/db2profile is being sourced (via . /database/config/db2dude/sqllib/db2profile).

However, when as root inside of the container (docker exec -it db2-test bash), calling su - db2dude -c 'echo $PATH', it prints /usr/local/bin:/bin:/usr/bin. Therefore, the PATH obviously is not as expected.

Maybe someone can figure out, what's happening at this point. I also tried running Docker with "new Virtualization framework", which did not change anything. I assume, Dockers compatibility magic might not be perfect, however I'm looking forward to find some kind of workaround, maybe by building an image upon ibmcom/db2.

I highly appreciate your time and advice. Thanks a lot in advance.


问:
Windows CreateFile in C# Returns Invalid Handle
I am trying to invoke the CreateFile method from Kernel32.dll in a C# application, and it is returning an invalid handle everytime. I've looked all over and can't find a solution to this problem. Here is the relevant code:

Constants:

```<code>    const UInt64 GENERIC_READ = 0x80000000L;
    const UInt64 GENERIC_WRITE = 0x40000000L;
    const UInt64 GENERIC_EXECUTE = 0x20000000L;
    const UInt64 GENERIC_ALL = 0x10000000L;
    const uint FILE_SHARE_READ = 0x00000001;
    const uint FILE_SHARE_WRITE = 0x00000002;
    const uint OPEN_EXISTING = 0x00000003;
    const uint FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;
</code>```

Importing the Method:

```<code>[DllImport("kernel32.dll", SetLastError = true)]
    static extern unsafe SafeFileHandle CreateFile(
          string FileName,
          ulong DesiredAccess,
          uint ShareMode,
          IntPtr SecurityAttributes,
          uint CreationDisposition,
          uint FlagsAndAttributes,
          IntPtr hTemplateFile
          );
SafeFileHandle JFifoDrv = LoadDriver();
</code>```

Method to Load Driver:

```<code>unsafe private SafeFileHandle LoadDriver()
    {
        SafeFileHandle hDrv = (SafeFileHandle)null;
        try
        {
            hDrv = CreateFile("\\\\.\\JFIFODRV",
                GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                (IntPtr)null,
                OPEN_EXISTING,
                FILE_FLAG_DELETE_ON_CLOSE,
                (IntPtr)null);

            DriverLoaded = true;
        }
        catch
        {
            poll.Stop();
            DriverLoaded = false;
        }

        return hDrv;
    }
</code>```

Can Anyone help me figure out the problem?

答: Your declaration is wrong, the 2nd argument is an uint, not an ulong.  The pinvoke.net website is a decent source for declarations.  Be sure to throw Win32Exception when JFifoDrv.IsInvalid is true.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am trying to invoke the CreateFile method from Kernel32.dll in a C# application, and it is returning an invalid handle everytime. I've looked all over and can't find a solution to this problem. Here is the relevant code:

Constants:

    const UInt64 GENERIC_READ = 0x80000000L;
    const UInt64 GENERIC_WRITE = 0x40000000L;
    const UInt64 GENERIC_EXECUTE = 0x20000000L;
    const UInt64 GENERIC_ALL = 0x10000000L;
    const uint FILE_SHARE_READ = 0x00000001;
    const uint FILE_SHARE_WRITE = 0x00000002;
    const uint OPEN_EXISTING = 0x00000003;
    const uint FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;

Importing the Method:

[DllImport("kernel32.dll", SetLastError = true)]
    static extern unsafe SafeFileHandle CreateFile(
          string FileName,
          ulong DesiredAccess,
          uint ShareMode,
          IntPtr SecurityAttributes,
          uint CreationDisposition,
          uint FlagsAndAttributes,
          IntPtr hTemplateFile
          );
SafeFileHandle JFifoDrv = LoadDriver();

Method to Load Driver:

unsafe private SafeFileHandle LoadDriver()
    {
        SafeFileHandle hDrv = (SafeFileHandle)null;
        try
        {
            hDrv = CreateFile("\\\\.\\JFIFODRV",
                GENERIC_READ | GENERIC_WRITE,
                FILE_SHARE_READ | FILE_SHARE_WRITE,
                (IntPtr)null,
                OPEN_EXISTING,
                FILE_FLAG_DELETE_ON_CLOSE,
                (IntPtr)null);

            DriverLoaded = true;
        }
        catch
        {
            poll.Stop();
            DriverLoaded = false;
        }

        return hDrv;
    }

Can Anyone help me figure out the problem?


问:
Given an ArrayList is-a List and a List is-a Collection is the following true? ArrayList<String> is-a Collection<String>
I'm almost sure that the answer for this question is yes, but I'm not sure how to articulate it on my exam. Since an ArrayList is a List and a List is a Collection, we can definitely say that an ArrayList is a Collection.

However, how can I afirm that an ArrayList<String> is a Collection<String> without knowing that Collection is a generic class beforehand?

How would you answer this question?

Thanks

答:
Try this, for example at https://www.programiz.com/java-programming/online-compiler/ or https://www.tutorialspoint.com/compile_java_online.php:

```<code>import java.util.Collection;
import java.util.List;
import java.util.ArrayList;

public class Is_A_List_A_Class_class{

     public static void main(String []args){
        List<String> list = new ArrayList<String>();
        System.out.println(list instanceof Collection);
     }
}
</code>```

Output:

> java -cp /tmp/K2aGszTI3o Is_A_List_A_Class_class
true
```

Body:
Try this, for example at https://www.programiz.com/java-programming/online-compiler/ or https://www.tutorialspoint.com/compile_java_online.php:

import java.util.Collection;
import java.util.List;
import java.util.ArrayList;

public class Is_A_List_A_Class_class{

     public static void main(String []args){
        List<String> list = new ArrayList<String>();
        System.out.println(list instanceof Collection);
     }
}

Output:

> java -cp /tmp/K2aGszTI3o Is_A_List_A_Class_class
true


问:
Not able to import image id
enter image description here

Glide.with(this).load(url).into(imageView)

答:
You can try with findViewById:

```<code>Glide.with(this).load(url).into(findViewById(R.id.imageView))
</code>```

However, the best approach would be using viewBinding:

```<code>class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ...

        Glide.with(this).load(url).into(binding.imageView)
    }
}
</code>```

In this case, don't forget to enable viewBinding in your app-level build.gradle file, by adding:

```<code>android {
    ...
    buildFeatures {
        viewBinding = true
    }
}
</code>```

For more on viewBinding check here

Title: Not able to import image id

Body:
You can try with findViewById:

Glide.with(this).load(url).into(findViewById(R.id.imageView))

However, the best approach would be using viewBinding:

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        ...

        Glide.with(this).load(url).into(binding.imageView)
    }
}

In this case, don't forget to enable viewBinding in your app-level build.gradle file, by adding:

android {
    ...
    buildFeatures {
        viewBinding = true
    }
}

For more on viewBinding check here


问:
Angular: how to initialize variable inside *ngFor
I have an Angular template:

  <input type="radio" class="form-check-input" id="radio-{{rand}}" name="field-radio"
    [value]="item.key">

    {{ item.key }}

```

I want to execute random() function for every iteration of loop. But I get an error:

Property 'random' does not exist on type...

How can I use internal variable inside Angular template?

答:
```<code><li *ngFor="let item of list | keyvalue; let i= index" >
  <input type="radio" class="form-check-input" [id]="'radio-'+i" name="field-radio"
    [value]="item.key">
  <label class="form-check-label" [for]="'radio-'+i">
    {{ item.key }}
  </label>
</li>
</code>```

Try to use index, it will give you unique identifier on id and for attributes

Body:
I have an Angular template:

  <input type="radio" class="form-check-input" id="radio-{{rand}}" name="field-radio"
    [value]="item.key">

    {{ item.key }}

I want to execute random() function for every iteration of loop. But I get an error:

Property 'random' does not exist on type...

How can I use internal variable inside Angular template?

Body:
<li *ngFor="let item of list | keyvalue; let i= index" >
  <input type="radio" class="form-check-input" [id]="'radio-'+i" name="field-radio"
    [value]="item.key">
  <label class="form-check-label" [for]="'radio-'+i">
    {{ item.key }}
  </label>
</li>

Try to use index, it will give you unique identifier on id and for attributes


问:
How can I switch focus between the various parts of vscode with the keyboard?
For example, how to switch between the Explorer and the Editors, or between the Editors and the Terminal?</p>

答: Press Ctrl+Shift+P to bring up the command palette and search for Focus. There are several commands to switch the focus, e.g. View: Focus Active Editor Group or Explorer: Focus on Outline View. You can assign custom keybindings to those.


问:
How to change color based on theme flutter
I'm trying to change my container's color based on the system theme mode. Is there a way to change it using conditional if?

Here is the code:

```<code>     Container(
            color: //this is what I'm trying to change based on the theme,
            padding: EdgeInsets.only(right: 10, left: 10, top: 7, bottom: 25),
            child: Row(
              children: [
                Flexible(
                          ...
</code>```

And this is my theme_provider:

```<code>class MyThemes {
  static final darkTheme = ThemeData(
    ...
  );

  static final lightTheme = ThemeData(
    ...
  );
}
</code>```

答:
If you are trying to change theme using provider proceed with following code and structure hope it will work for you.

```<code>final darkTheme = ThemeData(
scaffoldBackgroundColor: Colors.grey.shade900,
primaryColor: Colors.black,
colorScheme: ColorScheme.dark(),
iconTheme: IconThemeData(color: Colors.blue, opacity: 0.8),
primarySwatch: Colors.grey,
);

final lightTheme = ThemeData(
scaffoldBackgroundColor: Colors.white,
primaryColor: Colors.white,
iconTheme: IconThemeData(color: Colors.red, opacity: 0.8),
primarySwatch: Colors.blue,
);
</code>```

Then create a class with ChangeNotifier

```<code>class ThemeProvider with ChangeNotifier {
  ThemeData themesData;
  ThemeProvider(this.themesData);

  getTheme() => themesData;

  setTheme(ThemeData themeData) async {
    print('Inside set theme');

    themesData = themeData;
    notifyListeners();
  }
}
</code>```

In your View write the following code to toogle the theme and call this function with Button or Switch whatever you want to use

```<code>void onThemeChanged(bool value, ThemeProvider themeNotifier) async {
value ? themeNotifier.setTheme(darkTheme) : themeNotifier.setTheme(lightTheme)}
</code>```

And now you can change the color based on the selected,

```<code> final themeNotifier = Provider.of<ThemeProvider>(context);

 Color ContainerColor = themeNotifier.getTheme() == darkTheme ? Colors.grey[700] : Colors.blue[400];

Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: ContainerColor
        ),
</code>```

Body:
I'm trying to change my container's color based on the system theme mode. Is there a way to change it using conditional if?

Here is the code:

     Container(
            color: //this is what I'm trying to change based on the theme,
            padding: EdgeInsets.only(right: 10, left: 10, top: 7, bottom: 25),
            child: Row(
              children: [
                Flexible(
                          ...

And this is my theme_provider:

class MyThemes {
  static final darkTheme = ThemeData(
    ...
  );

  static final lightTheme = ThemeData(
    ...
  );
}

Body:
If you are trying to change theme using provider proceed with following code and structure hope it will work for you.

final darkTheme = ThemeData(
scaffoldBackgroundColor: Colors.grey.shade900,
primaryColor: Colors.black,
colorScheme: ColorScheme.dark(),
iconTheme: IconThemeData(color: Colors.blue, opacity: 0.8),
primarySwatch: Colors.grey,
);

final lightTheme = ThemeData(
scaffoldBackgroundColor: Colors.white,
primaryColor: Colors.white,
iconTheme: IconThemeData(color: Colors.red, opacity: 0.8),
primarySwatch: Colors.blue,
);

Then create a class with ChangeNotifier

class ThemeProvider with ChangeNotifier {
  ThemeData themesData;
  ThemeProvider(this.themesData);

  getTheme() => themesData;

  setTheme(ThemeData themeData) async {
    print('Inside set theme');

    themesData = themeData;
    notifyListeners();
  }
}

In your View write the following code to toogle the theme and call this function with Button or Switch whatever you want to use

void onThemeChanged(bool value, ThemeProvider themeNotifier) async {
value ? themeNotifier.setTheme(darkTheme) : themeNotifier.setTheme(lightTheme)}

And now you can change the color based on the selected,

 final themeNotifier = Provider.of<ThemeProvider>(context);

 Color ContainerColor = themeNotifier.getTheme() == darkTheme ? Colors.grey[700] : Colors.blue[400];

Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: ContainerColor
        ),


问:
How should I access attributes of union types in typscript?
What is the correct way to access attributes of a union type that is not present on all of the types? I seem to always get a typescript "property ... does not exist on type..." error, even if I do a check to make sure the attribute exists (see example below)

```<code>interface Car {
  wheels: 4,
  spareWheels: 1,
}

interface Bicycle {
  wheels: 2,
}

type Vehicle = Car | Bicycle

getWheelCount(vehicle: Vehicle): number => {
   return vehicle.spareWheels ? vehicle.spareWheels + vehicle.wheels : vehicle.wheels
}
</code>```

The documentation (https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types ) has a solution to use 'typeof', but that doesn't work for custom types.

答:
You can use type-predicates.

interface Car {
  wheels: 4;
  spareWheels: 1;
}

interface Bicycle {
  wheels: 2;
}

type Vehicle = Car | Bicycle;

const getWheelCount = (vehicle: Vehicle): number => {
  return isVehiculeCar(vehicle) ? vehicle.spareWheels + vehicle.wheels : vehicle.wheels;
};

const isVehiculeCar = (subject: Vehicle): subject is Car => {
  return (subject as Car).spareWheels !== undefined;
};
```

This way Typescript will know when you are dealing with a Car or a Bicycle.

Technically, Typescript is inferring your vehicule var with Car type after the function isVehiculeCar. Meaning that if you are using an IDE with smart typing feature (like auto-completion) you will only have access to Car interface attributes in this scope.

Body:
What is the correct way to access attributes of a union type that is not present on all of the types? I seem to always get a typescript "property ... does not exist on type..." error, even if I do a check to make sure the attribute exists (see example below)

interface Car {
  wheels: 4,
  spareWheels: 1,
}

interface Bicycle {
  wheels: 2,
}

type Vehicle = Car | Bicycle

getWheelCount(vehicle: Vehicle): number => {
   return vehicle.spareWheels ? vehicle.spareWheels + vehicle.wheels : vehicle.wheels
}

The documentation (https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types ) has a solution to use 'typeof', but that doesn't work for custom types.

Body:
You can use type-predicates.

interface Car {
  wheels: 4;
  spareWheels: 1;
}

interface Bicycle {
  wheels: 2;
}

type Vehicle = Car | Bicycle;

const getWheelCount = (vehicle: Vehicle): number => {
  return isVehiculeCar(vehicle) ? vehicle.spareWheels + vehicle.wheels : vehicle.wheels;
};

const isVehiculeCar = (subject: Vehicle): subject is Car => {
  return (subject as Car).spareWheels !== undefined;
};

This way Typescript will know when you are dealing with a Car or a Bicycle.

Technically, Typescript is inferring your vehicule var with Car type after the function isVehiculeCar. Meaning that if you are using an IDE with smart typing feature (like auto-completion) you will only have access to Car interface attributes in this scope.


答:
Try to use computed property in the development. If you change any property, that will be refreshing and you can see data changes directly</p>
```<code>ThemeData get darkTheme => ThemeData(
    ...
  );
</code>```

Title: How to change color based on theme flutter

Body:
Try to use computed property in the development. If you change any property, that will be refreshing and you can see data changes directly

ThemeData get darkTheme => ThemeData(
    ...
  );