/**
  ******************************************************************************
  * @file      startup_stm32f413xx.s
  * @author    MCD Application Team
  * @brief     STM32F413xx Devices vector table for GCC based toolchains.
  *            This module performs:
  *                - Set the initial SP
  *                - Set the initial PC == Reset_Handler,
  *                - Set the vector table entries with the exceptions ISR address
  *                - Branches to main in the C library (which eventually
  *                  calls main()).
  *            After Reset the Cortex-M4 processor is in Thread mode,
  *            priority is Privileged, and the Stack is set to Main.
  ******************************************************************************
  * @attention
  *
  *
© COPYRIGHT 2017 STMicroelectronics

  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */

  .syntax unified
  .cpu cortex-m4
  .fpu softvfp
  .thumb

.global  g_pfnVectors
.global  Default_Handler

/* start address for the initialization values of the .data section.
defined in linker script */
.word  _sidata
/* start address for the .data section. defined in linker script */
.word  _sdata
/* end address for the .data section. defined in linker script */
.word  _edata
/* start address for the .bss section. defined in linker script */
.word  _sbss
/* end address for the .bss section. defined in linker script */
.word  _ebss
/* stack used for SystemInit_ExtMemCtl; always internal RAM used */

/**
 * @brief  This is the code that gets called when the processor first
 *          starts execution following a reset event. Only the absolutely
 *          necessary set is performed, after which the application
 *          supplied main() routine is called.
 * @param  None
 * @retval : None
*/

    .section  .text.Reset_Handler
  .weak  Reset_Handler
  .type  Reset_Handler, %function
Reset_Handler:
  ldr   sp, =_estack       /* set stack pointer */

/* Copy the data segment initializers from flash to SRAM */
  movs  r1, #0
  b  LoopCopyDataInit

CopyDataInit:
  ldr  r3, =_sidata
  ldr  r3, [r3, r1]
  str  r3, [r0, r1]
  adds  r1, r1, #4

LoopCopyDataInit:
  ldr  r0, =_sdata
  ldr  r3, =_edata
  adds  r2, r0, r1
  cmp  r2, r3
  bcc  CopyDataInit
  ldr  r2, =_sbss
  b  LoopFillZerobss
/* Zero fill the bss segment. */
FillZerobss:
  movs  r3, #0
  str  r3, [r2], #4

LoopFillZerobss:
  ldr  r3, = _ebss
  cmp  r2, r3
  bcc  FillZerobss

/* Call the clock system intitialization function.*/
  bl  SystemInit
/* Call static constructors */
    bl __libc_init_array
/* Call the application's entry point.*/
  bl  main
  bx  lr
.size  Reset_Handler, .-Reset_Handler

/**
 * @brief  This is the code that gets called when the processor receives an
 *         unexpected interrupt.  This simply enters an infinite loop, preserving
 *         the system state for examination by a debugger.
 * @param  None
 * @retval None
*/
    .section  .text.Default_Handler,"ax",%progbits
Default_Handler:
Infinite_Loop:
  b  Infinite_Loop
  .size  Default_Handler, .-Default_Handler
/******************************************************************************
*
* The minimal vector table for a Cortex M3. Note that the proper constructs
* must be placed on this to ensure that it ends up at physical address
* 0x0000.0000.
*
*******************************************************************************/
   .section  .isr_vector,"a",%progbits
  .type  g_pfnVectors, %object
  .size  g_pfnVectors, .-g_pfnVectors

g_pfnVectors:
  .word  _estack
  .word  Reset_Handler
  .word  NMI_Handler
  .word  HardFault_Handler
  .word  MemManage_Handler
  .word  BusFault_Handler
  .word  UsageFault_Handler
  .word  0
  .word  0
  .word  0
  .word  0
  .word  SVC_Handler
  .word  DebugMon_Handler
  .word  0
  .word  PendSV_Handler
  .word  SysTick_Handler

  /* External Interrupts */
  .word     WWDG_IRQHandler                   /* Window WatchDog                             */
  .word     PVD_IRQHandler                    /* PVD through EXTI Line detection             */
  .word     TAMP_STAMP_IRQHandler             /* Tamper and TimeStamps through the EXTI line */
  .word     RTC_WKUP_IRQHandler               /* RTC Wakeup through the EXTI line            */
  .word     FLASH_IRQHandler                  /* FLASH                                       */
  .word     RCC_IRQHandler                    /* RCC                                         */
  .word     EXTI0_IRQHandler                  /* EXTI Line0                                  */
  .word     EXTI1_IRQHandler                  /* EXTI Line1                                  */
  .word     EXTI2_IRQHandler                  /* EXTI Line2                                  */
  .word     EXTI3_IRQHandler                  /* EXTI Line3                                  */
  .word     EXTI4_IRQHandler                  /* EXTI Line4                                  */
  .word     DMA1_Stream0_IRQHandler           /* DMA1 Stream 0                               */
  .word     DMA1_Stream1_IRQHandler           /* DMA1 Stream 1                               */
  .word     DMA1_Stream2_IRQHandler           /* DMA1 Stream 2                               */
  .word     DMA1_Stream3_IRQHandler           /* DMA1 Stream 3                               */
  .word     DMA1_Stream4_IRQHandler           /* DMA1 Stream 4                               */
  .word     DMA1_Stream5_IRQHandler           /* DMA1 Stream 5                               */
  .word     DMA1_Stream6_IRQHandler           /* DMA1 Stream 6                               */
  .word     ADC_IRQHandler                    /* ADC1, ADC2 and ADC3s                        */
  .word     CAN1_TX_IRQHandler                /* CAN1 TX                                     */
  .word     CAN1_RX0_IRQHandler               /* CAN1 RX0                                    */
  .word     CAN1_RX1_IRQHandler               /* CAN1 RX1                                    */
  .word     CAN1_SCE_IRQHandler               /* CAN1 SCE                                    */
  .word     EXTI9_5_IRQHandler                /* External Line[9:5]s                         */
  .word     TIM1_BRK_TIM9_IRQHandler          /* TIM1 Break and TIM9                         */
  .word     TIM1_UP_TIM10_IRQHandler          /* TIM1 Update and TIM10                       */
  .word     TIM1_TRG_COM_TIM11_IRQHandler     /* TIM1 Trigger and Commutation and TIM11      */
  .word     TIM1_CC_IRQHandler                /* TIM1 Capture Compare                        */
  .word     TIM2_IRQHandler                   /* TIM2                                        */
  .word     TIM3_IRQHandler                   /* TIM3                                        */
  .word     TIM4_IRQHandler                   /* TIM4                                        */
  .word     I2C1_EV_IRQHandler                /* I2C1 Event                                  */
  .word     I2C1_ER_IRQHandler                /* I2C1 Error                                  */
  .word     I2C2_EV_IRQHandler                /* I2C2 Event                                  */
  .word     I2C2_ER_IRQHandler                /* I2C2 Error                                  */
  .word     SPI1_IRQHandler                   /* SPI1                                        */
  .word     SPI2_IRQHandler                   /* SPI2                                        */
  .word     USART1_IRQHandler                 /* USART1                                      */
  .word     USART2_IRQHandler                 /* USART2                                      */
  .word     USART3_IRQHandler                 /* USART3                                      */
  .word     EXTI15_10_IRQHandler              /* External Line[15:10]s                       */
  .word     RTC_Alarm_IRQHandler              /* RTC Alarm (A and B) through EXTI Line       */
  .word     OTG_FS_WKUP_IRQHandler            /* USB OTG FS Wakeup through EXTI line         */
  .word     TIM8_BRK_TIM12_IRQHandler         /* TIM8 Break and TIM12                        */
  .word     TIM8_UP_TIM13_IRQHandler          /* TIM8 Update and TIM13                       */
  .word     TIM8_TRG_COM_TIM14_IRQHandler     /* TIM8 Trigger and Commutation and TIM14      */
  .word     TIM8_CC_IRQHandler                /* TIM8 Capture Compare                        */
  .word     DMA1_Stream7_IRQHandler           /* DMA1 Stream7                                */
  .word     FSMC_IRQHandler                   /* FSMC                                        */
  .word     SDIO_IRQHandler                   /* SDIO                                        */
  .word     TIM5_IRQHandler                   /* TIM5                                        */
  .word     SPI3_IRQHandler                   /* SPI3                                        */
  .word     UART4_IRQHandler                  /* UART4                                       */
  .word     UART5_IRQHandler                  /* UART5                                       */
  .word     TIM6_DAC_IRQHandler               /* TIM6, DAC1 and DAC2                         */
  .word     TIM7_IRQHandler                   /* TIM7                                        */
  .word     DMA2_Stream0_IRQHandler           /* DMA2 Stream 0                               */
  .word     DMA2_Stream1_IRQHandler           /* DMA2 Stream 1                               */
  .word     DMA2_Stream2_IRQHandler           /* DMA2 Stream 2                               */
  .word     DMA2_Stream3_IRQHandler           /* DMA2 Stream 3                               */
  .word     DMA2_Stream4_IRQHandler           /* DMA2 Stream 4                               */
  .word     DFSDM1_FLT0_IRQHandler            /* DFSDM1 Filter0                              */
  .word     DFSDM1_FLT1_IRQHandler            /* DFSDM1 Filter1                              */
  .word     CAN2_TX_IRQHandler                /* CAN2 TX                                     */
  .word     CAN2_RX0_IRQHandler               /* CAN2 RX0                                    */
  .word     CAN2_RX1_IRQHandler               /* CAN2 RX1                                    */
  .word     CAN2_SCE_IRQHandler               /* CAN2 SCE                                    */
  .word     OTG_FS_IRQHandler                 /* USB OTG FS                                  */
  .word     DMA2_Stream5_IRQHandler           /* DMA2 Stream 5                               */
  .word     DMA2_Stream6_IRQHandler           /* DMA2 Stream 6                               */
  .word     DMA2_Stream7_IRQHandler           /* DMA2 Stream 7                               */
  .word     USART6_IRQHandler                 /* USART6                                      */
  .word     I2C3_EV_IRQHandler                /* I2C3 event                                  */
  .word     I2C3_ER_IRQHandler                /* I2C3 error                                  */
  .word     CAN3_TX_IRQHandler                /* CAN3 TX                                     */
  .word     CAN3_RX0_IRQHandler               /* CAN3 RX0                                    */
  .word     CAN3_RX1_IRQHandler               /* CAN3 RX1                                    */
  .word     CAN3_SCE_IRQHandler               /* CAN3 SCE                                    */
  .word     0                                 /* Reserved                                    */
  .word     0                                 /* Reserved                                    */
  .word     RNG_IRQHandler                    /* RNG                                         */
  .word     FPU_IRQHandler                    /* FPU                                         */
  .word     UART7_IRQHandler                  /* UART7                                       */
  .word     UART8_IRQHandler                  /* UART8                                       */
  .word     SPI4_IRQHandler                   /* SPI4                                        */
  .word     SPI5_IRQHandler                   /* SPI5                                        */
  .word     0                                 /* Reserved                                    */
  .word     SAI1_IRQHandler                   /* SAI1                                        */
  .word     UART9_IRQHandler                  /* UART9                                       */
  .word     UART10_IRQHandler                 /* UART10                                      */
  .word     0                                 /* Reserved                                    */
  .word     0                                 /* Reserved                                    */
  .word     QUADSPI_IRQHandler                /* QuadSPI                                     */
  .word     0                                 /* Reserved                                    */
  .word     0                                 /* Reserved                                    */
  .word     FMPI2C1_EV_IRQHandler             /* FMPI2C1 Event                               */
  .word     FMPI2C1_ER_IRQHandler             /* FMPI2C1 Error                               */
  .word     LPTIM1_IRQHandler                 /* LPTIM1                                      */
  .word     DFSDM2_FLT0_IRQHandler            /* DFSDM2 Filter0                              */
  .word     DFSDM2_FLT1_IRQHandler            /* DFSDM2 Filter1                              */
  .word     DFSDM2_FLT2_IRQHandler            /* DFSDM2 Filter2                              */
  .word     DFSDM2_FLT3_IRQHandler            /* DFSDM2 Filter3                              */

/*******************************************************************************
*
* Provide weak aliases for each Exception handler to the Default_Handler.
* As they are weak aliases, any function with the same name will override
* this definition.
*
*******************************************************************************/
   .weak      NMI_Handler
   .thumb_set NMI_Handler,Default_Handler

   .weak      HardFault_Handler
   .thumb_set HardFault_Handler,Default_Handler

   .weak      MemManage_Handler
   .thumb_set MemManage_Handler,Default_Handler

   .weak      BusFault_Handler
   .thumb_set BusFault_Handler,Default_Handler

   .weak      UsageFault_Handler
   .thumb_set UsageFault_Handler,Default_Handler

   .weak      SVC_Handler
   .thumb_set SVC_Handler,Default_Handler

   .weak      DebugMon_Handler
   .thumb_set DebugMon_Handler,Default_Handler

   .weak      PendSV_Handler
   .thumb_set PendSV_Handler,Default_Handler

   .weak      SysTick_Handler
   .thumb_set SysTick_Handler,Default_Handler

   .weak      WWDG_IRQHandler
   .thumb_set WWDG_IRQHandler,Default_Handler

   .weak      PVD_IRQHandler
   .thumb_set PVD_IRQHandler,Default_Handler

   .weak      TAMP_STAMP_IRQHandler
   .thumb_set TAMP_STAMP_IRQHandler,Default_Handler

   .weak      RTC_WKUP_IRQHandler
   .thumb_set RTC_WKUP_IRQHandler,Default_Handler

   .weak      FLASH_IRQHandler
   .thumb_set FLASH_IRQHandler,Default_Handler

   .weak      RCC_IRQHandler
   .thumb_set RCC_IRQHandler,Default_Handler

   .weak      EXTI0_IRQHandler
   .thumb_set EXTI0_IRQHandler,Default_Handler

   .weak      EXTI1_IRQHandler
   .thumb_set EXTI1_IRQHandler,Default_Handler

   .weak      EXTI2_IRQHandler
   .thumb_set EXTI2_IRQHandler,Default_Handler

   .weak      EXTI3_IRQHandler
   .thumb_set EXTI3_IRQHandler,Default_Handler

   .weak      EXTI4_IRQHandler
   .thumb_set EXTI4_IRQHandler,Default_Handler

   .weak      DMA1_Stream0_IRQHandler
   .thumb_set DMA1_Stream0_IRQHandler,Default_Handler

   .weak      DMA1_Stream1_IRQHandler
   .thumb_set DMA1_Stream1_IRQHandler,Default_Handler

   .weak      DMA1_Stream2_IRQHandler
   .thumb_set DMA1_Stream2_IRQHandler,Default_Handler

   .weak      DMA1_Stream3_IRQHandler
   .thumb_set DMA1_Stream3_IRQHandler,Default_Handler

   .weak      DMA1_Stream4_IRQHandler
   .thumb_set DMA1_Stream4_IRQHandler,Default_Handler

   .weak      DMA1_Stream5_IRQHandler
   .thumb_set DMA1_Stream5_IRQHandler,Default_Handler

   .weak      DMA1_Stream6_IRQHandler
   .thumb_set DMA1_Stream6_IRQHandler,Default_Handler

   .weak      ADC_IRQHandler
   .thumb_set ADC_IRQHandler,Default_Handler

   .weak      CAN1_TX_IRQHandler
   .thumb_set CAN1_TX_IRQHandler,Default_Handler

   .weak      CAN1_RX0_IRQHandler
   .thumb_set CAN1_RX0_IRQHandler,Default_Handler

   .weak      CAN1_RX1_IRQHandler
   .thumb_set CAN1_RX1_IRQHandler,Default_Handler

   .weak      CAN1_SCE_IRQHandler
   .thumb_set CAN1_SCE_IRQHandler,Default_Handler

   .weak      EXTI9_5_IRQHandler
   .thumb_set EXTI9_5_IRQHandler,Default_Handler

   .weak      TIM1_BRK_TIM9_IRQHandler
   .thumb_set TIM1_BRK_TIM9_IRQHandler,Default_Handler

   .weak      TIM1_UP_TIM10_IRQHandler
   .thumb_set TIM1_UP_TIM10_IRQHandler,Default_Handler

   .weak      TIM1_TRG_COM_TIM11_IRQHandler
   .thumb_set TIM1_TRG_COM_TIM11_IRQHandler,Default_Handler

   .weak      TIM1_CC_IRQHandler
   .thumb_set TIM1_CC_IRQHandler,Default_Handler

   .weak      TIM2_IRQHandler
   .thumb_set TIM2_IRQHandler,Default_Handler

   .weak      TIM3_IRQHandler
   .thumb_set TIM3_IRQHandler,Default_Handler

   .weak      TIM4_IRQHandler
   .thumb_set TIM4_IRQHandler,Default_Handler

   .weak      I2C1_EV_IRQHandler
   .thumb_set I2C1_EV_IRQHandler,Default_Handler

   .weak      I2C1_ER_IRQHandler
   .thumb_set I2C1_ER_IRQHandler,Default_Handler

   .weak      I2C2_EV_IRQHandler
   .thumb_set I2C2_EV_IRQHandler,Default_Handler

   .weak      I2C2_ER_IRQHandler
   .thumb_set I2C2_ER_IRQHandler,Default_Handler

   .weak      SPI1_IRQHandler
   .thumb_set SPI1_IRQHandler,Default_Handler

   .weak      SPI2_IRQHandler
   .thumb_set SPI2_IRQHandler,Default_Handler

   .weak      USART1_IRQHandler
   .thumb_set USART1_IRQHandler,Default_Handler

   .weak      USART2_IRQHandler
   .thumb_set USART2_IRQHandler,Default_Handler

   .weak      USART3_IRQHandler
   .thumb_set USART3_IRQHandler,Default_Handler

   .weak      EXTI15_10_IRQHandler
   .thumb_set EXTI15_10_IRQHandler,Default_Handler

   .weak      RTC_Alarm_IRQHandler
   .thumb_set RTC_Alarm_IRQHandler,Default_Handler

   .weak      OTG_FS_WKUP_IRQHandler
   .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler

   .weak      TIM8_BRK_TIM12_IRQHandler
   .thumb_set TIM8_BRK_TIM12_IRQHandler,Default_Handler

   .weak      TIM8_UP_TIM13_IRQHandler
   .thumb_set TIM8_UP_TIM13_IRQHandler,Default_Handler

   .weak      TIM8_TRG_COM_TIM14_IRQHandler
   .thumb_set TIM8_TRG_COM_TIM14_IRQHandler,Default_Handler

   .weak      TIM8_CC_IRQHandler
   .thumb_set TIM8_CC_IRQHandler,Default_Handler

   .weak      DMA1_Stream7_IRQHandler
   .thumb_set DMA1_Stream7_IRQHandler,Default_Handler

   .weak      FSMC_IRQHandler
   .thumb_set FSMC_IRQHandler,Default_Handler

   .weak      SDIO_IRQHandler
   .thumb_set SDIO_IRQHandler,Default_Handler

   .weak      TIM5_IRQHandler
   .thumb_set TIM5_IRQHandler,Default_Handler

   .weak      SPI3_IRQHandler
   .thumb_set SPI3_IRQHandler,Default_Handler

   .weak      UART4_IRQHandler
   .thumb_set UART4_IRQHandler,Default_Handler

   .weak      UART5_IRQHandler
   .thumb_set UART5_IRQHandler,Default_Handler

   .weak      TIM6_DAC_IRQHandler
   .thumb_set TIM6_DAC_IRQHandler,Default_Handler

   .weak      TIM7_IRQHandler
   .thumb_set TIM7_IRQHandler,Default_Handler

   .weak      DMA2_Stream0_IRQHandler
   .thumb_set DMA2_Stream0_IRQHandler,Default_Handler

   .weak      DMA2_Stream1_IRQHandler
   .thumb_set DMA2_Stream1_IRQHandler,Default_Handler

   .weak      DMA2_Stream2_IRQHandler
   .thumb_set DMA2_Stream2_IRQHandler,Default_Handler

   .weak      DMA2_Stream3_IRQHandler
   .thumb_set DMA2_Stream3_IRQHandler,Default_Handler

   .weak      DMA2_Stream4_IRQHandler
   .thumb_set DMA2_Stream4_IRQHandler,Default_Handler

   .weak      DFSDM1_FLT0_IRQHandler
   .thumb_set DFSDM1_FLT0_IRQHandler,Default_Handler

   .weak      DFSDM1_FLT1_IRQHandler
   .thumb_set DFSDM1_FLT1_IRQHandler,Default_Handler

   .weak      CAN2_TX_IRQHandler
   .thumb_set CAN2_TX_IRQHandler,Default_Handler

   .weak      CAN2_RX0_IRQHandler
   .thumb_set CAN2_RX0_IRQHandler,Default_Handler

   .weak      CAN2_RX1_IRQHandler
   .thumb_set CAN2_RX1_IRQHandler,Default_Handler

   .weak      CAN2_SCE_IRQHandler
   .thumb_set CAN2_SCE_IRQHandler,Default_Handler

   .weak      OTG_FS_IRQHandler
   .thumb_set OTG_FS_IRQHandler,Default_Handler

   .weak      DMA2_Stream5_IRQHandler
   .thumb_set DMA2_Stream5_IRQHandler,Default_Handler

   .weak      DMA2_Stream6_IRQHandler
   .thumb_set DMA2_Stream6_IRQHandler,Default_Handler

   .weak      DMA2_Stream7_IRQHandler
   .thumb_set DMA2_Stream7_IRQHandler,Default_Handler

   .weak      USART6_IRQHandler
   .thumb_set USART6_IRQHandler,Default_Handler

   .weak      I2C3_EV_IRQHandler
   .thumb_set I2C3_EV_IRQHandler,Default_Handler

   .weak      I2C3_ER_IRQHandler
   .thumb_set I2C3_ER_IRQHandler,Default_Handler

   .weak      CAN3_TX_IRQHandler
   .thumb_set CAN3_TX_IRQHandler,Default_Handler

   .weak      CAN3_RX0_IRQHandler
   .thumb_set CAN3_RX0_IRQHandler,Default_Handler

   .weak      CAN3_RX1_IRQHandler
   .thumb_set CAN3_RX1_IRQHandler,Default_Handler

   .weak      CAN3_SCE_IRQHandler
   .thumb_set CAN3_SCE_IRQHandler,Default_Handler

   .weak      RNG_IRQHandler
   .thumb_set RNG_IRQHandler,Default_Handler

   .weak      FPU_IRQHandler
   .thumb_set FPU_IRQHandler,Default_Handler

   .weak      UART7_IRQHandler
   .thumb_set UART7_IRQHandler,Default_Handler

   .weak      UART8_IRQHandler
   .thumb_set UART8_IRQHandler,Default_Handler

   .weak      SPI4_IRQHandler
   .thumb_set SPI4_IRQHandler,Default_Handler

   .weak      SPI5_IRQHandler
   .thumb_set SPI5_IRQHandler,Default_Handler

   .weak      SAI1_IRQHandler
   .thumb_set SAI1_IRQHandler,Default_Handler

   .weak      UART9_IRQHandler
   .thumb_set UART9_IRQHandler,Default_Handler

   .weak      UART10_IRQHandler
   .thumb_set UART10_IRQHandler,Default_Handler

   .weak      QUADSPI_IRQHandler
   .thumb_set QUADSPI_IRQHandler,Default_Handler

    .weak     FMPI2C1_EV_IRQHandler
   .thumb_set FMPI2C1_EV_IRQHandler,Default_Handler

   .weak      FMPI2C1_ER_IRQHandler
   .thumb_set FMPI2C1_ER_IRQHandler,Default_Handler

   .weak      LPTIM1_IRQHandler
   .thumb_set LPTIM1_IRQHandler,Default_Handler

   .weak      DFSDM2_FLT0_IRQHandler
   .thumb_set DFSDM2_FLT0_IRQHandler,Default_Handler

   .weak      DFSDM2_FLT1_IRQHandler
   .thumb_set DFSDM2_FLT1_IRQHandler,Default_Handler

   .weak      DFSDM2_FLT2_IRQHandler
   .thumb_set DFSDM2_FLT2_IRQHandler,Default_Handler

   .weak      DFSDM2_FLT3_IRQHandler
   .thumb_set DFSDM2_FLT3_IRQHandler,Default_Handler
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

{'repo_name': 'RoboMaster/RoboRTS-Firmware', 'stars': '205', 'repo_language': 'C', 'file_name': 'protocol.md', 'mime_type': 'text/x-c', 'hash': 4043286254819970396, 'source_dataset': 'data'}


<snippet>
    <content><![CDATA[<!--

@license Apache-2.0

Copyright (c) 2020 The Stdlib Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

-->
]]></content>

    <!-- Tab trigger to activate the snippet -->
    <tabTrigger>stdlib.license</tabTrigger>

    <!-- Scope the tab trigger will be active in -->
    <scope>text.html.markdown</scope>

    <!-- Description to show in the menu -->
    <description>Markdown license header</description>
</snippet>

{'repo_name': 'stdlib-js/stdlib', 'stars': '2298', 'repo_language': 'JavaScript', 'file_name': '00141.aec902144f2d18dce81d4a5dd84e11bf.txt', 'mime_type': 'text/plain', 'hash': -3457920351715876054, 'source_dataset': 'data'}


/*
 * Copyright (c) 2015, Michael Mitterer (office@mikemitterer.at),
 * IT-Consulting and Development Limited.
 *
 * All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

library mdldnd;

import 'dart:html' as dom;
import 'package:logging/logging.dart';
import 'package:dryice/dryice.dart' as di;
import 'package:validate/validate.dart';

import 'package:dnd/dnd.dart';

import "package:mdl/mdlcore.dart";
import "package:mdl/mdlcomponents.dart";
import "package:mdl/mdlapplication.dart";
import "package:mdl/mdlutils.dart";

part "src/dnd/MaterialDraggable.dart";
part "src/dnd/MaterialDropZone.dart";

void registerMdlDND() {
    registerMaterialDraggable();
    registerMaterialDropZone();
}

{'repo_name': 'MikeMitterer/dart-material-design-lite', 'stars': '231', 'repo_language': 'CSS', 'file_name': 'tooltip-rich.html', 'mime_type': 'text/plain', 'hash': 2434780570279761234, 'source_dataset': 'data'}


#! /bin/sh

. ../../testenv.sh

analyze_failure --std=08 OSVVM_TB.vhd

clean

echo "Test successful"

{'repo_name': 'ghdl/ghdl', 'stars': '1042', 'repo_language': 'VHDL', 'file_name': 'Debugging.rst', 'mime_type': 'text/plain', 'hash': 8447999515278010467, 'source_dataset': 'data'}


/* Arduino SPIMemory Library v.3.4.0
 * Copyright (C) 2019 by Prajwal Bhattaram
 * Created by Prajwal Bhattaram - 18/04/2018
 * Modified by Prajwal Bhattaram - 19/06/2018
 *
 * This file is part of the Arduino SPIMemory Library. This library is for
 * Flash and FRAM memory modules. In its current form it enables reading,
 * writing and erasing data from and to various locations;
 * suspending and resuming programming/erase and powering down for low power operation.
 *
 * This Library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This Library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License v3.0
 * along with the Arduino SPIMemory Library.  If not, see
 * <http://www.gnu.org/licenses/>.
 */

 #include "SPIFlash.h"
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//     Private Functions that retrieve date from the SFDP tables      //
//              - if the flash chip supports SFDP                     //
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//

// This function returns the SFDP table requested as an array of 32 bit integers
bool SPIFlash::_getSFDPTable(uint32_t _address, uint8_t *data_buffer, uint8_t numberOfDWords) {
  if(!_notBusy()) {
   return false;
  }
  _beginSPI(READSFDP);
  _nextByte(WRITE, Higher(_address));
  _nextByte(WRITE, Hi(_address));
  _nextByte(WRITE, Lo(_address));
  _nextByte(WRITE, DUMMYBYTE);
  _nextBuf(READDATA, &(*data_buffer), numberOfDWords*4); //*4 to convert from dWords to bytes
  CHIP_DESELECT
  return true;
}

// This function returns a custom length of data from the SFDP table requested as an array of 8 bit integers (bytes)
bool SPIFlash::_getSFDPData(uint32_t _address, uint8_t *data_buffer, uint8_t numberOfBytes) {
  if(!_notBusy()) {
   return false;
  }
  _beginSPI(READSFDP);
  _nextByte(WRITE, Higher(_address));
  _nextByte(WRITE, Hi(_address));
  _nextByte(WRITE, Lo(_address));
  _nextByte(WRITE, DUMMYBYTE);
  _nextBuf(READDATA, &(*data_buffer), numberOfBytes); //*4 to convert from dWords to bytes
  CHIP_DESELECT
  return true;
}

//dWordNumber can be between 1 to 256
uint32_t SPIFlash::_getSFDPdword(uint32_t _tableAddress, uint8_t dWordNumber) {
  if(!_notBusy()) {
   return false;
  }
  union {
    uint32_t dWord;
    uint8_t byteArray[4];
  } SFDPdata;
  uint32_t _address = ADDRESSOFSFDPDWORD(_tableAddress, dWordNumber);
  _getSFDPData(_address, &(*SFDPdata.byteArray), sizeof(uint32_t));
  return SFDPdata.dWord;
}

//startByte is the byte from which the 16-bit integer starts and can be between 1 to 256
uint16_t SPIFlash::_getSFDPint(uint32_t _tableAddress, uint8_t dWordNumber, uint8_t startByte) {
  if(!_notBusy()) {
   return false;
  }
  union {
    uint16_t word;
    uint8_t byteArray[2];
  } SFDPdata;
  uint32_t _address = ADDRESSOFSFDPBYTE(_tableAddress, dWordNumber, startByte);
  _getSFDPData(_address, &(*SFDPdata.byteArray), sizeof(uint16_t));
  return SFDPdata.word;
}

//byteNumber can be between 1 to 256
uint8_t SPIFlash::_getSFDPbyte(uint32_t _tableAddress, uint8_t dWordNumber, uint8_t byteNumber) {
  if(!_notBusy()) {
   return false;
  }
  uint8_t SFDPdataByte;
  uint32_t _address = ADDRESSOFSFDPBYTE(_tableAddress, dWordNumber, byteNumber);
  _getSFDPData(_address, &SFDPdataByte, sizeof(uint8_t));
  return SFDPdataByte;
}

//bitNumber can be between 0 to 31
bool SPIFlash::_getSFDPbit(uint32_t _tableAddress, uint8_t dWordNumber, uint8_t bitNumber) {
  return(_getSFDPdword(_tableAddress, dWordNumber) & (0x01 << bitNumber));
}

uint32_t SPIFlash::_getSFDPTableAddr(uint32_t paramHeaderNum) {
  uint32_t _tableAddr = _getSFDPdword(paramHeaderNum * 8, 0x02); // Each parameter header table is 8 bytes long
  Highest(_tableAddr) = 0x00; // Top byte in the dWord containing the table address is always 0xFF.
  return _tableAddr;
}

bool SPIFlash::_checkForSFDP(void) {
  if (_getSFDPdword(SFDP_HEADER_ADDR, SFDP_SIGNATURE_DWORD) == SFDPSIGNATURE) {
    _chip.sfdpAvailable = true;
    #ifdef RUNDIAGNOSTIC
    Serial.println(F("SFDP available"));
    #endif
  }
  else {
    _troubleshoot(NOSFDP);
    _chip.sfdpAvailable = false;
  }
  return _chip.sfdpAvailable;
}
uint32_t SPIFlash::_calcSFDPEraseTimeUnits(uint8_t _unitBits) {
  switch (_unitBits) {
    case MS1:
    return 1000L;
    break;

    case MS16:
    return (16L*1000L);
    break;

    case MS128:
    return (128L*1000L);
    break;

    case S1:
    return (1000L*1000L);
  }
  return false;
}

void SPIFlash::_getSFDPEraseParam(void) {
  // Get sector erase details if available on SFDP Tables
  if (_noOfBasicParamDwords >= SFDP_ERASE1_INSTRUCTION_DWORD) {
    uint32_t _eraseInfoAddress;
    uint8_t _eraseInfo[8];
    uint8_t _eraseExists = 0;
    uint8_t _count;
    uint32_t _units;
    union {
      uint32_t dword;
      uint8_t byte[4];
    } _eraseTime;
    _eraseInfoAddress = ADDRESSOFSFDPDWORD(_BasicParamTableAddr, SFDP_ERASE1_INSTRUCTION_DWORD);
    _getSFDPData(_eraseInfoAddress, &(*_eraseInfo), 8);

    for (uint8_t i = 0; i < 8; i++) {
      _eraseExists += _eraseInfo[i];
      if (!_eraseExists) { // If faulty SFDP read, then revert to defaults
          kb4Erase.supported = kb32Erase.supported = kb64Erase.supported = chipErase.supported = true;
          kb4Erase.opcode = SECTORERASE;
          kb32Erase.opcode = BLOCK32ERASE;
          kb64Erase.opcode = BLOCK64ERASE;
          kb4Erase.time = BUSY_TIMEOUT;
          kb32Erase.time = kb4Erase.time * 8;
          kb64Erase.time = kb32Erase.time * 4;
          kb256Erase.supported = false;
          chipErase.opcode = CHIPERASE;
          chipErase.time = kb64Erase.time * 100L;
        _troubleshoot(NOSFDPERASEPARAM);
      }
    }
    for (uint8_t i = 0; i < 8; i++) {
      if ((i % 2) == 0) {
        switch ((_eraseInfo[i])) {
          case KB4ERASE_TYPE:
          kb4Erase.supported = true;
          kb4Erase.opcode = _eraseInfo[i+1];
          break;

          case KB32ERASE_TYPE:
          kb32Erase.supported = true;
          kb32Erase.opcode = _eraseInfo[i+1];
          break;

          case KB64ERASE_TYPE:
          kb64Erase.supported = true;
          kb64Erase.opcode = _eraseInfo[i+1];
          break;

          case KB256ERASE_TYPE:
          kb256Erase.supported = true;
          kb256Erase.opcode = _eraseInfo[i+1];
          break;
        }
      }
    }
    // Some flash memory chips have information about sector erase times in DWORD 10 of SFDP Basic param table.
    if (_noOfBasicParamDwords >= SFDP_SECTOR_ERASE_TIME_DWORD) {
      _eraseTime.dword = _getSFDPdword(_BasicParamTableAddr, SFDP_SECTOR_ERASE_TIME_DWORD);
      _eraseTimeMultiplier = _eraseTime.byte[0];
      setUpperNibble(_eraseTimeMultiplier, 0b0000);
      _eraseTimeMultiplier = 2 * (_eraseTimeMultiplier + 1);  // Refer JESD216B Page 21

      for (uint8_t i = 0; i < 8; i++) {
        if ((i % 2) == 0) {
          switch ((_eraseInfo[i])) {
            case KB4ERASE_TYPE:
            _count = ( ( ( (_eraseTime.byte[1] & _createMask(0, 0)) << 5) | ( (_eraseTime.byte[0] & _createMask(4, 7)) ) >> 4) + 1);
            _units = _calcSFDPEraseTimeUnits((_eraseTime.byte[1] & _createMask(1, 2)) >> 1);
            kb4Erase.time = (_count * _units * _eraseTimeMultiplier);
            break;

            case KB32ERASE_TYPE:
            _count = (((_eraseTime.byte[1] & _createMask(3, 7)) >> 3) + 1);
            _units = _calcSFDPEraseTimeUnits(_eraseTime.byte[2] & _createMask(0, 1));
            kb32Erase.time = (_count * _units * _eraseTimeMultiplier);
            break;

            case KB64ERASE_TYPE:
            _count = (((_eraseTime.byte[2] & _createMask(2, 6)) >> 2) + 1);
            _units = _calcSFDPEraseTimeUnits(((_eraseTime.byte[2] & _createMask(7, 7)) >> 7) | (_eraseTime.byte[3] & _createMask(0,0)) << 1);
            kb64Erase.time = (_count * _units * _eraseTimeMultiplier);
            break;

            case KB256ERASE_TYPE:
            _count = (((_eraseTime.byte[3] & _createMask(1, 5)) >> 1) + 1);
            _units = _calcSFDPEraseTimeUnits((_eraseTime.byte[3] & _createMask(6, 7)) >> 6);
            kb64Erase.time = (_count * _units) * _eraseTimeMultiplier;
            break;
          }
        }
      }

      // Some flash memory chips have information about chip erase times in DWORD 11 of SFDP Basic param table.
      if (_noOfBasicParamDwords >= SFDP_CHIP_ERASE_TIME_DWORD) {
        // Get chip erase details
        _eraseInfoAddress = ADDRESSOFSFDPDWORD(_BasicParamTableAddr, DWORD(11));
        _getSFDPData(_eraseInfoAddress, &(*_eraseInfo), 8);
        chipErase.supported = true; // chipErase.opcode is set in _chipID().
        _count = (((_eraseTime.byte[3] & _createMask(0, 4))) + 1);
        _units = _calcSFDPEraseTimeUnits((_eraseTime.byte[3] & _createMask(5, 6)) >> 5);
        chipErase.time = (_count * _units) * _eraseTimeMultiplier;
      }

    }
    else { //If flash memory does not have any sfdp information about sector erase times
      _troubleshoot(NOSFDPERASETIME);
      kb4Erase.time = BUSY_TIMEOUT;
      kb32Erase.time = kb4Erase.time * 8;
      kb64Erase.time = kb32Erase.time * 4;
      kb256Erase.supported = false;
      chipErase.opcode = CHIPERASE;
      chipErase.time = kb64Erase.time * 100L;
    }

  }
  else {
    _troubleshoot(NOSFDPERASEPARAM);
  }
}

// Gets IO timing information from SFDP tables - if available.
void SPIFlash::_getSFDPProgramTimeParam(void) {
  if (_noOfBasicParamDwords >= SFDP_PROGRAM_TIME_DWORD) {
    union {
      uint32_t dword;
      uint8_t byte[4];
    } _sfdp;
    uint8_t _count;
    uint32_t _units;

    _sfdp.dword= _getSFDPdword(_BasicParamTableAddr, SFDP_PROGRAM_TIME_DWORD);

    //Calculate Program time multiplier
    _prgmTimeMultiplier = (2 * ((_sfdp.byte[1] >> 4) + 1));
    //Serial.print("_prgmTimeMultiplier: ");
    //Serial.println(_prgmTimeMultiplier);

    // Get pageSize
    //setUpperNibble(_eraseTimeMultiplier, 0b0000);
    _pageSize = setUpperNibble(_sfdp.byte[1], 0b0000);
    _pageSize *= 2;
    //Serial.print("_pageSize: ");
    //Serial.println(_pageSize);

    //Calculate Page Program time
    _count = (((_sfdp.byte[1] & _createMask(0, 4))) + 1);
    ((_sfdp.byte[1] & _createMask(7, 7)) >> 7) ? (_units = 64) : (_units = 8);
    _pagePrgmTime = (_count * _units) * _prgmTimeMultiplier;
    //Serial.print("_pagePrgmTime: ");
    //Serial.println(_pagePrgmTime);

    //Calculate First Byte Program time
    _count = ( (((_sfdp.byte[1] & _createMask(6, 7)) >> 4) | (((_sfdp.byte[2] & _createMask(6, 7))) >> 6)) + 1);
    ((_sfdp.byte[2] & _createMask(5, 5)) >> 5) ? (_units = 8) : (_units = 1);
    _byteFirstPrgmTime = (_count * _units) * _prgmTimeMultiplier;
    //Serial.print("_byteFirstPrgmTime :");
    //Serial.println(_byteFirstPrgmTime);

    //Calculate Additional Byte Program time
    _count = ( ((_sfdp.byte[2] & _createMask(4, 1)) >> 1) + 1);
    (_sfdp.byte[2] & _createMask(0, 0)) ? (_units = 8) : (_units = 1);
    _byteAddnlPrgmTime = (_count * _units) * _prgmTimeMultiplier;
    //Serial.print("_byteAddnlPrgmTime :");
    //Serial.println(_byteAddnlPrgmTime);
  }
  else {
    _pageSize = SPI_PAGESIZE;
    _pagePrgmTime = BUSY_TIMEOUT;
    _byteFirstPrgmTime = BUSY_TIMEOUT;
    _byteAddnlPrgmTime = BUSY_TIMEOUT;
    _troubleshoot(NOSFDPPROGRAMTIMEPARAM);
  }
}

// Reads and stores any required values from the Basic Flash Parameter table
bool SPIFlash::_getSFDPFlashParam(void) {
    _noOfParamHeaders = _getSFDPbyte(SFDP_HEADER_ADDR, SFDP_NPH_DWORD, SFDP_NPH_BYTE) + 1; // Number of parameter headers is 0 based - i.e. 0x00 means there is 1 header.
    if (_noOfParamHeaders > 1) {
      _SectorMapParamTableAddr = _getSFDPTableAddr(SFDP_SECTOR_MAP_PARAM_TABLE_NO);
    }
    _noOfBasicParamDwords = _getSFDPbyte(SFDP_BASIC_PARAM_TABLE_HDR_ADDR, SFDP_PARAM_TABLE_LENGTH_DWORD, SFDP_PARAM_TABLE_LENGTH_BYTE);
    _BasicParamTableAddr = _getSFDPTableAddr(SFDP_BASIC_PARAM_TABLE_NO);

    // Calculate chip capacity

    _chip.capacity = _getSFDPdword(_BasicParamTableAddr, SFDP_MEMORY_DENSITY_DWORD);
    if (bitIsSet(Highest(_chip.capacity), 7)) {     // If bit 31 (bit 7 of byte 3) is set, then the density is double the value read in bits from 30:0 (Refer to Page 16 of JESD216B)
      clearBit(Highest(_chip.capacity), 7); // Clear bit 31
      _chip.capacity*=2;
    }
    // Else _chip.capacity is the value as read in bits.

    _chip.capacity = (_chip.capacity/8) + 1; // Since the value read in is in bits, convert it to bytes here (1 is added because the number of bits is zero based - i.e. if there are 8 bytes, then they are numbered 0 -> 7)

  // Get Erase Parameters if available
  _getSFDPEraseParam();

  //Get Program time Parameters
  _getSFDPProgramTimeParam();
// TODO Update the use of Program time parameters across the library

  //Serial.print("dWord 9: 0x");
  //Serial.println(_getSFDPdword(_BasicParamTableAddr, DWORD(9)), HEX);
  #ifdef RUNDIAGNOSTIC
    Serial.println("Chip identified using sfdp. Most of this chip's functions are supported by the library.");
  #endif
  return true;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ End SFDP ID section ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//

{'repo_name': 'Marzogh/SPIMemory', 'stars': '223', 'repo_language': 'C++', 'file_name': 'DMASAMD.cpp', 'mime_type': 'text/x-c', 'hash': 7144894107391451697, 'source_dataset': 'data'}


# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities to create TensorProtos."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import six

from tensorflow.core.framework import tensor_pb2
from tensorflow.core.framework import tensor_shape_pb2
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.util import compat

# Fallback in case fast_tensor_util is not properly compiled.
# pylint: disable=g-import-not-at-top
try:
  from tensorflow.python.framework import fast_tensor_util
  _FAST_TENSOR_UTIL_AVAILABLE = True
except ImportError:
  _FAST_TENSOR_UTIL_AVAILABLE = False

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.util.tf_export import tf_export

# pylint: enable=g-import-not-at-top

def ExtractBitsFromFloat16(x):
  return np.asscalar(np.asarray(x, dtype=np.float16).view(np.uint16))

def SlowAppendFloat16ArrayToTensorProto(tensor_proto, proto_values):
  tensor_proto.half_val.extend(
      [ExtractBitsFromFloat16(x) for x in proto_values])

def ExtractBitsFromBFloat16(x):
  return np.asscalar(
      np.asarray(x, dtype=dtypes.bfloat16.as_numpy_dtype).view(np.uint16))

def SlowAppendBFloat16ArrayToTensorProto(tensor_proto, proto_values):
  tensor_proto.half_val.extend(
      [ExtractBitsFromBFloat16(x) for x in proto_values])

if _FAST_TENSOR_UTIL_AVAILABLE:
  _NP_TO_APPEND_FN = {
      dtypes.bfloat16.as_numpy_dtype:
          SlowAppendBFloat16ArrayToTensorProto,
      # TODO(sesse): We should have a
      # fast_tensor_util.AppendFloat16ArrayToTensorProto,
      # but it seems np.float16_t doesn't exist?
      np.float16:
          SlowAppendFloat16ArrayToTensorProto,
      np.float32:
          fast_tensor_util.AppendFloat32ArrayToTensorProto,
      np.float64:
          fast_tensor_util.AppendFloat64ArrayToTensorProto,
      np.int32:
          fast_tensor_util.AppendInt32ArrayToTensorProto,
      np.int64:
          fast_tensor_util.AppendInt64ArrayToTensorProto,
      np.uint8:
          fast_tensor_util.AppendUInt8ArrayToTensorProto,
      np.uint16:
          fast_tensor_util.AppendUInt16ArrayToTensorProto,
      np.uint32:
          fast_tensor_util.AppendUInt32ArrayToTensorProto,
      np.uint64:
          fast_tensor_util.AppendUInt64ArrayToTensorProto,
      np.int8:
          fast_tensor_util.AppendInt8ArrayToTensorProto,
      np.int16:
          fast_tensor_util.AppendInt16ArrayToTensorProto,
      np.complex64:
          fast_tensor_util.AppendComplex64ArrayToTensorProto,
      np.complex128:
          fast_tensor_util.AppendComplex128ArrayToTensorProto,
      np.object:
          fast_tensor_util.AppendObjectArrayToTensorProto,
      np.bool:
          fast_tensor_util.AppendBoolArrayToTensorProto,
      dtypes.qint8.as_numpy_dtype:
          fast_tensor_util.AppendInt8ArrayToTensorProto,
      dtypes.quint8.as_numpy_dtype:
          fast_tensor_util.AppendUInt8ArrayToTensorProto,
      dtypes.qint16.as_numpy_dtype:
          fast_tensor_util.AppendInt8ArrayToTensorProto,
      dtypes.quint16.as_numpy_dtype:
          fast_tensor_util.AppendUInt8ArrayToTensorProto,
      dtypes.qint32.as_numpy_dtype:
          fast_tensor_util.AppendInt32ArrayToTensorProto,
      # NOTE(touts): Intentionally no way to feed a DT_BFLOAT16.
  }
else:

  def SlowAppendFloat32ArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.float_val.extend([np.asscalar(x) for x in proto_values])

  def SlowAppendFloat64ArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.double_val.extend([np.asscalar(x) for x in proto_values])

  def SlowAppendIntArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.int_val.extend([np.asscalar(x) for x in proto_values])

  def SlowAppendInt64ArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.int64_val.extend([np.asscalar(x) for x in proto_values])

  def SlowAppendQIntArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.int_val.extend([np.asscalar(x[0]) for x in proto_values])

  def SlowAppendUInt32ArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.uint32_val.extend([np.asscalar(x) for x in proto_values])

  def SlowAppendUInt64ArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.uint64_val.extend([np.asscalar(x) for x in proto_values])

  def SlowAppendComplex64ArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.scomplex_val.extend(
        [np.asscalar(v) for x in proto_values for v in [x.real, x.imag]])

  def SlowAppendComplex128ArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.dcomplex_val.extend(
        [np.asscalar(v) for x in proto_values for v in [x.real, x.imag]])

  def SlowAppendObjectArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.string_val.extend([compat.as_bytes(x) for x in proto_values])

  def SlowAppendBoolArrayToTensorProto(tensor_proto, proto_values):
    tensor_proto.bool_val.extend([np.asscalar(x) for x in proto_values])

  _NP_TO_APPEND_FN = {
      dtypes.bfloat16.as_numpy_dtype: SlowAppendBFloat16ArrayToTensorProto,
      np.float16: SlowAppendFloat16ArrayToTensorProto,
      np.float32: SlowAppendFloat32ArrayToTensorProto,
      np.float64: SlowAppendFloat64ArrayToTensorProto,
      np.int32: SlowAppendIntArrayToTensorProto,
      np.int64: SlowAppendInt64ArrayToTensorProto,
      np.uint8: SlowAppendIntArrayToTensorProto,
      np.uint16: SlowAppendIntArrayToTensorProto,
      np.uint32: SlowAppendUInt32ArrayToTensorProto,
      np.uint64: SlowAppendUInt64ArrayToTensorProto,
      np.int8: SlowAppendIntArrayToTensorProto,
      np.int16: SlowAppendIntArrayToTensorProto,
      np.complex64: SlowAppendComplex64ArrayToTensorProto,
      np.complex128: SlowAppendComplex128ArrayToTensorProto,
      np.object: SlowAppendObjectArrayToTensorProto,
      np.bool: SlowAppendBoolArrayToTensorProto,
      dtypes.qint8.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
      dtypes.quint8.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
      dtypes.qint16.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
      dtypes.quint16.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
      dtypes.qint32.as_numpy_dtype: SlowAppendQIntArrayToTensorProto,
      # NOTE(touts): Intentionally no way to feed a DT_BFLOAT16.
  }

def GetFromNumpyDTypeDict(dtype_dict, dtype):
  # NOTE: dtype_dict.get(dtype) always returns None.
  for key, val in six.iteritems(dtype_dict):
    if key == dtype:
      return val
  return None

def GetNumpyAppendFn(dtype):
  # numpy dtype for strings are variable length. We can not compare
  # dtype with a single constant (np.string does not exist) to decide
  # dtype is a "string" type. We need to compare the dtype.type to be
  # sure it's a string type.
  if dtype.type == np.string_ or dtype.type == np.unicode_:
    if _FAST_TENSOR_UTIL_AVAILABLE:
      return fast_tensor_util.AppendObjectArrayToTensorProto
    else:
      return SlowAppendObjectArrayToTensorProto
  return GetFromNumpyDTypeDict(_NP_TO_APPEND_FN, dtype)

def TensorShapeProtoToList(shape):
  """Convert a TensorShape to a list.

  Args:
    shape: A TensorShapeProto.

  Returns:
    List of integers representing the dimensions of the tensor.
  """
  return [dim.size for dim in shape.dim]

def _GetDenseDimensions(list_of_lists):
  """Returns the inferred dense dimensions of a list of lists."""
  if not isinstance(list_of_lists, (list, tuple)):
    return []
  elif not list_of_lists:
    return [0]
  else:
    return [len(list_of_lists)] + _GetDenseDimensions(list_of_lists[0])

def _FlattenToStrings(nested_strings):
  if isinstance(nested_strings, (list, tuple)):
    for inner in nested_strings:
      for flattened_string in _FlattenToStrings(inner):
        yield flattened_string
  else:
    yield nested_strings

_TENSOR_CONTENT_TYPES = frozenset([
    dtypes.float32, dtypes.float64, dtypes.int32, dtypes.uint8, dtypes.int16,
    dtypes.int8, dtypes.int64, dtypes.qint8, dtypes.quint8, dtypes.qint16,
    dtypes.quint16, dtypes.qint32, dtypes.uint32, dtypes.uint64
])

class _Message(object):

  def __init__(self, message):
    self._message = message

  def __repr__(self):
    return self._message

def _FirstNotNone(l):
  for x in l:
    if x is not None:
      if isinstance(x, ops.Tensor):
        return _Message("list containing Tensors")
      else:
        return x
  return None

def _NotNone(v):
  if v is None:
    return _Message("None")
  else:
    return v

def _FilterTuple(v):
  if not isinstance(v, (list, tuple)):
    return v
  if isinstance(v, tuple):
    if not any(isinstance(x, (list, tuple)) for x in v):
      return None
  if isinstance(v, list):
    if not any(isinstance(x, (list, tuple)) for x in v):
      return _FirstNotNone(
          [None if isinstance(x, (list, tuple)) else x for x in v])
  return _FirstNotNone([_FilterTuple(x) for x in v])

def _FilterInt(v):
  if isinstance(v, (list, tuple)):
    return _FirstNotNone([_FilterInt(x) for x in v])
  return None if isinstance(
      v, (compat.integral_types, tensor_shape.Dimension)) else _NotNone(v)

def _FilterFloat(v):
  if isinstance(v, (list, tuple)):
    return _FirstNotNone([_FilterFloat(x) for x in v])
  return None if isinstance(v, compat.real_types) else _NotNone(v)

def _FilterComplex(v):
  if isinstance(v, (list, tuple)):
    return _FirstNotNone([_FilterComplex(x) for x in v])
  return None if isinstance(v, compat.complex_types) else _NotNone(v)

def _FilterStr(v):
  if isinstance(v, (list, tuple)):
    return _FirstNotNone([_FilterStr(x) for x in v])
  if isinstance(v, compat.bytes_or_text_types):
    return None
  else:
    return _NotNone(v)

def _FilterBool(v):
  if isinstance(v, (list, tuple)):
    return _FirstNotNone([_FilterBool(x) for x in v])
  return None if isinstance(v, bool) else _NotNone(v)

def _FilterNotTensor(v):
  if isinstance(v, (list, tuple)):
    return _FirstNotNone([_FilterNotTensor(x) for x in v])
  return str(v) if isinstance(v, ops.Tensor) else None

_TF_TO_IS_OK = {
    dtypes.bool: [_FilterBool],
    dtypes.complex128: [_FilterComplex],
    dtypes.complex64: [_FilterComplex],
    dtypes.float16: [_FilterFloat],
    dtypes.float32: [_FilterFloat],
    dtypes.float64: [_FilterFloat],
    dtypes.int16: [_FilterInt],
    dtypes.int32: [_FilterInt],
    dtypes.int64: [_FilterInt],
    dtypes.int8: [_FilterInt],
    dtypes.qint16: [_FilterInt, _FilterTuple],
    dtypes.qint32: [_FilterInt, _FilterTuple],
    dtypes.qint8: [_FilterInt, _FilterTuple],
    dtypes.quint16: [_FilterInt, _FilterTuple],
    dtypes.quint8: [_FilterInt, _FilterTuple],
    dtypes.string: [_FilterStr],
    dtypes.uint16: [_FilterInt],
    dtypes.uint8: [_FilterInt],
}

def _AssertCompatible(values, dtype):
  fn_list = _TF_TO_IS_OK.get(dtype, [_FilterNotTensor])
  mismatch = _FirstNotNone([fn(values) for fn in fn_list])
  if mismatch is not None:
    if dtype is None:
      raise TypeError("List of Tensors when single Tensor expected")
    else:
      raise TypeError("Expected %s, got %s of type '%s' instead." %
                      (dtype.name, repr(mismatch), type(mismatch).__name__))

@tf_export("make_tensor_proto")
def make_tensor_proto(values, dtype=None, shape=None, verify_shape=False):
  """Create a TensorProto.

  Args:
    values:         Values to put in the TensorProto.
    dtype:          Optional tensor_pb2 DataType value.
    shape:          List of integers representing the dimensions of tensor.
    verify_shape:   Boolean that enables verification of a shape of values.

  Returns:
    A `TensorProto`. Depending on the type, it may contain data in the
    "tensor_content" attribute, which is not directly useful to Python programs.
    To access the values you should convert the proto back to a numpy ndarray
    with `tensor_util.MakeNdarray(proto)`.

    If `values` is a `TensorProto`, it is immediately returned; `dtype` and
    `shape` are ignored.

  Raises:
    TypeError:  if unsupported types are provided.
    ValueError: if arguments have inappropriate values or if verify_shape is
     True and shape of values is not equals to a shape from the argument.

  make_tensor_proto accepts "values" of a python scalar, a python list, a
  numpy ndarray, or a numpy scalar.

  If "values" is a python scalar or a python list, make_tensor_proto
  first convert it to numpy ndarray. If dtype is None, the
  conversion tries its best to infer the right numpy data
  type. Otherwise, the resulting numpy array has a compatible data
  type with the given dtype.

  In either case above, the numpy ndarray (either the caller provided
  or the auto converted) must have the compatible type with dtype.

  make_tensor_proto then converts the numpy array to a tensor proto.

  If "shape" is None, the resulting tensor proto represents the numpy
  array precisely.

  Otherwise, "shape" specifies the tensor's shape and the numpy array
  can not have more elements than what "shape" specifies.

  """
  if isinstance(values, tensor_pb2.TensorProto):
    return values

  if dtype:
    dtype = dtypes.as_dtype(dtype)

  is_quantized = (
      dtype in [
          dtypes.qint8, dtypes.quint8, dtypes.qint16, dtypes.quint16,
          dtypes.qint32
      ])

  # We first convert value to a numpy array or scalar.
  if isinstance(values, (np.ndarray, np.generic)):
    if dtype:
      nparray = values.astype(dtype.as_numpy_dtype)
    else:
      nparray = values
  elif callable(getattr(values, "__array__", None)) or isinstance(
      getattr(values, "__array_interface__", None), dict):
    # If a class has the __array__ method, or __array_interface__ dict, then it
    # is possible to convert to numpy array.
    nparray = np.asarray(values, dtype=dtype)

    # This is the preferred way to create an array from the object, so replace
    # the `values` with the array so that _FlattenToStrings is not run.
    values = nparray
  else:
    if values is None:
      raise ValueError("None values not supported.")
    # if dtype is provided, forces numpy array to be the type
    # provided if possible.
    if dtype and dtype.is_numpy_compatible:
      np_dt = dtype.as_numpy_dtype
    else:
      np_dt = None
    # If shape is None, numpy.prod returns None when dtype is not set, but raises
    # exception when dtype is set to np.int64
    if shape is not None and np.prod(shape, dtype=np.int64) == 0:
      nparray = np.empty(shape, dtype=np_dt)
    else:
      _AssertCompatible(values, dtype)
      nparray = np.array(values, dtype=np_dt)
      # check to them.
      # We need to pass in quantized values as tuples, so don't apply the shape
      if (list(nparray.shape) != _GetDenseDimensions(values) and
          not is_quantized):
        raise ValueError("""Argument must be a dense tensor: %s"""
                         """ - got shape %s, but wanted %s.""" %
                         (values, list(nparray.shape),
                          _GetDenseDimensions(values)))

    # python/numpy default float type is float64. We prefer float32 instead.
    if (nparray.dtype == np.float64) and dtype is None:
      nparray = nparray.astype(np.float32)
    # python/numpy default int type is int64. We prefer int32 instead.
    elif (nparray.dtype == np.int64) and dtype is None:
      downcasted_array = nparray.astype(np.int32)
      # Do not down cast if it leads to precision loss.
      if np.array_equal(downcasted_array, nparray):
        nparray = downcasted_array

  # if dtype is provided, it must be compatible with what numpy
  # conversion says.
  numpy_dtype = dtypes.as_dtype(nparray.dtype)
  if numpy_dtype is None:
    raise TypeError("Unrecognized data type: %s" % nparray.dtype)

  # If dtype was specified and is a quantized type, we convert
  # numpy_dtype back into the quantized version.
  if is_quantized:
    numpy_dtype = dtype

  if dtype is not None and (not hasattr(dtype, "base_dtype") or
                            dtype.base_dtype != numpy_dtype.base_dtype):
    raise TypeError("Incompatible types: %s vs. %s. Value is %s" %
                    (dtype, nparray.dtype, values))

  # If shape is not given, get the shape from the numpy array.
  if shape is None:
    shape = nparray.shape
    is_same_size = True
    shape_size = nparray.size
  else:
    shape = [int(dim) for dim in shape]
    shape_size = np.prod(shape, dtype=np.int64)
    is_same_size = shape_size == nparray.size

    if verify_shape:
      if not nparray.shape == tuple(shape):
        raise TypeError("Expected Tensor's shape: %s, got %s." %
                        (tuple(shape), nparray.shape))

    if nparray.size > shape_size:
      raise ValueError(
          "Too many elements provided. Needed at most %d, but received %d" %
          (shape_size, nparray.size))

  tensor_proto = tensor_pb2.TensorProto(
      dtype=numpy_dtype.as_datatype_enum,
      tensor_shape=tensor_shape.as_shape(shape).as_proto())

  if is_same_size and numpy_dtype in _TENSOR_CONTENT_TYPES and shape_size > 1:
    if nparray.size * nparray.itemsize >= (1 << 31):
      raise ValueError(
          "Cannot create a tensor proto whose content is larger than 2GB.")
    tensor_proto.tensor_content = nparray.tostring()
    return tensor_proto

  # If we were not given values as a numpy array, compute the proto_values
  # from the given values directly, to avoid numpy trimming nulls from the
  # strings. Since values could be a list of strings, or a multi-dimensional
  # list of lists that might or might not correspond to the given shape,
  # we flatten it conservatively.
  if numpy_dtype == dtypes.string and not isinstance(values, np.ndarray):
    proto_values = _FlattenToStrings(values)

    # At this point, values may be a list of objects that we could not
    # identify a common type for (hence it was inferred as
    # np.object/dtypes.string).  If we are unable to convert it to a
    # string, we raise a more helpful error message.
    #
    # Ideally, we'd be able to convert the elements of the list to a
    # common type, but this type inference requires some thinking and
    # so we defer it for now.
    try:
      str_values = [compat.as_bytes(x) for x in proto_values]
    except TypeError:
      raise TypeError("Failed to convert object of type %s to Tensor. "
                      "Contents: %s. Consider casting elements to a "
                      "supported type." % (type(values), values))
    tensor_proto.string_val.extend(str_values)
    return tensor_proto

  # TensorFlow expects C order (a.k.a., eigen row major).
  proto_values = nparray.ravel()

  append_fn = GetNumpyAppendFn(proto_values.dtype)
  if append_fn is None:
    raise TypeError(
        "Element type not supported in TensorProto: %s" % numpy_dtype.name)
  append_fn(tensor_proto, proto_values)

  return tensor_proto

@tf_export("make_ndarray")
def MakeNdarray(tensor):
  """Create a numpy ndarray from a tensor.

  Create a numpy ndarray with the same shape and data as the tensor.

  Args:
    tensor: A TensorProto.

  Returns:
    A numpy array with the tensor contents.

  Raises:
    TypeError: if tensor has unsupported type.

  """
  shape = [d.size for d in tensor.tensor_shape.dim]
  num_elements = np.prod(shape, dtype=np.int64)
  tensor_dtype = dtypes.as_dtype(tensor.dtype)
  dtype = tensor_dtype.as_numpy_dtype

  if tensor.tensor_content:
    return (np.frombuffer(tensor.tensor_content, dtype=dtype).copy()
            .reshape(shape))
  elif tensor_dtype == dtypes.float16 or tensor_dtype == dtypes.bfloat16:
    # the half_val field of the TensorProto stores the binary representation
    # of the fp16: we need to reinterpret this as a proper float16
    if len(tensor.half_val) == 1:
      tmp = np.array(tensor.half_val[0], dtype=np.uint16)
      tmp.dtype = tensor_dtype.as_numpy_dtype
      return np.repeat(tmp, num_elements).reshape(shape)
    else:
      tmp = np.fromiter(tensor.half_val, dtype=np.uint16)
      tmp.dtype = tensor_dtype.as_numpy_dtype
      return tmp.reshape(shape)
  elif tensor_dtype == dtypes.float32:
    if len(tensor.float_val) == 1:
      return np.repeat(
          np.array(tensor.float_val[0], dtype=dtype),
          num_elements).reshape(shape)
    else:
      return np.fromiter(tensor.float_val, dtype=dtype).reshape(shape)
  elif tensor_dtype == dtypes.float64:
    if len(tensor.double_val) == 1:
      return np.repeat(
          np.array(tensor.double_val[0], dtype=dtype),
          num_elements).reshape(shape)
    else:
      return np.fromiter(tensor.double_val, dtype=dtype).reshape(shape)
  elif tensor_dtype in [
      dtypes.int32, dtypes.uint8, dtypes.uint16, dtypes.int16, dtypes.int8,
      dtypes.qint32, dtypes.quint8, dtypes.qint8, dtypes.qint16, dtypes.quint16
  ]:
    if len(tensor.int_val) == 1:
      return np.repeat(np.array(tensor.int_val[0], dtype=dtype),
                       num_elements).reshape(shape)
    else:
      return np.fromiter(tensor.int_val, dtype=dtype).reshape(shape)
  elif tensor_dtype == dtypes.int64:
    if len(tensor.int64_val) == 1:
      return np.repeat(
          np.array(tensor.int64_val[0], dtype=dtype),
          num_elements).reshape(shape)
    else:
      return np.fromiter(tensor.int64_val, dtype=dtype).reshape(shape)
  elif tensor_dtype == dtypes.string:
    if len(tensor.string_val) == 1:
      return np.repeat(
          np.array(tensor.string_val[0], dtype=dtype),
          num_elements).reshape(shape)
    else:
      return np.array(
          [x for x in tensor.string_val], dtype=dtype).reshape(shape)
  elif tensor_dtype == dtypes.complex64:
    it = iter(tensor.scomplex_val)
    if len(tensor.scomplex_val) == 2:
      return np.repeat(
          np.array(
              complex(tensor.scomplex_val[0], tensor.scomplex_val[1]),
              dtype=dtype), num_elements).reshape(shape)
    else:
      return np.array(
          [complex(x[0], x[1]) for x in zip(it, it)],
          dtype=dtype).reshape(shape)
  elif tensor_dtype == dtypes.complex128:
    it = iter(tensor.dcomplex_val)
    if len(tensor.dcomplex_val) == 2:
      return np.repeat(
          np.array(
              complex(tensor.dcomplex_val[0], tensor.dcomplex_val[1]),
              dtype=dtype), num_elements).reshape(shape)
    else:
      return np.array(
          [complex(x[0], x[1]) for x in zip(it, it)],
          dtype=dtype).reshape(shape)
  elif tensor_dtype == dtypes.bool:
    if len(tensor.bool_val) == 1:
      return np.repeat(np.array(tensor.bool_val[0], dtype=dtype),
                       num_elements).reshape(shape)
    else:
      return np.fromiter(tensor.bool_val, dtype=dtype).reshape(shape)
  else:
    raise TypeError("Unsupported tensor type: %s" % tensor.dtype)

def ShapeEquals(tensor_proto, shape):
  """Returns True if "tensor_proto" has the given "shape".

  Args:
    tensor_proto: A TensorProto.
    shape: A tensor shape, expressed as a TensorShape, list, or tuple.

  Returns:
    True if "tensor_proto" has the given "shape", otherwise False.

  Raises:
    TypeError: If "tensor_proto" is not a TensorProto, or shape is not a
      TensorShape, list, or tuple.
  """
  if not isinstance(tensor_proto, tensor_pb2.TensorProto):
    raise TypeError("tensor_proto is not a tensor_pb2.TensorProto object")
  if isinstance(shape, tensor_shape_pb2.TensorShapeProto):
    shape = [d.size for d in shape.dim]
  elif not isinstance(shape, (list, tuple)):
    raise TypeError("shape is not a list or tuple")
  tensor_shape_list = [d.size for d in tensor_proto.tensor_shape.dim]
  return all(x == y for x, y in zip(tensor_shape_list, shape))

def _ConstantValue(tensor, partial):
  # TODO(touts): Support Variables?
  if not isinstance(tensor, ops.Tensor):
    raise TypeError("tensor is not a Tensor")
  if tensor.op.type == "Const":
    return MakeNdarray(tensor.op.get_attr("value"))
  elif tensor.op.type == "Shape":
    input_shape = tensor.op.inputs[0].get_shape()
    if input_shape.is_fully_defined():
      return np.array(
          [dim.value for dim in input_shape.dims],
          dtype=tensor.dtype.as_numpy_dtype)
    else:
      return None
  elif tensor.op.type == "Size":
    input_shape = tensor.op.inputs[0].get_shape()
    if input_shape.is_fully_defined():
      return np.prod([dim.value for dim in input_shape.dims], dtype=np.int32)
    else:
      return None
  elif tensor.op.type == "Rank":
    input_shape = tensor.op.inputs[0].get_shape()
    if input_shape.ndims is not None:
      return np.ndarray(
          shape=(),
          buffer=np.array([input_shape.ndims], dtype=np.int32),
          dtype=np.int32)
    else:
      return None
  elif tensor.op.type == "Range":
    start = constant_value(tensor.op.inputs[0])
    if start is None:
      return None
    limit = constant_value(tensor.op.inputs[1])
    if limit is None:
      return None
    delta = constant_value(tensor.op.inputs[2])
    if delta is None:
      return None
    return np.arange(start, limit, delta, dtype=tensor.dtype.as_numpy_dtype)
  elif tensor.op.type == "Cast":
    pre_cast = constant_value(tensor.op.inputs[0])
    if pre_cast is None:
      return None
    cast_dtype = dtypes.as_dtype(tensor.op.get_attr("DstT"))
    return pre_cast.astype(cast_dtype.as_numpy_dtype)
  elif tensor.op.type == "Concat":
    dim = constant_value(tensor.op.inputs[0])
    if dim is None:
      return None
    values = []
    for x in tensor.op.inputs[1:]:
      value = constant_value(x)
      if value is None:
        return None
      values.append(value)
    return np.concatenate(values, axis=dim)
  elif tensor.op.type == "ConcatV2":
    dim = constant_value(tensor.op.inputs[-1])
    if dim is None:
      return None
    values = []
    for x in tensor.op.inputs[:-1]:
      value = constant_value(x)
      if value is None:
        return None
      values.append(value)
    return np.concatenate(values, axis=dim)
  elif tensor.op.type == "Pack":
    values = []
    # Some imported GraphDefs have Pack ops with zero inputs. Those are invalid
    # and shouldn't be produced, but to deal sensibly with them here we check
    # and return None.
    if not tensor.op.inputs:
      return None
    # We can't handle axis != 0 Packs at the moment.
    if tensor.op.get_attr("axis") != 0:
      return None
    for x in tensor.op.inputs:
      value = constant_value(x, partial)
      if value is None and not partial:
        return None
      values.append(value)
    return np.array(values)
  elif tensor.op.type == "Fill":
    fill_shape = tensor.shape
    fill_value = constant_value(tensor.op.inputs[1])
    if fill_shape.is_fully_defined() and fill_value is not None:
      return np.full(fill_shape.as_list(), fill_value, dtype=fill_value.dtype)
    else:
      return None
  elif tensor.op.type == "Equal":
    value1 = constant_value(tensor.op.inputs[0])
    if value1 is None:
      return None
    value2 = constant_value(tensor.op.inputs[1])
    if value2 is None:
      return None
    return np.equal(value1, value2)
  elif tensor.op.type == "NotEqual":
    value1 = constant_value(tensor.op.inputs[0])
    if value1 is None:
      return None
    value2 = constant_value(tensor.op.inputs[1])
    if value2 is None:
      return None
    return np.not_equal(value1, value2)
  else:
    return None

def constant_value(tensor, partial=False):  # pylint: disable=invalid-name
  """Returns the constant value of the given tensor, if efficiently calculable.

  This function attempts to partially evaluate the given tensor, and
  returns its value as a numpy ndarray if this succeeds.

  TODO(mrry): Consider whether this function should use a registration
  mechanism like gradients and ShapeFunctions, so that it is easily
  extensible.

  NOTE: If `constant_value(tensor)` returns a non-`None` result, it will no
  longer be possible to feed a different value for `tensor`. This allows the
  result of this function to influence the graph that is constructed, and
  permits static shape optimizations.

  Args:
    tensor: The Tensor to be evaluated.
    partial: If True, the returned numpy array is allowed to have partially
      evaluated values. Values that can't be evaluated will be None.

  Returns:
    A numpy ndarray containing the constant value of the given `tensor`,
    or None if it cannot be calculated.

  Raises:
    TypeError: if tensor is not an ops.Tensor.
  """
  if isinstance(tensor, ops.EagerTensor):
    return tensor.numpy()
  ret = _ConstantValue(tensor, partial)
  if ret is not None:
    # The caller may now depend on the constant value of `tensor`, so we
    # conservatively prevent it from being fed.
    tensor.graph.prevent_feeding(tensor)
  return ret

def constant_value_as_shape(tensor):  # pylint: disable=invalid-name
  """A version of `constant_value()` that returns a `TensorShape`.

  This version should be used when a constant tensor value is
  interpreted as a (possibly partial) shape, e.g. in the shape
  function for `tf.reshape()`. By explicitly requesting a
  `TensorShape` as the return value, it is possible to represent
  unknown dimensions; by contrast, `constant_value()` is
  all-or-nothing.

  Args:
    tensor: The rank-0 or rank-1 Tensor to be evaluated.

  Returns:
    A `TensorShape` based on the constant value of the given `tensor`.

  Raises:
    ValueError: If the shape is rank-0 and is not statically known to be -1.
  """
  if isinstance(tensor, ops.EagerTensor):
    return tensor_shape.as_shape(
        [dim if dim != -1 else None for dim in tensor.numpy()])

  if tensor.get_shape().ndims == 0:
    value = constant_value(tensor)
    if value is None:
      raise ValueError(
          "Received a scalar with unknown value as shape; require a statically "
          "known scalar with value '-1' to describe an unknown shape.")
    if value != -1:
      raise ValueError(
          "Received a scalar value '%s' as shape; require a statically known "
          "scalar with value '-1' to describe an unknown shape." % value)
    return tensor_shape.unknown_shape()

  shape = tensor.get_shape().with_rank(1)
  if shape == [0]:
    return tensor_shape.scalar()
  elif tensor.op.type == "Shape":
    return tensor.op.inputs[0].get_shape()
  elif tensor.op.type == "Pack":
    ret = tensor_shape.scalar()  # Empty list.
    # Since we expect rank 1 inputs, Pack's axis must be zero, otherwise it
    # would not be rank 1.
    assert tensor.op.get_attr("axis") == 0
    for pack_input in tensor.op.inputs:
      # `pack_input` must be a scalar. Attempt to evaluate it, and append it
      # to `ret`.
      pack_input_val = constant_value(pack_input)
      if pack_input_val is None or pack_input_val < 0:
        new_dim = tensor_shape.Dimension(None)
      else:
        new_dim = tensor_shape.Dimension(pack_input_val)
      ret = ret.concatenate([new_dim])
    return ret
  elif tensor.op.type == "Concat":
    # We assume that `tensor.op.inputs[0]` evaluates to 0, as this is
    # the only legal value when concatenating vectors, and it will
    # have been checked by a previous shape function.
    ret = tensor_shape.scalar()  # Empty list.
    for concat_input in tensor.op.inputs[1:]:
      # `concat_input` must be a vector. Attempt to evaluate it as a shape,
      # and concatenate it with `ret`.
      ret = ret.concatenate(constant_value_as_shape(concat_input))
    return ret
  elif tensor.op.type == "ConcatV2":
    # We assume that `tensor.op.inputs[-1]` evaluates to 0, as this is
    # the only legal value when concatenating vectors, and it will
    # have been checked by a previous shape function.
    ret = tensor_shape.scalar()  # Empty list.
    for concat_input in tensor.op.inputs[:-1]:
      # `concat_input` must be a vector. Attempt to evaluate it as a shape,
      # and concatenate it with `ret`.
      ret = ret.concatenate(constant_value_as_shape(concat_input))
    return ret
  elif tensor.op.type == "StridedSlice":
    try:
      begin = constant_value(tensor.op.inputs[1])
      end = constant_value(tensor.op.inputs[2])
      strides = constant_value(tensor.op.inputs[3])
      if begin is not None and end is not None and strides is not None:
        begin = begin[0]
        end = end[0]
        strides = strides[0]
        begin_mask = tensor.op.get_attr("begin_mask")
        if begin_mask == 1:
          begin = None
        end_mask = tensor.op.get_attr("end_mask")
        if end_mask == 1:
          end = None

        ellipsis_mask = tensor.op.get_attr("ellipsis_mask")
        new_axis_mask = tensor.op.get_attr("new_axis_mask")
        shrink_axis_mask = tensor.op.get_attr("shrink_axis_mask")
        valid_attributes = (not ellipsis_mask and not new_axis_mask and
                            not shrink_axis_mask and (not begin_mask or
                                                      (begin_mask == 1)) and
                            (not end_mask or (end_mask == 1)))
        if valid_attributes:  # additional inputs not supported
          prev = constant_value_as_shape(tensor.op.inputs[0])
          prev = prev[begin:end:strides]
          ret = tensor_shape.TensorShape(prev)
          return ret

    except ValueError:  # Could come from get_attr or slicing prev.
      pass
    except TypeError:  # Could come from slicing prev.
      pass

  ret = tensor_shape.unknown_shape(shape[0].value)
  value = constant_value(tensor)
  if value is not None:
    ret = ret.merge_with(
        tensor_shape.TensorShape([d if d >= 0 else None for d in value]))
  return ret

def is_tensor(x):  # pylint: disable=invalid-name
  """Check whether `x` is of tensor type.

  Check whether an object is a tensor. Equivalent to
  `isinstance(x, [tf.Tensor, tf.SparseTensor, tf.Variable])`.

  Args:
    x: A python object to check.

  Returns:
    `True` if `x` is a tensor, `False` if not.
  """
  return isinstance(x, ops._TensorLike) or ops.is_dense_tensor_like(x)  # pylint: disable=protected-access

{'repo_name': 'ryfeus/lambda-packs', 'stars': '940', 'repo_language': 'Python', 'file_name': 'six.py', 'mime_type': 'text/x-python', 'hash': 9030195903954967099, 'source_dataset': 'data'}


function! lsc#search#workspaceSymbol(...) abort
  if a:0 >= 1
    let l:query = a:1
  else
    let l:query = input('Search Workspace For: ')
  endif
  call lsc#server#userCall('workspace/symbol', {'query': l:query},
      \ function('<SID>setQuickFixSymbols'))
endfunction

function! s:setQuickFixSymbols(results) abort
  if type(a:results) != type([]) || len(a:results) == 0
    call lsc#message#show('No symbols found')
    return
  endif

  call map(a:results, {_, symbol -> lsc#convert#quickFixSymbol(symbol)})
  call sort(a:results, 'lsc#util#compareQuickFixItems')
  call setqflist(a:results)
  copen
endfunction

{'repo_name': 'natebosch/vim-lsc', 'stars': '453', 'repo_language': 'Vim script', 'file_name': 'lsc.vim', 'mime_type': 'text/plain', 'hash': -3255732688049615903, 'source_dataset': 'data'}


// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
// Copyright (c) 2016 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

/**
 * \file boost/process/spawn.hpp
 *
 * Defines the spawn function.
 */

#ifndef BOOST_PROCESS_SPAWN_HPP
#define BOOST_PROCESS_SPAWN_HPP

#include <boost/process/detail/config.hpp>
#include <boost/process/detail/child_decl.hpp>
#include <boost/process/detail/execute_impl.hpp>
#include <boost/process/detail/async_handler.hpp>

#if defined(BOOST_POSIX_API)
#include <boost/process/posix.hpp>
#endif

namespace boost {

namespace process {

namespace detail {

}

/** Launch a process and detach it. Returns no handle.

This function starts a process and immediately detaches it. It thereby prevents the system from creating a zombie process,
but will also cause the system to be unable to wait for the child to exit.

\note This will set `SIGCHLD` to `SIGIGN` on posix.

\warning This function does not allow asynchronous operations, since it cannot wait for the end of the process.
It will fail to compile if a reference to `boost::asio::io_context` is passed.

 */
template<typename ...Args>
inline void spawn(Args && ...args)
{
    typedef typename ::boost::process::detail::has_async_handler<Args...>::type
            has_async;

    static_assert(
            !has_async::value,
            "Spawn cannot wait for exit, so async properties cannot be used");

    auto c = ::boost::process::detail::execute_impl(
#if defined(BOOST_POSIX_API)
            ::boost::process::posix::sig.ign(),
#endif
             std::forward<Args>(args)...);
    c.detach();
}

}}
#endif

{'repo_name': 'GoyaPtyLtd/BaseElements-Plugin', 'stars': '125', 'repo_language': 'C++', 'file_name': 'libturbojpeg.a', 'mime_type': 'text/plain', 'hash': 7893057731902611577, 'source_dataset': 'data'}


#Want to skip this test from daily Valgrind execution
--source include/no_valgrind_without_big.inc
################################################################################
# t/partition_float_myisam.test                                                #
#                                                                              #
# Purpose:                                                                     #
#  Tests around float type                                                     #
#        MyISAM branch                                                         #
#                                                                              #
#------------------------------------------------------------------------------#
# Original Author: HH                                                          #
# Original Date: 2006-08-01                                                    #
# Change Author:                                                               #
# Change Date:                                                                 #
# Change:                                                                      #
################################################################################

#
# NOTE: PLEASE DO NOT ADD NOT MYISAM SPECIFIC TESTCASES HERE !
#       TESTCASES WHICH MUST BE APPLIED TO ALL STORAGE ENGINES MUST BE ADDED IN
#       THE SOURCED FILES ONLY.
#
# Please read the README at the end of inc/partition.pre before changing
# any of the variables.
#

#------------------------------------------------------------------------------#
# General not engine specific settings and requirements

##### Options, for debugging support #####
let $debug= 0;

# The server must support partitioning.
--source include/have_partition.inc

#------------------------------------------------------------------------------#
# Engine specific settings and requirements

##### Storage engine to be tested
let $engine= 'MYISAM';
##### Number of row to be inserted.
let $maxrows=16384;

#------------------------------------------------------------------------------#
# Execute the tests to be applied to all storage engines
--source suite/parts/inc/partition_float.inc
--source suite/parts/inc/partition_double.inc

{'repo_name': 'alibaba/AliSQLBackup', 'stars': '102', 'repo_language': 'C++', 'file_name': 'ndb_rpl_binlog_format_errors.test', 'mime_type': 'text/plain', 'hash': 3348482700658479454, 'source_dataset': 'data'}