问:
The callback function HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac) with STM32U575CGU6 doesn't work
Could some one assist and clarify how to use the callback function HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac) with STM32U575CGU6. I try to integrate mp3 player with STM32U575CGU6. I checked flags and the status of DAC. All works but call-back functions HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac) and HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac) do not work.
Please assist.
Thanks!
Please see part of the code below.
//////////////////////////////////////////////////////
////this is a place of handling for the callback function////////

```<code>void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac)
{

 if (AudioPlayerState == PLAYER_PLAYING )
 {
    MP3_callback();
 }

}

</code>```

/////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
////this is configuration of DAC and DMA //////////////

```<code>/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "dac.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

DAC_HandleTypeDef hdac1;
DMA_HandleTypeDef handle_GPDMA1_Channel10;

/* DAC1 init function */
void MX_DAC1_Init(void)
{

  /* USER CODE BEGIN DAC1_Init 0 */

  /* USER CODE END DAC1_Init 0 */

  DAC_ChannelConfTypeDef sConfig = {0};
  DAC_AutonomousModeConfTypeDef sAutonomousMode = {0};

  /* USER CODE BEGIN DAC1_Init 1 */

  /* USER CODE END DAC1_Init 1 */

  /** DAC Initialization
  */
  hdac1.Instance = DAC1;

  if (HAL_DAC_Init(&hdac1) != HAL_OK)
  {
    Error_Handler();
  }

  /** DAC channel OUT1 config
  */
  sConfig.DAC_HighFrequency = DAC_HIGH_FREQUENCY_INTERFACE_MODE_ABOVE_80MHZ;
  sConfig.DAC_DMADoubleDataMode = DISABLE;
  sConfig.DAC_SignedFormat = DISABLE;
  sConfig.DAC_SampleAndHold = DAC_SAMPLEANDHOLD_DISABLE;
  sConfig.DAC_Trigger = DAC_TRIGGER_T2_TRGO;
  sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE;
  sConfig.DAC_ConnectOnChipPeripheral = DAC_CHIPCONNECT_EXTERNAL;
  sConfig.DAC_UserTrimming = DAC_TRIMMING_FACTORY;
  if (HAL_DAC_ConfigChannel(&hdac1, &sConfig, DAC_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Autonomous Mode
  */
  sAutonomousMode.AutonomousModeState = DAC_AUTONOMOUS_MODE_DISABLE;
  if (HAL_DACEx_SetConfigAutonomousMode(&hdac1, &sAutonomousMode) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN DAC1_Init 2 */

  /* USER CODE END DAC1_Init 2 */

}

void HAL_DAC_MspInit(DAC_HandleTypeDef* dacHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
  if(dacHandle->Instance==DAC1)
  {
  /* USER CODE BEGIN DAC1_MspInit 0 */

  /* USER CODE END DAC1_MspInit 0 */

  /** Initializes the peripherals clock
  */
    PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADCDAC|RCC_PERIPHCLK_DAC1;
    PeriphClkInit.AdcDacClockSelection = RCC_ADCDACCLKSOURCE_HSI;
    PeriphClkInit.Dac1ClockSelection = RCC_DAC1CLKSOURCE_LSI;
    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
    {
      Error_Handler();
    }

    /* DAC1 clock enable */
    __HAL_RCC_DAC1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**DAC1 GPIO Configuration
    PA4     ------> DAC1_OUT1
    */
    GPIO_InitStruct.Pin = GPIO_PIN_4;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* DAC1 DMA Init */
    /* GPDMA1_REQUEST_DAC1_CH1 Init */
    handle_GPDMA1_Channel10.Instance = GPDMA1_Channel10;
    handle_GPDMA1_Channel10.Init.Request = GPDMA1_REQUEST_DAC1_CH1;
    handle_GPDMA1_Channel10.Init.BlkHWRequest = DMA_BREQ_SINGLE_BURST;
    handle_GPDMA1_Channel10.Init.Direction = DMA_MEMORY_TO_PERIPH;
    handle_GPDMA1_Channel10.Init.SrcInc = DMA_SINC_INCREMENTED;
    handle_GPDMA1_Channel10.Init.DestInc = DMA_DINC_FIXED;
    handle_GPDMA1_Channel10.Init.SrcDataWidth = DMA_SRC_DATAWIDTH_HALFWORD;
    handle_GPDMA1_Channel10.Init.DestDataWidth = DMA_DEST_DATAWIDTH_BYTE;
    handle_GPDMA1_Channel10.Init.Priority = DMA_LOW_PRIORITY_LOW_WEIGHT;
    handle_GPDMA1_Channel10.Init.SrcBurstLength = 1;
    handle_GPDMA1_Channel10.Init.DestBurstLength = 1;
    handle_GPDMA1_Channel10.Init.TransferAllocatedPort = DMA_SRC_ALLOCATED_PORT1|DMA_DEST_ALLOCATED_PORT0;
    handle_GPDMA1_Channel10.Init.TransferEventMode = DMA_TCEM_BLOCK_TRANSFER;
    handle_GPDMA1_Channel10.Init.Mode = DMA_NORMAL;
    if (HAL_DMA_Init(&handle_GPDMA1_Channel10) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(dacHandle, DMA_Handle1, handle_GPDMA1_Channel10);

    if (HAL_DMA_ConfigChannelAttributes(&handle_GPDMA1_Channel10, DMA_CHANNEL_NPRIV) != HAL_OK)
    {
      Error_Handler();
    }

    /* DAC1 interrupt Init */
    HAL_NVIC_SetPriority(DAC1_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(DAC1_IRQn);
  /* USER CODE BEGIN DAC1_MspInit 1 */

  /* USER CODE END DAC1_MspInit 1 */
  }
}

void HAL_DAC_MspDeInit(DAC_HandleTypeDef* dacHandle)
{

  if(dacHandle->Instance==DAC1)
  {
  /* USER CODE BEGIN DAC1_MspDeInit 0 */

  /* USER CODE END DAC1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_DAC1_CLK_DISABLE();

    /**DAC1 GPIO Configuration
    PA4     ------> DAC1_OUT1
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_4);

    /* DAC1 DMA DeInit */
    HAL_DMA_DeInit(dacHandle->DMA_Handle1);

    /* DAC1 interrupt Deinit */
    HAL_NVIC_DisableIRQ(DAC1_IRQn);
  /* USER CODE BEGIN DAC1_MspDeInit 1 */

  /* USER CODE END DAC1_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */
</code>```

////////////////////////////////////////////////////////

```<code>/* Includes ------------------------------------------------------------------*/
#include "gpdma.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* GPDMA1 init function */
void MX_GPDMA1_Init(void)
{

  /* USER CODE BEGIN GPDMA1_Init 0 */

  /* USER CODE END GPDMA1_Init 0 */

  /* Peripheral clock enable */
  __HAL_RCC_GPDMA1_CLK_ENABLE();

  /* GPDMA1 interrupt Init */
    HAL_NVIC_SetPriority(GPDMA1_Channel10_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(GPDMA1_Channel10_IRQn);

  /* USER CODE BEGIN GPDMA1_Init 1 */

  /* USER CODE END GPDMA1_Init 1 */
  /* USER CODE BEGIN GPDMA1_Init 2 */

  /* USER CODE END GPDMA1_Init 2 */

}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */
</code>```

////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
////this is configuration of the timers //////////////

```<code>/* Includes ------------------------------------------------------------------*/
#include "tim.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

TIM_HandleTypeDef htim2;

/* TIM2 init function */
void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 0;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 2999;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */

}

void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
{

  if(tim_baseHandle->Instance==TIM2)
  {
  /* USER CODE BEGIN TIM2_MspInit 0 */

  /* USER CODE END TIM2_MspInit 0 */
    /* TIM2 clock enable */
    __HAL_RCC_TIM2_CLK_ENABLE();

    /* TIM2 interrupt Init */
    HAL_NVIC_SetPriority(TIM2_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(TIM2_IRQn);
  /* USER CODE BEGIN TIM2_MspInit 1 */

  /* USER CODE END TIM2_MspInit 1 */
  }
}

void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* tim_baseHandle)
{

  if(tim_baseHandle->Instance==TIM2)
  {
  /* USER CODE BEGIN TIM2_MspDeInit 0 */

  /* USER CODE END TIM2_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_TIM2_CLK_DISABLE();

    /* TIM2 interrupt Deinit */
    HAL_NVIC_DisableIRQ(TIM2_IRQn);
  /* USER CODE BEGIN TIM2_MspDeInit 1 */

  /* USER CODE END TIM2_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */

</code>```

Please give me advice on how to work with call back function correctly.

Body:
Could some one assist and clarify how to use the callback function HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac) with STM32U575CGU6. I try to integrate mp3 player with STM32U575CGU6. I checked flags and the status of DAC. All works but call-back functions HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac) and HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac) do not work.
Please assist.
Thanks!
Please see part of the code below.
//////////////////////////////////////////////////////
////this is a place of handling for the callback function////////

void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac)
{

 if (AudioPlayerState == PLAYER_PLAYING )
 {
    MP3_callback();
 }

}

/////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
////this is configuration of DAC and DMA //////////////

/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "dac.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

DAC_HandleTypeDef hdac1;
DMA_HandleTypeDef handle_GPDMA1_Channel10;

/* DAC1 init function */
void MX_DAC1_Init(void)
{

  /* USER CODE BEGIN DAC1_Init 0 */

  /* USER CODE END DAC1_Init 0 */

  DAC_ChannelConfTypeDef sConfig = {0};
  DAC_AutonomousModeConfTypeDef sAutonomousMode = {0};

  /* USER CODE BEGIN DAC1_Init 1 */

  /* USER CODE END DAC1_Init 1 */

  /** DAC Initialization
  */
  hdac1.Instance = DAC1;

  if (HAL_DAC_Init(&hdac1) != HAL_OK)
  {
    Error_Handler();
  }

  /** DAC channel OUT1 config
  */
  sConfig.DAC_HighFrequency = DAC_HIGH_FREQUENCY_INTERFACE_MODE_ABOVE_80MHZ;
  sConfig.DAC_DMADoubleDataMode = DISABLE;
  sConfig.DAC_SignedFormat = DISABLE;
  sConfig.DAC_SampleAndHold = DAC_SAMPLEANDHOLD_DISABLE;
  sConfig.DAC_Trigger = DAC_TRIGGER_T2_TRGO;
  sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE;
  sConfig.DAC_ConnectOnChipPeripheral = DAC_CHIPCONNECT_EXTERNAL;
  sConfig.DAC_UserTrimming = DAC_TRIMMING_FACTORY;
  if (HAL_DAC_ConfigChannel(&hdac1, &sConfig, DAC_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Autonomous Mode
  */
  sAutonomousMode.AutonomousModeState = DAC_AUTONOMOUS_MODE_DISABLE;
  if (HAL_DACEx_SetConfigAutonomousMode(&hdac1, &sAutonomousMode) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN DAC1_Init 2 */

  /* USER CODE END DAC1_Init 2 */

}

void HAL_DAC_MspInit(DAC_HandleTypeDef* dacHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
  if(dacHandle->Instance==DAC1)
  {
  /* USER CODE BEGIN DAC1_MspInit 0 */

  /* USER CODE END DAC1_MspInit 0 */

  /** Initializes the peripherals clock
  */
    PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADCDAC|RCC_PERIPHCLK_DAC1;
    PeriphClkInit.AdcDacClockSelection = RCC_ADCDACCLKSOURCE_HSI;
    PeriphClkInit.Dac1ClockSelection = RCC_DAC1CLKSOURCE_LSI;
    if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
    {
      Error_Handler();
    }

    /* DAC1 clock enable */
    __HAL_RCC_DAC1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**DAC1 GPIO Configuration
    PA4     ------> DAC1_OUT1
    */
    GPIO_InitStruct.Pin = GPIO_PIN_4;
    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* DAC1 DMA Init */
    /* GPDMA1_REQUEST_DAC1_CH1 Init */
    handle_GPDMA1_Channel10.Instance = GPDMA1_Channel10;
    handle_GPDMA1_Channel10.Init.Request = GPDMA1_REQUEST_DAC1_CH1;
    handle_GPDMA1_Channel10.Init.BlkHWRequest = DMA_BREQ_SINGLE_BURST;
    handle_GPDMA1_Channel10.Init.Direction = DMA_MEMORY_TO_PERIPH;
    handle_GPDMA1_Channel10.Init.SrcInc = DMA_SINC_INCREMENTED;
    handle_GPDMA1_Channel10.Init.DestInc = DMA_DINC_FIXED;
    handle_GPDMA1_Channel10.Init.SrcDataWidth = DMA_SRC_DATAWIDTH_HALFWORD;
    handle_GPDMA1_Channel10.Init.DestDataWidth = DMA_DEST_DATAWIDTH_BYTE;
    handle_GPDMA1_Channel10.Init.Priority = DMA_LOW_PRIORITY_LOW_WEIGHT;
    handle_GPDMA1_Channel10.Init.SrcBurstLength = 1;
    handle_GPDMA1_Channel10.Init.DestBurstLength = 1;
    handle_GPDMA1_Channel10.Init.TransferAllocatedPort = DMA_SRC_ALLOCATED_PORT1|DMA_DEST_ALLOCATED_PORT0;
    handle_GPDMA1_Channel10.Init.TransferEventMode = DMA_TCEM_BLOCK_TRANSFER;
    handle_GPDMA1_Channel10.Init.Mode = DMA_NORMAL;
    if (HAL_DMA_Init(&handle_GPDMA1_Channel10) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(dacHandle, DMA_Handle1, handle_GPDMA1_Channel10);

    if (HAL_DMA_ConfigChannelAttributes(&handle_GPDMA1_Channel10, DMA_CHANNEL_NPRIV) != HAL_OK)
    {
      Error_Handler();
    }

    /* DAC1 interrupt Init */
    HAL_NVIC_SetPriority(DAC1_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(DAC1_IRQn);
  /* USER CODE BEGIN DAC1_MspInit 1 */

  /* USER CODE END DAC1_MspInit 1 */
  }
}

void HAL_DAC_MspDeInit(DAC_HandleTypeDef* dacHandle)
{

  if(dacHandle->Instance==DAC1)
  {
  /* USER CODE BEGIN DAC1_MspDeInit 0 */

  /* USER CODE END DAC1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_DAC1_CLK_DISABLE();

    /**DAC1 GPIO Configuration
    PA4     ------> DAC1_OUT1
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_4);

    /* DAC1 DMA DeInit */
    HAL_DMA_DeInit(dacHandle->DMA_Handle1);

    /* DAC1 interrupt Deinit */
    HAL_NVIC_DisableIRQ(DAC1_IRQn);
  /* USER CODE BEGIN DAC1_MspDeInit 1 */

  /* USER CODE END DAC1_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */

////////////////////////////////////////////////////////

/* Includes ------------------------------------------------------------------*/
#include "gpdma.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* GPDMA1 init function */
void MX_GPDMA1_Init(void)
{

  /* USER CODE BEGIN GPDMA1_Init 0 */

  /* USER CODE END GPDMA1_Init 0 */

  /* Peripheral clock enable */
  __HAL_RCC_GPDMA1_CLK_ENABLE();

  /* GPDMA1 interrupt Init */
    HAL_NVIC_SetPriority(GPDMA1_Channel10_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(GPDMA1_Channel10_IRQn);

  /* USER CODE BEGIN GPDMA1_Init 1 */

  /* USER CODE END GPDMA1_Init 1 */
  /* USER CODE BEGIN GPDMA1_Init 2 */

  /* USER CODE END GPDMA1_Init 2 */

}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */

////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
////this is configuration of the timers //////////////

/* Includes ------------------------------------------------------------------*/
#include "tim.h"

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

TIM_HandleTypeDef htim2;

/* TIM2 init function */
void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 0;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 2999;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */

}

void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
{

  if(tim_baseHandle->Instance==TIM2)
  {
  /* USER CODE BEGIN TIM2_MspInit 0 */

  /* USER CODE END TIM2_MspInit 0 */
    /* TIM2 clock enable */
    __HAL_RCC_TIM2_CLK_ENABLE();

    /* TIM2 interrupt Init */
    HAL_NVIC_SetPriority(TIM2_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(TIM2_IRQn);
  /* USER CODE BEGIN TIM2_MspInit 1 */

  /* USER CODE END TIM2_MspInit 1 */
  }
}

void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* tim_baseHandle)
{

  if(tim_baseHandle->Instance==TIM2)
  {
  /* USER CODE BEGIN TIM2_MspDeInit 0 */

  /* USER CODE END TIM2_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_TIM2_CLK_DISABLE();

    /* TIM2 interrupt Deinit */
    HAL_NVIC_DisableIRQ(TIM2_IRQn);
  /* USER CODE BEGIN TIM2_MspDeInit 1 */

  /* USER CODE END TIM2_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */

/* USER CODE END 1 */

Please give me advice on how to work with call back function correctly.


来源: stackexchange

问:
Change the color of the background of text from a search
Newbie coder here. Recently I asked a question that I think may have been a bit misunderstood (my fault I have no doubt.)

I have a javascript that works in a pdf. The code below does work for me, so while it may not be the prettiest of codes...it works.

It makes use of the Acrobat JavaScript API.
Look here for further details:
https://opensource.adobe.com/dc-acrobat-sdk-docs/library/jsdevguide/index.html

What I want to do is change the background of my search result. I work with technical manuals, this code is meant to go from one page in an illustrated parts list (lets say item 80) to an illustration on another page, and highlight the callout for item 80. This code will do this, but I want to be able to highlight the callout in yellow or green instead of the default blueish grey color to help it stand out more clearly in acrobat.

I have inserted the if (nWait=="0") so that I can actually manipulate it to go to the specific result (often there can be more than 1 "80" on the page, so that's why I've used that, I can increment as I need to.

Here is my code...This is inserted directly into the link from the properties menu in Acrobat.

Again, I am new to this, I know very little and need all the help I can get.

```<code>nWait = 0;
nWords = getPageNumWords(217);
   for (var loop = 0; loop < [nWords - 1]; loop++) {
     word = getPageNthWord(217, loop);
     if (word == "80") {
       if (nWait == "0") {
         this.selectPageNthWord(217, loop);
         break;
       }
       nWait = nWait + 1;
     }
}
</code>```

I have searched the internet and have really not found much that makes sense to me. Be kind.

API reference:

getPageNumWords

https://opensource.adobe.com/dc-acrobat-sdk-docs/library/jsapiref/doc.html?highlight=selectpagenthword#getpagenumwords

getPageNthWord

https://opensource.adobe.com/dc-acrobat-sdk-docs/library/jsapiref/doc.html?highlight=selectpagenthword#getpagenthword

selectPageNthWord

https://opensource.adobe.com/dc-acrobat-sdk-docs/library/jsapiref/doc.html?highlight=selectpagenthword#selectpagenthword

ContentLicense: CC BY-SA 4.0

Body:
Newbie coder here. Recently I asked a question that I think may have been a bit misunderstood (my fault I have no doubt.)

I have a javascript that works in a pdf. The code below does work for me, so while it may not be the prettiest of codes...it works.

It makes use of the Acrobat JavaScript API.
Look here for further details:
https://opensource.adobe.com/dc-acrobat-sdk-docs/library/jsdevguide/index.html

What I want to do is change the background of my search result. I work with technical manuals, this code is meant to go from one page in an illustrated parts list (lets say item 80) to an illustration on another page, and highlight the callout for item 80. This code will do this, but I want to be able to highlight the callout in yellow or green instead of the default blueish grey color to help it stand out more clearly in acrobat.

I have inserted the if (nWait=="0") so that I can actually manipulate it to go to the specific result (often there can be more than 1 "80" on the page, so that's why I've used that, I can increment as I need to.

Here is my code...This is inserted directly into the link from the properties menu in Acrobat.

Again, I am new to this, I know very little and need all the help I can get.

nWait = 0;
nWords = getPageNumWords(217);
   for (var loop = 0; loop < [nWords - 1]; loop++) {
     word = getPageNthWord(217, loop);
     if (word == "80") {
       if (nWait == "0") {
         this.selectPageNthWord(217, loop);
         break;
       }
       nWait = nWait + 1;
     }
}

I have searched the internet and have really not found much that makes sense to me. Be kind.

API reference:

getPageNumWords

https://opensource.adobe.com/dc-acrobat-sdk-docs/library/jsapiref/doc.html?highlight=selectpagenthword#getpagenumwords

getPageNthWord

https://opensource.adobe.com/dc-acrobat-sdk-docs/library/jsapiref/doc.html?highlight=selectpagenthword#getpagenthword

selectPageNthWord

https://opensource.adobe.com/dc-acrobat-sdk-docs/library/jsapiref/doc.html?highlight=selectpagenthword#selectpagenthword


问:
When I deploy my new project to rail and the website needs to use the puppeteer module, I get this error and I don't know how to fix it
I don't know what can I do to resolve this problem.

I create an application with puppeteer, it uses data from some pages and displays it in a table, now it will only let me mount it and use rail, the main page works very well, but when I want to enter the page that executes the puppeteer commands it gives me the following error

```<code>Server on port  6172
file:///app/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.js:269
reject(new Error([
^
Error: Failed to launch the browser process!
[0102/220036.855613:ERROR:zygote_host_impl_linux.cc(100)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.
TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md
at onClose (file:///app/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.js:269:20)
at Interface.<anonymous> (file:///app/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.js:257:24)
at Interface.emit (node:events:525:35)
at Interface.close (node:readline:590:8)
at Socket.onend (node:readline:280:10)
at Socket.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
</code>```

the app works until I need to use puppeter (sorry for my poor English)

I think it is because there is no chromium that can be used, I don't know what to do

Body:
I don't know what can I do to resolve this problem.

I create an application with puppeteer, it uses data from some pages and displays it in a table, now it will only let me mount it and use rail, the main page works very well, but when I want to enter the page that executes the puppeteer commands it gives me the following error

Server on port  6172
file:///app/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.js:269
reject(new Error([
^
Error: Failed to launch the browser process!
[0102/220036.855613:ERROR:zygote_host_impl_linux.cc(100)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.
TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md
at onClose (file:///app/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.js:269:20)
at Interface.<anonymous> (file:///app/node_modules/puppeteer-core/lib/esm/puppeteer/node/BrowserRunner.js:257:24)
at Interface.emit (node:events:525:35)
at Interface.close (node:readline:590:8)
at Socket.onend (node:readline:280:10)
at Socket.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)

the app works until I need to use puppeter (sorry for my poor English)

I think it is because there is no chromium that can be used, I don't know what to do


问:
Python crashing on macOS ARM M1
I recently installed Python 3.10.9 using Brew on my ARM mac (macOS 13.1 Ventura) but when running any of my Python script with PyCharm (native for ARM using a system env with Python 3.10.9 /usr/local/bin/python3), Python crashes and returns one of the 2 error reports, as shown below:

```<code>-------------------------------------
Translated Report (Full Report Below)
-------------------------------------

Process:               Python [78382]
Path:                  /Library/Frameworks/Python.framework/Versions/3.10/Resources/Python.app/Contents/MacOS/Python
Identifier:            org.python.python
Version:               3.10.9 (3.10.9)
Code Type:             ARM-64 (Native)
Parent Process:        pycharm [77323]
Responsible:           pycharm [77323]
User ID:               501

Date/Time:             2023-01-02 19:22:46.8969 +0100
OS Version:            macOS 13.1 (22C65)
Report Version:        12
Anonymous UUID:        90007ABA-5D79-9CD1-C540-78C58ED447AC

Sleep/Wake UUID:       C0F3DA32-9A4C-40DA-B838-0C43B7D63AA1

Time Awake Since Boot: 22000 seconds
Time Since Wake:       59 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x000000000000001e
Exception Codes:       0x0000000000000001, 0x000000000000001e

Termination Reason:    Namespace SIGNAL, Code 11 Segmentation fault: 11
Terminating Process:   exc handler [78382]

</code>```
```<code>-------------------------------------
Translated Report (Full Report Below)
-------------------------------------

Process:               Python [86657]
Path:                  /Library/Frameworks/Python.framework/Versions/3.10/Resources/Python.app/Contents/MacOS/Python
Identifier:            org.python.python
Version:               3.10.9 (3.10.9)
Code Type:             ARM-64 (Native)
Parent Process:        pycharm [84646]
Responsible:           pycharm [84646]
User ID:               501

Date/Time:             2023-01-02 22:59:59.8243 +0100
OS Version:            macOS 13.1 (22C65)
Report Version:        12
Anonymous UUID:        90007ABA-5D79-9CD1-C540-78C58ED447AC

Sleep/Wake UUID:       C7252D6D-6A22-475B-BEB4-81B2B1C35C73

Time Awake Since Boot: 30000 seconds
Time Since Wake:       1526 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BREAKPOINT (SIGTRAP)
Exception Codes:       0x0000000000000001, 0x00000001a3b8e810

Termination Reason:    Namespace SIGNAL, Code 5 Trace/BPT trap: 5
Terminating Process:   exc handler [86657]
</code>```

I saw that sometimes Python's installation using Brew can sometimes results in weird issues, therefore I tried to uninstall and reinstall using Python installer from Python.org. Didn't change a thing.

Also uninstall/reinstall openssl, tried with version 1.0.2t, 1.1.1s and 3.0.7. Tried this solution, which worked on my intel mac. Yet, this failed to solve the matter here.

I then tried to manually link openssl. Didn't solve my issue.

And at last, I tried using lido to combine binaries, both the intel and ARM versions, but this solution didn't work, both command cp -r openssl-1.1.1s openssl-1.1.1s-arm64 and cp -r openssl-1.1.1s openssl-1.1.1s-x86_x64 returned cp: openssl-1.1.1s: No such file or directory, even when openssl@1.1 (version 1.1.1s) is installed using Brew.

So far none of those solutions worked for me.

Title: Python crashing on macOS ARM M1

Body:
I recently installed Python 3.10.9 using Brew on my ARM mac (macOS 13.1 Ventura) but when running any of my Python script with PyCharm (native for ARM using a system env with Python 3.10.9 /usr/local/bin/python3), Python crashes and returns one of the 2 error reports, as shown below:

-------------------------------------
Translated Report (Full Report Below)
-------------------------------------

Process:               Python [78382]
Path:                  /Library/Frameworks/Python.framework/Versions/3.10/Resources/Python.app/Contents/MacOS/Python
Identifier:            org.python.python
Version:               3.10.9 (3.10.9)
Code Type:             ARM-64 (Native)
Parent Process:        pycharm [77323]
Responsible:           pycharm [77323]
User ID:               501

Date/Time:             2023-01-02 19:22:46.8969 +0100
OS Version:            macOS 13.1 (22C65)
Report Version:        12
Anonymous UUID:        90007ABA-5D79-9CD1-C540-78C58ED447AC

Sleep/Wake UUID:       C0F3DA32-9A4C-40DA-B838-0C43B7D63AA1

Time Awake Since Boot: 22000 seconds
Time Since Wake:       59 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x000000000000001e
Exception Codes:       0x0000000000000001, 0x000000000000001e

Termination Reason:    Namespace SIGNAL, Code 11 Segmentation fault: 11
Terminating Process:   exc handler [78382]

-------------------------------------
Translated Report (Full Report Below)
-------------------------------------

Process:               Python [86657]
Path:                  /Library/Frameworks/Python.framework/Versions/3.10/Resources/Python.app/Contents/MacOS/Python
Identifier:            org.python.python
Version:               3.10.9 (3.10.9)
Code Type:             ARM-64 (Native)
Parent Process:        pycharm [84646]
Responsible:           pycharm [84646]
User ID:               501

Date/Time:             2023-01-02 22:59:59.8243 +0100
OS Version:            macOS 13.1 (22C65)
Report Version:        12
Anonymous UUID:        90007ABA-5D79-9CD1-C540-78C58ED447AC

Sleep/Wake UUID:       C7252D6D-6A22-475B-BEB4-81B2B1C35C73

Time Awake Since Boot: 30000 seconds
Time Since Wake:       1526 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BREAKPOINT (SIGTRAP)
Exception Codes:       0x0000000000000001, 0x00000001a3b8e810

Termination Reason:    Namespace SIGNAL, Code 5 Trace/BPT trap: 5
Terminating Process:   exc handler [86657]

I saw that sometimes Python's installation using Brew can sometimes results in weird issues, therefore I tried to uninstall and reinstall using Python installer from Python.org. Didn't change a thing.

Also uninstall/reinstall openssl, tried with version 1.0.2t, 1.1.1s and 3.0.7. Tried this solution, which worked on my intel mac. Yet, this failed to solve the matter here.

I then tried to manually link openssl. Didn't solve my issue.

And at last, I tried using lido to combine binaries, both the intel and ARM versions, but this solution didn't work, both command cp -r openssl-1.1.1s openssl-1.1.1s-arm64 and cp -r openssl-1.1.1s openssl-1.1.1s-x86_x64 returned cp: openssl-1.1.1s: No such file or directory, even when openssl@1.1 (version 1.1.1s) is installed using Brew.

So far none of those solutions worked for me.


问:
Run own maven plugin from local classes folder or jar but not from local repo
I develop a Maven plugin and trying to find an easy way to test it.
One of the ways is to use embedder, and it works great (I run it from JUnit).
My scenario requires more real-time testing rather than maven-testing-harness approach but I use both.

But in order to use my plugin I have to install it to local repo (otherwise it can't be found).
So the question is - if there's any way to run plugin by directly adding it to classpath?

I've tried to find a way to add it to classpath, no luck so far. Have a thought to configure an additional virtual repository but seems too complicated for this case.


问:
RecursionError on SQLAlchemy when using Loader options to eager load self referencial relationship
I am working with the following project: A CRUD for a system with dynamic models. To utilize SQL Alchemy ORM features, I am using automap_base to load the table models and be able to traverse the relationships and such.

In one particular case, I have a User table, which has a CreatedByUserId, UpdatedByUserId, and DeletedByUserId.

If I try to fetch a User with its CreatedByUser related model, using the following query:

Base = automap_base()
tables = Base.classes
model = (db.query(tables['User'])
        .options(
            joinedload(tables['User'].CreatedByUser)
        )
        .first())
```
<p>I get a <code>RecursionError: maximum recursion depth exceeded</code></p>
<p>Reading the documentation, what I guess happens is that SQLAlchemy enables eager loading for the User-CreatedByUser relationship for the entire query, so every time a User appears in the query, it fetches the CreatedByUser which results in an infinite loop. To be clear, what the optimal result would be is just the User model with a "CreatedByUser" attribute with the associated CreatedByUser model.</p>
<p>I tried adding a <code>noload()</code> or <code>lazyload('*')</code> at the end of the joinedload and using selectinload, subqueryload or immediateload with no luck.</p>
<p>.</p>
<p>Edit: After continuing to read SQLAlchemy documentation, I believe the error is due to the CreatedByUser being the same as the original. For example, having a user:</p>
```{
  id:3
  createdByUserId:3
}
```

However, I'm nowhere closer to finding a solution.

Body:
I am working with the following project: A CRUD for a system with dynamic models. To utilize SQL Alchemy ORM features, I am using automap_base to load the table models and be able to traverse the relationships and such.

In one particular case, I have a User table, which has a CreatedByUserId, UpdatedByUserId, and DeletedByUserId.

If I try to fetch a User with its CreatedByUser related model, using the following query:

Base = automap_base()
tables = Base.classes
model = (db.query(tables['User'])
        .options(
            joinedload(tables['User'].CreatedByUser)
        )
        .first())

I get a RecursionError: maximum recursion depth exceeded

Reading the documentation, what I guess happens is that SQLAlchemy enables eager loading for the User-CreatedByUser relationship for the entire query, so every time a User appears in the query, it fetches the CreatedByUser which results in an infinite loop. To be clear, what the optimal result would be is just the User model with a "CreatedByUser" attribute with the associated CreatedByUser model.

I tried adding a noload() or lazyload('*') at the end of the joinedload and using selectinload, subqueryload or immediateload with no luck.

.

Edit: After continuing to read SQLAlchemy documentation, I believe the error is due to the CreatedByUser being the same as the original. For example, having a user:

{
  id:3
  createdByUserId:3
}

However, I'm nowhere closer to finding a solution.


问:
Can i use the material ui barcode scanning so ml kit without firebase in a react app?
I would like the features and the intelligence of the google mateiral barcode scanner so Google ML Kit (https://developers.google.com/ml-kit). but i can only develop with firebase on ios or android. is there a similiar framework in mui or am i able to use a intelligent barcode scanner like the material ui barcode scanner in react?

I didnt have any code till now (for the barcode module), but have to decide with framework to use


问:
Is there a way to ignore segfaults on exit of R processes?
In some R processes, I occasionally see the following on process exit:

```<code>*** caught segfault ***
address 0x80, cause 'memory not mapped'

Traceback:
1: x$unload()
2: (function(x) x$unload())(<environment>)

An irrecoverable exception occurred. R is aborting now...
</code>```

There are a few problems keeping me from pinning this down:

The issue happens sporadically

It occasionally goes away on a retry

I don't know which package it's trying to unload

However, since this usually happens on process exit, I'd be fine with just ignoring it, but need an automated way to do so. I also don't really care whether the package is unloaded.

In summary, I'm looking for one of the following:

A way to prevent R from unloading packages

A way to determine whether the segmentation fault is happening at the end of a process, after the rest of the process has completed, so I can ignore any resulting segfault

A way of figuring out which package is causing this problem would help, but it's not certain I can just stop using the package even if I know which one it is

Ideally, whatever solution I use would not require changing the R code of an existing process since I may need to apply this to several processes (otherwise, I could, for example, just write a file when the process succeeds).

I've tried to strace the process to see which call is causing the segfault to get to the bottom of it, which has not returned useful results, but I'd rather just ignore it if possible.

Body:
In some R processes, I occasionally see the following on process exit:

*** caught segfault ***
address 0x80, cause 'memory not mapped'

Traceback:
1: x$unload()
2: (function(x) x$unload())(<environment>)

An irrecoverable exception occurred. R is aborting now...

There are a few problems keeping me from pinning this down:

The issue happens sporadically

It occasionally goes away on a retry

I don't know which package it's trying to unload

However, since this usually happens on process exit, I'd be fine with just ignoring it, but need an automated way to do so. I also don't really care whether the package is unloaded.

In summary, I'm looking for one of the following:

A way to prevent R from unloading packages

A way to determine whether the segmentation fault is happening at the end of a process, after the rest of the process has completed, so I can ignore any resulting segfault

A way of figuring out which package is causing this problem would help, but it's not certain I can just stop using the package even if I know which one it is

Ideally, whatever solution I use would not require changing the R code of an existing process since I may need to apply this to several processes (otherwise, I could, for example, just write a file when the process succeeds).

I've tried to strace the process to see which call is causing the segfault to get to the bottom of it, which has not returned useful results, but I'd rather just ignore it if possible.


问:
Disabling Pylint warnings in VSCode Version 1.74 not working
I am using VSCode 1.74 (the latest at the time of writing), and I am trying to disable some linting warnings in Pylint globally.
The warnings are:

Missing module docstringpylint(missing-module-docstring - C0114)

Missing class docstringpylint(missing-class-docstring - C0115)

Missing function docstringpylint(missing-function-docstring - C0116)

So as per the other answers on this site, I have tried adding the python.linting.pylintArgs in settings.json found in "Preferences:Open User Settings(JSON)" as shown below, but none is working out for me:

method 1

"python.linting.pylintArgs": [
        "--disable=missing-module-docstring",
        "--disable=missing-class-docstring",
        "--disable=missing-function-docstring"
      ]
```
<p><code>method 2</code></p>
<pre class="lang-json prettyprint-override"><code>"python.linting.pylintArgs": [
        "--disable=C0111"
    ]
</code>```

method 3

"python.linting.pylintArgs": [
        "--disable=C0114",
        "--disable=C0115",
        "--disable=C0116"
    ]
```

But the warnings still persist.
Any suggestions?

Body:
I am using VSCode 1.74 (the latest at the time of writing), and I am trying to disable some linting warnings in Pylint globally.
The warnings are:

Missing module docstringpylint(missing-module-docstring - C0114)

Missing class docstringpylint(missing-class-docstring - C0115)

Missing function docstringpylint(missing-function-docstring - C0116)

So as per the other answers on this site, I have tried adding the python.linting.pylintArgs in settings.json found in "Preferences:Open User Settings(JSON)" as shown below, but none is working out for me:

method 1

"python.linting.pylintArgs": [
        "--disable=missing-module-docstring",
        "--disable=missing-class-docstring",
        "--disable=missing-function-docstring"
      ]

method 2

"python.linting.pylintArgs": [
        "--disable=C0111"
    ]

method 3

"python.linting.pylintArgs": [
        "--disable=C0114",
        "--disable=C0115",
        "--disable=C0116"
    ]

But the warnings still persist.
Any suggestions?


问:
.call() function isn't working on web3.eth.Contract method
I'm using Next.js 13 and Web3 1.8 and I'm trying to retrieve the owner on the smart contract I wrote and the call() function won't work for some reason.
const picturesVault = await PicturesVaultContract(accountAddress).methods.owner().call();

I keep getting this error when trying to execute that function on the owner method?

Unhandled Runtime Error

Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.

Is there anyway to resolve this issue?

VaultsComponent Index.tsx

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

// Contracts
import { PicturesVaultContract } from '../../../../ethereum/canvas.js';
import { StoriesVaultContract } from '../../../../ethereum/canvas.js';
import { VideosVaultContract } from '../../../../ethereum/canvas.js';

// Components
import Layout from '../../../../components/Layout';
import CanvasHeader from '../../../../components/CanvasHeader';
import CanvasFooter from '../../../../components/CanvasFooter';
import VaultsList from '../../../../components/vaults/VaultsList';

// Vault Data
import { VAULT_DESCRIPTION } from '../../../../data/vaults_data';

// Utils
import { filterVaults } from '../../../../lib/utils.lib';

const Vaults = () => {
    const [vaults, setVaults]: any = useState([]);
    // const [isLoaded, setIsLoaded] = useState(false);

    const getVaults = async () => {
        const accountAddress = process.env.METAMASK_ACCOUNT_ADDRESS;

        const picturesVault = await PicturesVaultContract(accountAddress)
            .methods.owner()
            .call();
        // .send({ from: accountAddress, gas: '1000000' });

        const storiesVault = await StoriesVaultContract(accountAddress)
            .methods.owner()
            .call();
        // .send({ from: accountAddress, gas: '1000000' });

        const videosVault = await VideosVaultContract(accountAddress)
            .methods.owner()
            .call();
        // .send({ from: accountAddress, gas: '1000000' });

        console.log(picturesVault);
        console.log(storiesVault);
        console.log(videosVault);

        const vaults = [picturesVault, storiesVault, videosVault];

        const loadedVaults = vaults.map((address) => {
            const loadedVault = filterVaults(address, vaults);

            return loadedVault;
        });

        console.log(loadedVaults);

        setVaults(loadedVaults);
    };

    getVaults();

    return (

            <Layout>
                <CanvasHeader />

Vaults

{VAULT_DESCRIPTION}

                    <VaultsList vaults={vaults} />

            </Layout>
            <CanvasFooter />

    );
};

export default Vaults;

```
<p>deploy.js</p>
<pre class="lang-js prettyprint-override"><code>const HDWalletProvider = require('@truffle/hdwallet-provider');

const Web3 = require('web3');

const compiledPicturesVaultContract = require('./build/PicturesVault.json');
const compiledStoriesVaultContract = require('./build/StoriesVault.json');
const compiledVideosVaultContract = require('./build/VideosVault.json');

const provider = new HDWalletProvider(
    '[METAMASK_SEED_PHRASE]',
    '[GOERLI_INFURA_TEST_NODE_URL]'
);

const web3 = new Web3(provider);

const deploy = async () => {
    const accounts = await web3.eth.getAccounts();

    console.log('Attempting to deploy from account', accounts[0]);

    // Pictures Vault
    const compiledPicturesVaultContractResult = await new web3.eth.Contract(
        JSON.parse(JSON.stringify(compiledPicturesVaultContract.PicturesVault.abi))
    )
        .deploy({
            data: compiledPicturesVaultContract.PicturesVault.evm.bytecode.object,
            arguments: [],
        })
        .send({ gas: '10000000', from: accounts[0] });

    // Stories Vault
    const compiledStoriesVaultContractResult = await new web3.eth.Contract(
        JSON.parse(JSON.stringify(compiledStoriesVaultContract.StoriesVault.abi))
    )
        .deploy({
            data: compiledStoriesVaultContract.StoriesVault.evm.bytecode.object,
            arguments: [],
        })
        .send({ gas: '10000000', from: accounts[0] });

    // Videos Vault
    const compiledVideosVaultContractResult = await new web3.eth.Contract(
        JSON.parse(JSON.stringify(compiledVideosVaultContract.VideosVault.abi))
    )
        .deploy({
            data: compiledVideosVaultContract.VideosVault.evm.bytecode.object,
            arguments: [],
        })
        .send({ gas: '10000000', from: accounts[0] });

    const PicturesVaultAddress =
        compiledPicturesVaultContractResult.options.address;
    const StoriesVaultAddress =
        compiledStoriesVaultContractResult.options.address;
    const VideosVaultAddress = compiledVideosVaultContractResult.options.address;

    console.log('Deployed PicturesVault Contract to', PicturesVaultAddress);
    console.log('Deployed StoriesVault Contract to', StoriesVaultAddress);
    console.log('Deployed VideosVault Contract to', VideosVaultAddress);

    provider.engine.stop();
};

deploy();

</code>```

canvas.js

import web3 from './web3';

import PicturesVault from './build/PicturesVault.json';
import StoriesVault from './build/StoriesVault.json';
import VideosVault from './build/VideosVault.json';

export const PicturesVaultContract = (address) => {
    return new web3.eth.Contract(
        JSON.parse(JSON.stringify(PicturesVault.PicturesVault.abi)),
        address
    );
};

export const StoriesVaultContract = (address) => {
    return new web3.eth.Contract(
        JSON.parse(JSON.stringify(StoriesVault.StoriesVault.abi)),
        address
    );
};

export const VideosVaultContract = (address) => {
    return new web3.eth.Contract(
        JSON.parse(JSON.stringify(VideosVault.VideosVault.abi)),
        address
    );
};

```
<p>web3.js</p>
<pre class="lang-js prettyprint-override"><code>import Web3 from 'web3';

let web3;

if (typeof window !== 'undefined' && typeof window.ethereum !== 'undefined') {
    // We are in the browser and metamask is running.
    window.ethereum.request({ method: 'eth_requestAccounts' });

    web3 = new Web3(window.ethereum);
} else {
    // We are on the server *OR* the user is not running metamask
    const provider = new Web3.providers.HttpProvider(
        // '[GOERLI_INFURA_TEST_NODE]'
    );
    web3 = new Web3(provider);
}

export default web3;

</code>```

I've already tried using the send method to send a transaction which works, however, I don't want to send a transaction everytime I need to access the address. On top of that, it just prints out the tranasaction object instead of the owner's address.

I've also tried using async/await when creating the contract instance in canvas.js

Body:
I'm using Next.js 13 and Web3 1.8 and I'm trying to retrieve the owner on the smart contract I wrote and the call() function won't work for some reason.
const picturesVault = await PicturesVaultContract(accountAddress).methods.owner().call();

I keep getting this error when trying to execute that function on the owner method?

Unhandled Runtime Error

Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.

Is there anyway to resolve this issue?

VaultsComponent Index.tsx

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

// Contracts
import { PicturesVaultContract } from '../../../../ethereum/canvas.js';
import { StoriesVaultContract } from '../../../../ethereum/canvas.js';
import { VideosVaultContract } from '../../../../ethereum/canvas.js';

// Components
import Layout from '../../../../components/Layout';
import CanvasHeader from '../../../../components/CanvasHeader';
import CanvasFooter from '../../../../components/CanvasFooter';
import VaultsList from '../../../../components/vaults/VaultsList';

// Vault Data
import { VAULT_DESCRIPTION } from '../../../../data/vaults_data';

// Utils
import { filterVaults } from '../../../../lib/utils.lib';

const Vaults = () => {
    const [vaults, setVaults]: any = useState([]);
    // const [isLoaded, setIsLoaded] = useState(false);

    const getVaults = async () => {
        const accountAddress = process.env.METAMASK_ACCOUNT_ADDRESS;

        const picturesVault = await PicturesVaultContract(accountAddress)
            .methods.owner()
            .call();
        // .send({ from: accountAddress, gas: '1000000' });

        const storiesVault = await StoriesVaultContract(accountAddress)
            .methods.owner()
            .call();
        // .send({ from: accountAddress, gas: '1000000' });

        const videosVault = await VideosVaultContract(accountAddress)
            .methods.owner()
            .call();
        // .send({ from: accountAddress, gas: '1000000' });

        console.log(picturesVault);
        console.log(storiesVault);
        console.log(videosVault);

        const vaults = [picturesVault, storiesVault, videosVault];

        const loadedVaults = vaults.map((address) => {
            const loadedVault = filterVaults(address, vaults);

            return loadedVault;
        });

        console.log(loadedVaults);

        setVaults(loadedVaults);
    };

    getVaults();

    return (

            <Layout>
                <CanvasHeader />

Vaults

{VAULT_DESCRIPTION}

                    <VaultsList vaults={vaults} />

            </Layout>
            <CanvasFooter />

    );
};

export default Vaults;

deploy.js

const HDWalletProvider = require('@truffle/hdwallet-provider');

const Web3 = require('web3');

const compiledPicturesVaultContract = require('./build/PicturesVault.json');
const compiledStoriesVaultContract = require('./build/StoriesVault.json');
const compiledVideosVaultContract = require('./build/VideosVault.json');

const provider = new HDWalletProvider(
    '[METAMASK_SEED_PHRASE]',
    '[GOERLI_INFURA_TEST_NODE_URL]'
);

const web3 = new Web3(provider);

const deploy = async () => {
    const accounts = await web3.eth.getAccounts();

    console.log('Attempting to deploy from account', accounts[0]);

    // Pictures Vault
    const compiledPicturesVaultContractResult = await new web3.eth.Contract(
        JSON.parse(JSON.stringify(compiledPicturesVaultContract.PicturesVault.abi))
    )
        .deploy({
            data: compiledPicturesVaultContract.PicturesVault.evm.bytecode.object,
            arguments: [],
        })
        .send({ gas: '10000000', from: accounts[0] });

    // Stories Vault
    const compiledStoriesVaultContractResult = await new web3.eth.Contract(
        JSON.parse(JSON.stringify(compiledStoriesVaultContract.StoriesVault.abi))
    )
        .deploy({
            data: compiledStoriesVaultContract.StoriesVault.evm.bytecode.object,
            arguments: [],
        })
        .send({ gas: '10000000', from: accounts[0] });

    // Videos Vault
    const compiledVideosVaultContractResult = await new web3.eth.Contract(
        JSON.parse(JSON.stringify(compiledVideosVaultContract.VideosVault.abi))
    )
        .deploy({
            data: compiledVideosVaultContract.VideosVault.evm.bytecode.object,
            arguments: [],
        })
        .send({ gas: '10000000', from: accounts[0] });

    const PicturesVaultAddress =
        compiledPicturesVaultContractResult.options.address;
    const StoriesVaultAddress =
        compiledStoriesVaultContractResult.options.address;
    const VideosVaultAddress = compiledVideosVaultContractResult.options.address;

    console.log('Deployed PicturesVault Contract to', PicturesVaultAddress);
    console.log('Deployed StoriesVault Contract to', StoriesVaultAddress);
    console.log('Deployed VideosVault Contract to', VideosVaultAddress);

    provider.engine.stop();
};

deploy();

canvas.js

import web3 from './web3';

import PicturesVault from './build/PicturesVault.json';
import StoriesVault from './build/StoriesVault.json';
import VideosVault from './build/VideosVault.json';

export const PicturesVaultContract = (address) => {
    return new web3.eth.Contract(
        JSON.parse(JSON.stringify(PicturesVault.PicturesVault.abi)),
        address
    );
};

export const StoriesVaultContract = (address) => {
    return new web3.eth.Contract(
        JSON.parse(JSON.stringify(StoriesVault.StoriesVault.abi)),
        address
    );
};

export const VideosVaultContract = (address) => {
    return new web3.eth.Contract(
        JSON.parse(JSON.stringify(VideosVault.VideosVault.abi)),
        address
    );
};

web3.js

import Web3 from 'web3';

let web3;

if (typeof window !== 'undefined' && typeof window.ethereum !== 'undefined') {
    // We are in the browser and metamask is running.
    window.ethereum.request({ method: 'eth_requestAccounts' });

    web3 = new Web3(window.ethereum);
} else {
    // We are on the server *OR* the user is not running metamask
    const provider = new Web3.providers.HttpProvider(
        // '[GOERLI_INFURA_TEST_NODE]'
    );
    web3 = new Web3(provider);
}

export default web3;

I've already tried using the send method to send a transaction which works, however, I don't want to send a transaction everytime I need to access the address. On top of that, it just prints out the tranasaction object instead of the owner's address.

I've also tried using async/await when creating the contract instance in canvas.js


问:
Lifetime of an object when it's only referenced but not owned
Let's say I have this piece of Rust code:

#[derive(Debug)]
struct TestStruct<'a> {
    attr: &'a str
}

impl<'a> TestStruct<'a> {
     fn new() -> TestStruct<'a> {
        TestStruct {
            attr: "This is an test value"
        }
    }
}

fn main() {
    let val = &mut TestStruct::new();
}
```

If I understand correctly, the val contains a reference to instance of TestStruct. And if I understand correctly variable val is not an owner of this instance, but it borrows it mutably. If so, then who's the owner of the TestStruct instance and when the lifetime of this instance ends?

Body:
Let's say I have this piece of Rust code:

#[derive(Debug)]
struct TestStruct<'a> {
    attr: &'a str
}

impl<'a> TestStruct<'a> {
     fn new() -> TestStruct<'a> {
        TestStruct {
            attr: "This is an test value"
        }
    }
}

fn main() {
    let val = &mut TestStruct::new();
}

If I understand correctly, the val contains a reference to instance of TestStruct. And if I understand correctly variable val is not an owner of this instance, but it borrows it mutably. If so, then who's the owner of the TestStruct instance and when the lifetime of this instance ends?


问:
Change java.util.prefs.Preferences directory
I'm currently building a flatpak for a java app but have ran into a small problem with the way it's saving settings. If possible I'd like to solve it without editing the program itself.

It stores settings using java.util.prefs.Preferences like so

```<code>prefs.put(prefname, val);
</code>```

and this is saved at the default location $HOME/.java/.userPrefs

because I'm bundling openjdk with the app I'd prefer that the preferences weren't saved in the same place that the system install java would store them. I've tried passing these 2 arguments to change the default directory but in both cases the app still writes to $HOME/.java/.userPrefs

```<code>java -Djava.util.prefs.userRoot=$HOME/.var/app/com.test.App/data -jar App.jar
java -Duser.home=$HOME/.var/app/com.test.App/data -jar App.jar

</code>```

I've already tried messing with file permissions and it didn't make a difference

Body:
I'm currently building a flatpak for a java app but have ran into a small problem with the way it's saving settings. If possible I'd like to solve it without editing the program itself.

It stores settings using java.util.prefs.Preferences like so

prefs.put(prefname, val);

and this is saved at the default location $HOME/.java/.userPrefs

because I'm bundling openjdk with the app I'd prefer that the preferences weren't saved in the same place that the system install java would store them. I've tried passing these 2 arguments to change the default directory but in both cases the app still writes to $HOME/.java/.userPrefs

java -Djava.util.prefs.userRoot=$HOME/.var/app/com.test.App/data -jar App.jar
java -Duser.home=$HOME/.var/app/com.test.App/data -jar App.jar

I've already tried messing with file permissions and it didn't make a difference


问:
How to get input to list from user in Scala?
Counting Change

Write a recursive function that counts how many different ways you can make change for an amount, given a list of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2: 1+1+1+1, 1+1+2, 2+2.

Do this exercise by implementing the countChange function in Main.scala. This function takes an amount to change, and a list of unique denominations for the coins. Its signature is as follows:

```<code>def countChange(money: Int, coins: List[Int]): Int
</code>```

Once again, you can make use of functions isEmpty, head and tail on the list of integers coins.

Hint: Think of the degenerate cases. How many ways can you give change for 0 CHF(swiss money)? How many ways can you give change for >0 CHF, if you have no coins?

I tried to do like this, but this error occured

```<code>object main {
  def countChange(money: Int, coins: List[Int]): Int = {
    if (money == 0)
      1
    else if (money > 0 && !coins.isEmpty)
      countChange(money - coins.head, coins) + countChange(money, coins.tail)
    else
      0
  }
  def main(args: Array[String]): Unit = {
    var money = scala.io.StdIn.readInt()
    var coins = scala.io.StdIn.readInt()
    println(countChange(money, coins))
  }
}
</code>```
```<code>type mismatch;
found   : Int
required: List[Int]
println(countChange(money, coins))
</code>```

Body:
Counting Change

Write a recursive function that counts how many different ways you can make change for an amount, given a list of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2: 1+1+1+1, 1+1+2, 2+2.

Do this exercise by implementing the countChange function in Main.scala. This function takes an amount to change, and a list of unique denominations for the coins. Its signature is as follows:

def countChange(money: Int, coins: List[Int]): Int

Once again, you can make use of functions isEmpty, head and tail on the list of integers coins.

Hint: Think of the degenerate cases. How many ways can you give change for 0 CHF(swiss money)? How many ways can you give change for >0 CHF, if you have no coins?

I tried to do like this, but this error occured

object main {
  def countChange(money: Int, coins: List[Int]): Int = {
    if (money == 0)
      1
    else if (money > 0 && !coins.isEmpty)
      countChange(money - coins.head, coins) + countChange(money, coins.tail)
    else
      0
  }
  def main(args: Array[String]): Unit = {
    var money = scala.io.StdIn.readInt()
    var coins = scala.io.StdIn.readInt()
    println(countChange(money, coins))
  }
}

type mismatch;
found   : Int
required: List[Int]
println(countChange(money, coins))


问:
Converting SVG to PNG and appending to document with proper sizing
Okay, so here's a pretty niche question.
I'm using html2canvas to create a screenshot(thumbnail) of a dom element. From there I am creating an image element and appending to that element an SVG which is contained within the parent element as a child.
When I create this screenshot the images show up, but they're breaking out of their bounds.
My question is if there is a way to make my image elements adhere to their bound during this screenshot process.
I am using SvelteKit for my client, if that helps anything at all.

Here is the function which is creating the screenshot:

export const screenshotCanvas = async (element: string): Promise<File | null> => {
    const el: HTMLElement | null = document.querySelector(element);
    const svgAssets = document.querySelectorAll('img');

    if (el) {
        const canvas = await html2canvas(el, {
            allowTaint: true,
            useCORS: true,
            logging: true,
            imageTimeout: 0,
            proxy: 'https://cors-anywhere.herokuapp.com/',
            onclone: (doc) => {
                svgAssets.forEach((asset) => {
                    console.log('assets', asset, asset.width, asset.height)
                    const img = doc.createElement('img');
                    img.src = asset.src;
                    img.width = asset.width;
                    img.height = asset.height;
                    doc.body.appendChild(img);
                });
            }
        });

        const blob = await new Promise((resolve) => canvas.toBlob(resolve));
        // TODO handle error if blob is null somehow
        const file = new File([blob], 'thumbnail.webp', { type: 'image/webp' });
        return file;
    }
    return null;
};
```
<p>Here is the parent element, which is what is being passed into the screenshotCanvas element:</p>
<pre class="lang-js prettyprint-override"><code><div id="canvas" style="background: {background}">
        {#if info.elements}
            {#each info.elements as element}
                <ImgElement {element} />
            {/each}
        {/if}
        {#if $howToIsOpen}
            <HowToModal />
        {/if}
    </div>
</code>```

And here is the child element, which can be any number of elements within the canvas:

    {#if loading}
        <Loading />
    {/if}
    {#if image && !loading}
         {
                contextMenu(e);
                isOpen = true;
            }}
        />
    {/if}

```

In this image, the large image is the elements which I am creating a thumbnail of.
The boxes below are the 'pages' of the story and as you can see, the SVG images aren't adhering to the bounds of the parent div of the image element.

The public URL being used as the source is a reference to an SVG assets stored in my supabase storage.

Body:
Okay, so here's a pretty niche question.
I'm using html2canvas to create a screenshot(thumbnail) of a dom element. From there I am creating an image element and appending to that element an SVG which is contained within the parent element as a child.
When I create this screenshot the images show up, but they're breaking out of their bounds.
My question is if there is a way to make my image elements adhere to their bound during this screenshot process.
I am using SvelteKit for my client, if that helps anything at all.

Here is the function which is creating the screenshot:

export const screenshotCanvas = async (element: string): Promise<File | null> => {
    const el: HTMLElement | null = document.querySelector(element);
    const svgAssets = document.querySelectorAll('img');

    if (el) {
        const canvas = await html2canvas(el, {
            allowTaint: true,
            useCORS: true,
            logging: true,
            imageTimeout: 0,
            proxy: 'https://cors-anywhere.herokuapp.com/',
            onclone: (doc) => {
                svgAssets.forEach((asset) => {
                    console.log('assets', asset, asset.width, asset.height)
                    const img = doc.createElement('img');
                    img.src = asset.src;
                    img.width = asset.width;
                    img.height = asset.height;
                    doc.body.appendChild(img);
                });
            }
        });

        const blob = await new Promise((resolve) => canvas.toBlob(resolve));
        // TODO handle error if blob is null somehow
        const file = new File([blob], 'thumbnail.webp', { type: 'image/webp' });
        return file;
    }
    return null;
};

Here is the parent element, which is what is being passed into the screenshotCanvas element:

        {#if info.elements}
            {#each info.elements as element}
                <ImgElement {element} />
            {/each}
        {/if}
        {#if $howToIsOpen}
            <HowToModal />
        {/if}

And here is the child element, which can be any number of elements within the canvas:

    {#if loading}
        <Loading />
    {/if}
    {#if image && !loading}
         {
                contextMenu(e);
                isOpen = true;
            }}
        />
    {/if}

In this image, the large image is the elements which I am creating a thumbnail of.
The boxes below are the 'pages' of the story and as you can see, the SVG images aren't adhering to the bounds of the parent div of the image element.

The public URL being used as the source is a reference to an SVG assets stored in my supabase storage.


问:
Plotting a part of a part of a shapefile in R (yes, a part of a part)
I need to plot a map of Argentina with the level 1 division (provinces). I downloaded the shapefile from the official govt. entity and found that one of the provinces includes Antarctica. When plotting the whole map, Antarctica messes up the aspect ratio of the map, making the country look very thin in comparison.

Map as it is plotted including Antarctica

Diving into the polygons, there is one that includes Tierra del Fuego, Antarctica and Southern Atlantic Islands (which is the actual name of the province). I need to plot only Tierra del Fuego, which is the small triangle south of the country or north of Antarctica. The thing is, the shapefile has polygons inside polygons, and I don´t know how to selectively plot only some of them.

Part of the map I need to plot

I tried generating a subset of the main shapefile, separating Tierra del Fuego + Antarctica from the whole country. Unfortunately, there are polygons inside polygons, and I was not able to separate the triangle that represents Tierra del Fuego from the rest of the whole province (which includes Antarctica + Islands).

TdF <- subset(my_spdf,NAM=="Tierra del Fuego, Antártida e Islas del Atlántico Sur")

ARGsinTdF <- subset(my_spdf,NAM!="Tierra del Fuego, Antártida e Islas del Atlántico Sur")

Argentina without Tierra del Fuego

Part of the map of Tierra del Fuego + Antarctica I need to plot (and discard the rest)

Polygon 17 represents Tierra del Fuego + Antarctica + Islands
Polygons inside polygons

The Tierra del Fuego (TdF) subset with its embedded polygons inside
Polygons inside polygons (coordinates shown)

Any help will be welcome!
Thanks a lot in advance.


问:
How to disaggregate historical data in Power Query?
I would much be thankful if someone can help me with this situation.

I have weekly reports of sales by product and store, but these reports are aggregated by year (each report contains sales by year to current date) and I intend to disaggregate the data so I can have the sales of each week of the year in my reports.

Currently I am doing this with an excel formula and I want to pass this to power query / Language M

Here it is the formula in the image

enter image description here
Here is the explanation of the columns

Source.Name.1= The number of the report according to the week

SKU= Product code

Ventas YTD= Sales by year to current date

No.Tienda.number.1= Code of the store

Ventas semana= weekly sales using the excel formula

I currently have a mental block and I would appreciate of you could guide me through the problem


问:
how to fix Php query returning blank page with error 500
I have this code returning a blank page or error 500 when i try to add product.

It's also running to the last else statement on the code proving my querys are being skipped.

I am running this code on a live server cpanel to be specific.

On my local machine, am using xampp and it's perfectly working well.

```<code><?php
    include 'includes/session.php';
    include 'includes/slugify.php';

    if(isset($_POST['add'])){
        $name = $_POST['name'];
        $slug = slugify($name);
        $category = $_POST['category'];
        $price = $_POST['price'];
        $description = $_POST['description'];
        $filename = $_FILES['photo']['name'];

        $conn = $pdo->open();

        $stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM products WHERE slug=:slug GROUP BY id=:id");
        $stmt->execute(['slug'=>$slug]);
        $row = $stmt->fetch();

        if($row['numrows'] > 0){
            $_SESSION['error'] = 'Product already exist';
        }
        else{
            if(!empty($filename)){
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                $new_filename = $slug.'.'.$ext;
                move_uploaded_file($_FILES['photo']['tmp_name'], '../images/'.$new_filename);
            }
            else{
                $new_filename = '';
            }

            try{
                $stmt = $conn->prepare("INSERT INTO products (category_id, name, description, slug, price, photo) VALUES (:category, :name, :description, :slug, :price, :photo)");
                $stmt->execute(['category'=>$category, 'name'=>$name, 'description'=>$description, 'slug'=>$slug, 'price'=>$price, 'photo'=>$new_filename]);
                $_SESSION['success'] = 'User added successfully';

            }
            catch(PDOException $e){
                $_SESSION['error'] = 'Error adding product!';
            }
        }

        $pdo->close();
    }
    else{
        $_SESSION['error'] = 'Error adding product!';
    }

    header('location: products.php');

?>
</code>```

I am expecting php to run the select query first then insert into database.

So are there changes on my live server that need to be done since the code fully works on xampp offline bt returns error on live server cpanel.

Body:
I have this code returning a blank page or error 500 when i try to add product.

It's also running to the last else statement on the code proving my querys are being skipped.

I am running this code on a live server cpanel to be specific.

On my local machine, am using xampp and it's perfectly working well.

<?php
    include 'includes/session.php';
    include 'includes/slugify.php';

    if(isset($_POST['add'])){
        $name = $_POST['name'];
        $slug = slugify($name);
        $category = $_POST['category'];
        $price = $_POST['price'];
        $description = $_POST['description'];
        $filename = $_FILES['photo']['name'];

        $conn = $pdo->open();

        $stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM products WHERE slug=:slug GROUP BY id=:id");
        $stmt->execute(['slug'=>$slug]);
        $row = $stmt->fetch();

        if($row['numrows'] > 0){
            $_SESSION['error'] = 'Product already exist';
        }
        else{
            if(!empty($filename)){
                $ext = pathinfo($filename, PATHINFO_EXTENSION);
                $new_filename = $slug.'.'.$ext;
                move_uploaded_file($_FILES['photo']['tmp_name'], '../images/'.$new_filename);
            }
            else{
                $new_filename = '';
            }

            try{
                $stmt = $conn->prepare("INSERT INTO products (category_id, name, description, slug, price, photo) VALUES (:category, :name, :description, :slug, :price, :photo)");
                $stmt->execute(['category'=>$category, 'name'=>$name, 'description'=>$description, 'slug'=>$slug, 'price'=>$price, 'photo'=>$new_filename]);
                $_SESSION['success'] = 'User added successfully';

            }
            catch(PDOException $e){
                $_SESSION['error'] = 'Error adding product!';
            }
        }

        $pdo->close();
    }
    else{
        $_SESSION['error'] = 'Error adding product!';
    }

    header('location: products.php');

?>

I am expecting php to run the select query first then insert into database.

So are there changes on my live server that need to be done since the code fully works on xampp offline bt returns error on live server cpanel.


问:
Corrupted excel file built with openxml only on production server
My excel file generated by one of my applications, is getting this error

The error is :

“We Found A Problem with Some Content in Excel"

and it points me to a log file with the message:

Repaired recods: View from /xl/worksheets/sheet1.xml part.

Now to my .cs files where they are built:

First, this is how i start the workbook:

```<code> using (var spreadSheet = SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))
                {
                    var workbookPart = spreadSheet.AddWorkbookPart();

                    var openXmlExportHelper = new OpenXmlWriterHelper();
                    openXmlExportHelper.SaveCustomStylesheet(workbookPart);

                    var wkbook = workbookPart.Workbook = new Workbook();
                    var sheets = wkbook.AppendChild<Sheets>(new Sheets());

                    // create worksheet 1
                    var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                    var sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };
                    sheets.Append(sheet);

                    using (var writer = OpenXmlWriter.Create(worksheetPart))
                    {

                        writer.WriteStartElement(new Worksheet());
                        writer.WriteStartElement(new SheetData());
                        var headerList = new string[dataTableExcel.Columns.Count];
                        for (var i = 0; i < dataTableExcel.Columns.Count; i++)
                        {
                            headerList[i] = dataTableExcel.Columns[i].ColumnName;
                        }
                        //Create header row
                        writer.WriteStartElement(new Row());
                        for (int i = 0; i < headerList.Length; i++)
                        {
                            //header formatting attribute.  This will create a <c> element with s=2 as its attribute
                            //s stands for styleindex
                            var attributes = new OpenXmlAttribute[] { new OpenXmlAttribute("s", null, "2") }.ToList();
                            openXmlExportHelper.WriteCellValueSax(writer, headerList[i], CellValues.SharedString, attributes);

                        }
                        writer.WriteEndElement(); //end of Row tag

                        foreach(var element in lista)
                        {
                            writer.WriteStartElement(new Row());
                            foreach (var campo in element.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
                            {
                                var name = campo.Name;

                                openXmlExportHelper.WriteCellValueSax(writer, campo.GetValue(element) != null ? campo.GetValue(element).ToString() : string.Empty,
 campo.GetValue(element) != null ? RecuperaFormatoCampo(campo.GetValue(element).ToString()) : CellValues.InlineString,null,1,name);

                            }
                            writer.WriteEndElement();
                        }

                        writer.WriteEndElement(); //end of SheetData
                        writer.WriteEndElement(); //end of worksheet
                        writer.Close();
                        openXmlExportHelper.CreateShareStringPart(workbookPart);
                    }

                }
</code>```

Important, the savecustomstylesheet has some customizations like the following:

```<code>    //get a copy of the default excel style sheet then add additional styles to it
            var stylesheet = CreateDefaultStylesheet();

            // ***************************** Fills *********************************
            var fills = stylesheet.Fills;

            //header fills background color
            var fill = new Fill();
            var patternFill = new PatternFill();
            patternFill.PatternType = PatternValues.Solid;
            patternFill.ForegroundColor = new ForegroundColor { Rgb = HexBinaryValue.FromString("C8EEFF") };
            //patternFill.BackgroundColor = new BackgroundColor() { Indexed = 64 };
            fill.PatternFill = patternFill;
            fills.AppendChild(fill);
            fills.Count = (uint)fills.ChildElements.Count;

            // *************************** numbering formats ***********************
            var nfs = stylesheet.NumberingFormats;
            //number less than 164 is reserved by excel for default formats
            uint iExcelIndex = 165;
            NumberingFormat nf;
            nf = new NumberingFormat();
            nf.NumberFormatId = iExcelIndex++;
            nf.FormatCode = @"[$-409]m/d/yy\ h:mm\ AM/PM;@";
            nfs.Append(nf);

            NumberingFormat nf2;
            nf2 = new NumberingFormat();
            nf2.NumberFormatId = iExcelIndex++;
            nf2.FormatCode = "\"R$\"#,##0.00;[Red]\"R$\"#,##0.00";
            nfs.Append(nf2);

            nfs.Count = (uint)nfs.ChildElements.Count;

            NumberingFormat nf3;
            nf3 = new NumberingFormat();

            nf3.NumberFormatId = iExcelIndex++;
            nf3.FormatCode = "\"\"#,##0.00;[Red]\"\"#,##0.00";
            nfs.Append(nf3);

            NumberingFormat nf4;
            nf4 = new NumberingFormat();
            nf4.NumberFormatId = iExcelIndex++;
            nf4.FormatCode = "@";
            nfs.Append(nf4);

            nfs.Count = (uint)nfs.ChildElements.Count;

            //************************** cell formats ***********************************
            var cfs = stylesheet.CellFormats;//this should already contain a default StyleIndex of 0

            var cf = new CellFormat();// Date time format is defined as StyleIndex = 1
            cf.NumberFormatId = nf.NumberFormatId;
            cf.FontId = 0;
            cf.FillId = 0;
            cf.BorderId = 0;
            cf.FormatId = 1;
            cf.ApplyNumberFormat = true;
            cfs.Append(cf);

            cf = new CellFormat();// Header format is defined as StyleINdex = 2
            cf.NumberFormatId = nf.NumberFormatId;
            cf.FontId = 0;
            cf.FillId = 2;
            cf.ApplyFill = true;
            cf.BorderId = 0;
            cf.FormatId = 0;
            cf.ApplyNumberFormat = true;
            cfs.Append(cf);

            ///**Style index = 3
            CellFormat cellFormat1 = new CellFormat() { NumberFormatId = (UInt32Value)1,
                FontId = (UInt32Value)0U,
                FillId = (UInt32Value)0U,
                BorderId = (UInt32Value)0U,
                FormatId = (UInt32Value)0U,
                ApplyNumberFormat = true };
            cfs.Append(cellFormat1);

            ///**Style index = 4
            CellFormat cellFormatdecimal = new CellFormat()
            {
                NumberFormatId = (UInt32Value)nf2.NumberFormatId,
                FontId = (UInt32Value)0U,
                FillId = (UInt32Value)0U,
                BorderId = (UInt32Value)0U,
                FormatId = (UInt32Value)0U,
                ApplyNumberFormat = true
            };
            cfs.Append(cellFormatdecimal);

            //Style index = 5
            CellFormat cellFormat5 = new CellFormat()
            {
                NumberFormatId = (UInt32Value)nf3.NumberFormatId,
                FontId = (UInt32Value)0U,
                FillId = (UInt32Value)0U,
                BorderId = (UInt32Value)0U,
                FormatId = (UInt32Value)0U,
                ApplyNumberFormat = true
            };
            cfs.Append(cellFormat5);

            //Style index = 6
            CellFormat cellFormat6 = new CellFormat()
            {
                NumberFormatId = (UInt32Value)nf4.NumberFormatId,
                FontId = (UInt32Value)0U,
                FillId = (UInt32Value)0U,
                BorderId = (UInt32Value)0U,
                FormatId = (UInt32Value)0U,
                ApplyNumberFormat = true
            };
            cfs.Append(cellFormat6);

            cfs.Count = (uint)cfs.ChildElements.Count;

            var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
            var style = workbookStylesPart.Stylesheet = stylesheet;
            style.Save();

        }
</code>```

And for the writecellvaluesax:

```<code>public void WriteCellValueSax(OpenXmlWriter writer, string cellValue, CellValues dataType, List<OpenXmlAttribute> attributes = null,int idFormat = 0,string columnname = "")
        {
            switch (dataType)
            {
                case CellValues.InlineString:
                    {
                        if (attributes == null)
                        {
                            attributes = new List<OpenXmlAttribute>();
                        }
                        attributes.Add(new OpenXmlAttribute("t", null, "inlineStr"));
                        writer.WriteStartElement(new Cell(), attributes);
                        writer.WriteElement(new InlineString(new Text(cellValue)));
                        writer.WriteEndElement();
                        break;
                    }
                case CellValues.Number:
                    {
                        if (attributes == null)
                        {
                            attributes = new List<OpenXmlAttribute>();
                        }

                        writer.WriteStartElement(new Cell() {DataType = CellValues.Number,StyleIndex = FormatoCampo(columnname,cellValue.Length)});
                        writer.WriteElement(new CellValue(cellValue));
                        writer.WriteEndElement();
                        break;
                    }
                case CellValues.SharedString:
                    {
                        if (attributes == null)
                        {
                            attributes = new List<OpenXmlAttribute>();
                        }
                        attributes.Add(new OpenXmlAttribute("t", null, "s"));//shared string type
                        writer.WriteStartElement(new Cell(), attributes);
                        if (!_shareStringDictionary.ContainsKey(cellValue))
                        {
                            _shareStringDictionary.Add(cellValue, _shareStringMaxIndex);
                            _shareStringMaxIndex++;
                        }

                        //writing the index as the cell value
                        writer.WriteElement(new CellValue(_shareStringDictionary[cellValue].ToString()));

                        writer.WriteEndElement();//cell

                        break;
                    }
                case CellValues.Date:
                    {
                        if (attributes == null)
                        {
                            writer.WriteStartElement(new Cell() { DataType = CellValues.Number });
                        }
                        else
                        {
                            writer.WriteStartElement(new Cell() { DataType = CellValues.Number }, attributes);
                        }

                        writer.WriteElement(new CellValue(cellValue));

                        writer.WriteEndElement();

                        break;
                    }
                case CellValues.Boolean:
                    {
                        if (attributes == null)
                        {
                            attributes = new List<OpenXmlAttribute>();
                        }
                        attributes.Add(new OpenXmlAttribute("t", null, "b"));//boolean type
                        writer.WriteStartElement(new Cell(), attributes);
                        writer.WriteElement(new CellValue(cellValue == "True" ? "1" : "0"));
                        writer.WriteEndElement();
                        break;
                    }
                default:
                    {
                        if (attributes == null)
                        {
                            writer.WriteStartElement(new Cell() { DataType = dataType });
                        }
                        else
                        {
                            writer.WriteStartElement(new Cell() { DataType = dataType }, attributes);
                        }
                        writer.WriteElement(new CellValue(cellValue));

                        writer.WriteEndElement();

                        break;
                    }
            }

        }
</code>```

I tried unziping the xlsx file to see if i could manually find anything weird, but nothing shows

Body:
My excel file generated by one of my applications, is getting this error

The error is :

“We Found A Problem with Some Content in Excel"

and it points me to a log file with the message:

Repaired recods: View from /xl/worksheets/sheet1.xml part.

Now to my .cs files where they are built:

First, this is how i start the workbook:

 using (var spreadSheet = SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))
                {
                    var workbookPart = spreadSheet.AddWorkbookPart();

                    var openXmlExportHelper = new OpenXmlWriterHelper();
                    openXmlExportHelper.SaveCustomStylesheet(workbookPart);

                    var wkbook = workbookPart.Workbook = new Workbook();
                    var sheets = wkbook.AppendChild<Sheets>(new Sheets());

                    // create worksheet 1
                    var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                    var sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };
                    sheets.Append(sheet);

                    using (var writer = OpenXmlWriter.Create(worksheetPart))
                    {

                        writer.WriteStartElement(new Worksheet());
                        writer.WriteStartElement(new SheetData());
                        var headerList = new string[dataTableExcel.Columns.Count];
                        for (var i = 0; i < dataTableExcel.Columns.Count; i++)
                        {
                            headerList[i] = dataTableExcel.Columns[i].ColumnName;
                        }
                        //Create header row
                        writer.WriteStartElement(new Row());
                        for (int i = 0; i < headerList.Length; i++)
                        {
                            //header formatting attribute.  This will create a <c> element with s=2 as its attribute
                            //s stands for styleindex
                            var attributes = new OpenXmlAttribute[] { new OpenXmlAttribute("s", null, "2") }.ToList();
                            openXmlExportHelper.WriteCellValueSax(writer, headerList[i], CellValues.SharedString, attributes);

                        }
                        writer.WriteEndElement(); //end of Row tag

                        foreach(var element in lista)
                        {
                            writer.WriteStartElement(new Row());
                            foreach (var campo in element.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
                            {
                                var name = campo.Name;

                                openXmlExportHelper.WriteCellValueSax(writer, campo.GetValue(element) != null ? campo.GetValue(element).ToString() : string.Empty,
 campo.GetValue(element) != null ? RecuperaFormatoCampo(campo.GetValue(element).ToString()) : CellValues.InlineString,null,1,name);

                            }
                            writer.WriteEndElement();
                        }

                        writer.WriteEndElement(); //end of SheetData
                        writer.WriteEndElement(); //end of worksheet
                        writer.Close();
                        openXmlExportHelper.CreateShareStringPart(workbookPart);
                    }

                }

Important, the savecustomstylesheet has some customizations like the following:

    //get a copy of the default excel style sheet then add additional styles to it
            var stylesheet = CreateDefaultStylesheet();

            // ***************************** Fills *********************************
            var fills = stylesheet.Fills;

            //header fills background color
            var fill = new Fill();
            var patternFill = new PatternFill();
            patternFill.PatternType = PatternValues.Solid;
            patternFill.ForegroundColor = new ForegroundColor { Rgb = HexBinaryValue.FromString("C8EEFF") };
            //patternFill.BackgroundColor = new BackgroundColor() { Indexed = 64 };
            fill.PatternFill = patternFill;
            fills.AppendChild(fill);
            fills.Count = (uint)fills.ChildElements.Count;

            // *************************** numbering formats ***********************
            var nfs = stylesheet.NumberingFormats;
            //number less than 164 is reserved by excel for default formats
            uint iExcelIndex = 165;
            NumberingFormat nf;
            nf = new NumberingFormat();
            nf.NumberFormatId = iExcelIndex++;
            nf.FormatCode = @"[$-409]m/d/yy\ h:mm\ AM/PM;@";
            nfs.Append(nf);

            NumberingFormat nf2;
            nf2 = new NumberingFormat();
            nf2.NumberFormatId = iExcelIndex++;
            nf2.FormatCode = "\"R$\"#,##0.00;[Red]\"R$\"#,##0.00";
            nfs.Append(nf2);

            nfs.Count = (uint)nfs.ChildElements.Count;

            NumberingFormat nf3;
            nf3 = new NumberingFormat();

            nf3.NumberFormatId = iExcelIndex++;
            nf3.FormatCode = "\"\"#,##0.00;[Red]\"\"#,##0.00";
            nfs.Append(nf3);

            NumberingFormat nf4;
            nf4 = new NumberingFormat();
            nf4.NumberFormatId = iExcelIndex++;
            nf4.FormatCode = "@";
            nfs.Append(nf4);

            nfs.Count = (uint)nfs.ChildElements.Count;

            //************************** cell formats ***********************************
            var cfs = stylesheet.CellFormats;//this should already contain a default StyleIndex of 0

            var cf = new CellFormat();// Date time format is defined as StyleIndex = 1
            cf.NumberFormatId = nf.NumberFormatId;
            cf.FontId = 0;
            cf.FillId = 0;
            cf.BorderId = 0;
            cf.FormatId = 1;
            cf.ApplyNumberFormat = true;
            cfs.Append(cf);

            cf = new CellFormat();// Header format is defined as StyleINdex = 2
            cf.NumberFormatId = nf.NumberFormatId;
            cf.FontId = 0;
            cf.FillId = 2;
            cf.ApplyFill = true;
            cf.BorderId = 0;
            cf.FormatId = 0;
            cf.ApplyNumberFormat = true;
            cfs.Append(cf);

            ///**Style index = 3
            CellFormat cellFormat1 = new CellFormat() { NumberFormatId = (UInt32Value)1,
                FontId = (UInt32Value)0U,
                FillId = (UInt32Value)0U,
                BorderId = (UInt32Value)0U,
                FormatId = (UInt32Value)0U,
                ApplyNumberFormat = true };
            cfs.Append(cellFormat1);

            ///**Style index = 4
            CellFormat cellFormatdecimal = new CellFormat()
            {
                NumberFormatId = (UInt32Value)nf2.NumberFormatId,
                FontId = (UInt32Value)0U,
                FillId = (UInt32Value)0U,
                BorderId = (UInt32Value)0U,
                FormatId = (UInt32Value)0U,
                ApplyNumberFormat = true
            };
            cfs.Append(cellFormatdecimal);

            //Style index = 5
            CellFormat cellFormat5 = new CellFormat()
            {
                NumberFormatId = (UInt32Value)nf3.NumberFormatId,
                FontId = (UInt32Value)0U,
                FillId = (UInt32Value)0U,
                BorderId = (UInt32Value)0U,
                FormatId = (UInt32Value)0U,
                ApplyNumberFormat = true
            };
            cfs.Append(cellFormat5);

            //Style index = 6
            CellFormat cellFormat6 = new CellFormat()
            {
                NumberFormatId = (UInt32Value)nf4.NumberFormatId,
                FontId = (UInt32Value)0U,
                FillId = (UInt32Value)0U,
                BorderId = (UInt32Value)0U,
                FormatId = (UInt32Value)0U,
                ApplyNumberFormat = true
            };
            cfs.Append(cellFormat6);

            cfs.Count = (uint)cfs.ChildElements.Count;

            var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
            var style = workbookStylesPart.Stylesheet = stylesheet;
            style.Save();

        }

And for the writecellvaluesax:

public void WriteCellValueSax(OpenXmlWriter writer, string cellValue, CellValues dataType, List<OpenXmlAttribute> attributes = null,int idFormat = 0,string columnname = "")
        {
            switch (dataType)
            {
                case CellValues.InlineString:
                    {
                        if (attributes == null)
                        {
                            attributes = new List<OpenXmlAttribute>();
                        }
                        attributes.Add(new OpenXmlAttribute("t", null, "inlineStr"));
                        writer.WriteStartElement(new Cell(), attributes);
                        writer.WriteElement(new InlineString(new Text(cellValue)));
                        writer.WriteEndElement();
                        break;
                    }
                case CellValues.Number:
                    {
                        if (attributes == null)
                        {
                            attributes = new List<OpenXmlAttribute>();
                        }

                        writer.WriteStartElement(new Cell() {DataType = CellValues.Number,StyleIndex = FormatoCampo(columnname,cellValue.Length)});
                        writer.WriteElement(new CellValue(cellValue));
                        writer.WriteEndElement();
                        break;
                    }
                case CellValues.SharedString:
                    {
                        if (attributes == null)
                        {
                            attributes = new List<OpenXmlAttribute>();
                        }
                        attributes.Add(new OpenXmlAttribute("t", null, "s"));//shared string type
                        writer.WriteStartElement(new Cell(), attributes);
                        if (!_shareStringDictionary.ContainsKey(cellValue))
                        {
                            _shareStringDictionary.Add(cellValue, _shareStringMaxIndex);
                            _shareStringMaxIndex++;
                        }

                        //writing the index as the cell value
                        writer.WriteElement(new CellValue(_shareStringDictionary[cellValue].ToString()));

                        writer.WriteEndElement();//cell

                        break;
                    }
                case CellValues.Date:
                    {
                        if (attributes == null)
                        {
                            writer.WriteStartElement(new Cell() { DataType = CellValues.Number });
                        }
                        else
                        {
                            writer.WriteStartElement(new Cell() { DataType = CellValues.Number }, attributes);
                        }

                        writer.WriteElement(new CellValue(cellValue));

                        writer.WriteEndElement();

                        break;
                    }
                case CellValues.Boolean:
                    {
                        if (attributes == null)
                        {
                            attributes = new List<OpenXmlAttribute>();
                        }
                        attributes.Add(new OpenXmlAttribute("t", null, "b"));//boolean type
                        writer.WriteStartElement(new Cell(), attributes);
                        writer.WriteElement(new CellValue(cellValue == "True" ? "1" : "0"));
                        writer.WriteEndElement();
                        break;
                    }
                default:
                    {
                        if (attributes == null)
                        {
                            writer.WriteStartElement(new Cell() { DataType = dataType });
                        }
                        else
                        {
                            writer.WriteStartElement(new Cell() { DataType = dataType }, attributes);
                        }
                        writer.WriteElement(new CellValue(cellValue));

                        writer.WriteEndElement();

                        break;
                    }
            }

        }

I tried unziping the xlsx file to see if i could manually find anything weird, but nothing shows