text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
 * Copyright 2014 Cisco Systems, Inc.
 *
 * 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.
 -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <parent>
    <groupId>com.cisco.oss.foundation.directory</groupId>
    <artifactId>sd-common-pom</artifactId>
    <version>1.0.5</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <artifactId>sd-api</artifactId>
  <name>Service Directory API</name>
  <version>1.2.1-6-SNAPSHOT</version>
  <description>Project for Cisco OSS service directory API library.</description>
  <url>https://github.com/foundation-runtime/service-directory/1.1/sd-api</url>
  <packaging>jar</packaging>
  <licenses>
    <license>
      <name>The Apache Software License, Version 2.0</name>
      <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      <distribution>repo</distribution>
    </license>
  </licenses>
  <issueManagement>
    <system>Github
        </system>
    <url>{URL in JIRA or Product name in CQ}</url>
  </issueManagement>
  <mailingLists>
    <mailingList />
  </mailingLists>
  <developers>
    <developer>
      <id>Alex Wu</id>
      <name>Yiding Wu</name>
      <email>yidwu@cisco.com</email>
      <organization>Cisco</organization>
      <organizationUrl>http://www.cisco.com</organizationUrl>
      <roles>
        <role>Developer</role>
      </roles>
    </developer>
    <developer>
      <id>Xuan Zhong</id>
      <name>Xuan Zhong</name>
      <email>xuzhong@cisco.com</email>
      <organization>Cisco</organization>
      <organizationUrl>http://www.cisco.com</organizationUrl>
      <roles>
        <role>Developer</role>
      </roles>
    </developer>
  </developers>
  <scm>
    <connection>scm:git:git@github.com:foundation-runtime/service-directory.git</connection>
    <developerConnection>scm:git:git@github.com:foundation-runtime/service-directory.git</developerConnection>
    <url>https://github.com/foundation-runtime/service-directory.git</url>
    <tag>HEAD</tag>
  </scm>
  <organization>
    <name>Cisco</name>
    <url>http://www.cisco.com</url>
  </organization>

  <properties>
    <timestamp>${maven.build.timestamp}</timestamp>
    <maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
    <org.jboss.resteasy.version>3.0.14.Final</org.jboss.resteasy.version>
    <org.mockito.version>1.10.19</org.mockito.version>
    <sd.module.dir>/opt/jboss-as/modules/system/layers/base/com/cisco/oss/foundation/directory/main</sd.module.dir>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <build>
    <finalName>cisco.sd.api-${project.version}</finalName>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>version.txt</include>
        </includes>
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>

    <plugins>

      <plugin>
        <artifactId>maven-javadoc-plugin</artifactId>
        <executions>
          <execution>
            <id>attach-doc</id>
            <goals>
              <goal>jar</goal>
            </goals>
            <phase>package</phase>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <artifactId>exec-maven-plugin</artifactId>
        <groupId>org.codehaus.mojo</groupId>
        <version>1.4.0</version>
        <executions>
          <execution>
            <id>Generate SD Jboss Module</id>
            <phase>package</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>${basedir}/scripts/generateModule.sh</executable>
              <arguments>
                <argument>${project.build.directory}</argument>
              </arguments>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <executions>
          <execution>
            <id>reserve-network-port</id>
            <goals>
              <goal>reserve-network-port</goal>
            </goals>
            <phase>process-resources</phase>
            <configuration>
              <portNames>
                <portName>jetty.http.port1</portName>
                <portName>jetty.http.port2</portName>
                <portName>jetty.http.port3</portName>
                <portName>zk.client.port1</portName>
                <portName>zk.client.port2</portName>
                <portName>zk.client.port3</portName>
                <portName>zk.sync.port1</portName>
                <portName>zk.sync.port2</portName>
                <portName>zk.sync.port3</portName>
                <portName>zk.sync.port4</portName>
                <portName>zk.sync.port5</portName>
                <portName>zk.sync.port6</portName>
              </portNames>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <systemProperties>
            <property>
              <name>SD_HTTP_PORT1</name>
              <value>${jetty.http.port1}</value>
            </property>
            <property>
              <name>SD_HTTP_PORT2</name>
              <value>${jetty.http.port2}</value>
            </property>
            <property>
              <name>SD_HTTP_PORT3</name>
              <value>${jetty.http.port3}</value>
            </property>
            <property>
              <name>SD_CLIENT_PORT1</name>
              <value>${zk.client.port1}</value>
            </property>
            <property>
              <name>SD_CLIENT_PORT2</name>
              <value>${zk.client.port2}</value>
            </property>
            <property>
              <name>SD_CLIENT_PORT3</name>
              <value>${zk.client.port3}</value>
            </property>
            <property>
              <name>SD_ZK_PORT1</name>
              <value>${zk.sync.port1}</value>
            </property>
            <property>
              <name>SD_ZK_PORT2</name>
              <value>${zk.sync.port2}</value>
            </property>
            <property>
              <name>SD_ZK_PORT3</name>
              <value>${zk.sync.port3}</value>
            </property>
            <property>
              <name>SD_ZK_PORT4</name>
              <value>${zk.sync.port4}</value>
            </property>
            <property>
              <name>SD_ZK_PORT5</name>
              <value>${zk.sync.port5}</value>
            </property>
            <property>
              <name>SD_ZK_PORT6</name>
              <value>${zk.sync.port6}</value>
            </property>
          </systemProperties>
        </configuration>
      </plugin>

      <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>prepare-package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/lib</outputDirectory>
              <overWriteReleases>false</overWriteReleases>
              <overWriteSnapshots>false</overWriteSnapshots>
              <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <id>make-assembly</id> <!-- this is used for inheritance merges -->
            <phase>package</phase> <!-- bind to the packaging phase -->
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <appendAssemblyId>false</appendAssemblyId> <!-- not append id to the result name-->
          <descriptors>
            <descriptor>src/assembly/assembly.xml</descriptor>
          </descriptors>
        </configuration>
      </plugin>

      <plugin>
        <artifactId>maven-site-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>rpm-maven-plugin</artifactId>
        <version>2.1.3</version>
        <executions>
          <execution>
            <id>generate-rpm</id>
            <goals>
              <goal>attached-rpm</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <copyright>2015, Cisco</copyright>
          <group>Application/System</group>
          <packager>Cisco Systems, Inc</packager>
          <name>${project.artifactId}</name>
          <version>${project.version}</version>
          <targetOS>linux</targetOS>
          <needarch>noarch</needarch>

          <defineStatements>
            <!-- Do not run /usr/lib/rpm/redhat/brp-java-repack-jars -->
            <defineStatement><![CDATA[__os_install_post %{nil}]]></defineStatement>
            <defineStatement>_unpackaged_files_terminate_build 0</defineStatement>
            <defineStatement>_tmppath /tmp</defineStatement>
          </defineStatements>

          <mappings>
            <mapping>
              <directory>${sd.module.dir}</directory>
              <filemode>644</filemode>
              <username>jboss</username>
              <groupname>jboss</groupname>
              <sources>
                <source>
                  <location>${project.build.directory}/modules</location>
                </source>
              </sources>
            </mapping>
          </mappings>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <reporting>
    <plugins>
      <plugin>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <version>2.8</version>
        <configuration>
          <dependencyLocationsEnabled>false</dependencyLocationsEnabled>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.10.3</version>
      </plugin>
      <plugin>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.18.1</version>
      </plugin>
    </plugins>
  </reporting>

  <dependencies>
    <dependency>
      <groupId>com.cisco.oss.foundation.directory</groupId>
      <artifactId>sd-core</artifactId>
      <version>1.2.1-1</version>
    </dependency>
   <dependency>
     <groupId>org.jboss.resteasy</groupId>
     <artifactId>resteasy-client</artifactId>
     <version>${org.jboss.resteasy.version}</version>
   </dependency>
   <dependency>
     <groupId>org.mockito</groupId>
     <artifactId>mockito-core</artifactId>
     <version>${org.mockito.version}</version>
     <scope>test</scope>
   </dependency>

  </dependencies>
</project>


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32H7xx_HAL_RNG_H
#define STM32H7xx_HAL_RNG_H

#ifdef __cplusplus
extern "C" {
#endif

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

/** @addtogroup STM32H7xx_HAL_Driver
  * @{
  */

#if defined (RNG)

/** @defgroup RNG RNG
  * @brief RNG HAL module driver
  * @{
  */

/* Exported types ------------------------------------------------------------*/

/** @defgroup RNG_Exported_Types RNG Exported Types
  * @{
  */

/** @defgroup RNG_Exported_Types_Group1 RNG Init Structure definition
  * @{
  */
typedef struct
{
  uint32_t                    ClockErrorDetection; /*!< CED Clock error detection */
} RNG_InitTypeDef;

/**
  * @}
  */

/** @defgroup RNG_Exported_Types_Group2 RNG State Structure definition
  * @{
  */
typedef enum
{
  HAL_RNG_STATE_RESET     = 0x00U,  /*!< RNG not yet initialized or disabled */
  HAL_RNG_STATE_READY     = 0x01U,  /*!< RNG initialized and ready for use   */
  HAL_RNG_STATE_BUSY      = 0x02U,  /*!< RNG internal process is ongoing     */
  HAL_RNG_STATE_TIMEOUT   = 0x03U,  /*!< RNG timeout state                   */
  HAL_RNG_STATE_ERROR     = 0x04U   /*!< RNG error state                     */

} HAL_RNG_StateTypeDef;

/**
  * @}
  */

/** @defgroup RNG_Exported_Types_Group3 RNG Handle Structure definition
  * @{
  */
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
typedef struct  __RNG_HandleTypeDef
#else
typedef struct
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */
{
  RNG_TypeDef                 *Instance;    /*!< Register base address   */

  RNG_InitTypeDef             Init;         /*!< RNG configuration parameters */

  HAL_LockTypeDef             Lock;         /*!< RNG locking object      */

  __IO HAL_RNG_StateTypeDef   State;        /*!< RNG communication state */

  __IO  uint32_t              ErrorCode;    /*!< RNG Error code          */

  uint32_t                    RandomNumber; /*!< Last Generated RNG Data */

#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
  void (* ReadyDataCallback)(struct __RNG_HandleTypeDef *hrng, uint32_t random32bit);  /*!< RNG Data Ready Callback    */
  void (* ErrorCallback)(struct __RNG_HandleTypeDef *hrng);                            /*!< RNG Error Callback         */

  void (* MspInitCallback)(struct __RNG_HandleTypeDef *hrng);                          /*!< RNG Msp Init callback      */
  void (* MspDeInitCallback)(struct __RNG_HandleTypeDef *hrng);                        /*!< RNG Msp DeInit callback    */
#endif  /* USE_HAL_RNG_REGISTER_CALLBACKS */

} RNG_HandleTypeDef;

#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
/**
  * @brief  HAL RNG Callback ID enumeration definition
  */
typedef enum
{
  HAL_RNG_ERROR_CB_ID                   = 0x00U,     /*!< RNG Error Callback ID          */

  HAL_RNG_MSPINIT_CB_ID                 = 0x01U,     /*!< RNG MspInit callback ID        */
  HAL_RNG_MSPDEINIT_CB_ID               = 0x02U      /*!< RNG MspDeInit callback ID      */

} HAL_RNG_CallbackIDTypeDef;

/**
  * @brief  HAL RNG Callback pointer definition
  */
typedef  void (*pRNG_CallbackTypeDef)(RNG_HandleTypeDef *hrng);                                  /*!< pointer to a common RNG callback function */
typedef  void (*pRNG_ReadyDataCallbackTypeDef)(RNG_HandleTypeDef *hrng, uint32_t random32bit);   /*!< pointer to an RNG Data Ready specific callback function */

#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */

/**
  * @}
  */

/**
  * @}
  */

/* Exported constants --------------------------------------------------------*/
/** @defgroup RNG_Exported_Constants RNG Exported Constants
  * @{
  */

/** @defgroup RNG_Exported_Constants_Group1 RNG Interrupt definition
  * @{
  */
#define RNG_IT_DRDY  RNG_SR_DRDY  /*!< Data Ready interrupt  */
#define RNG_IT_CEI   RNG_SR_CEIS  /*!< Clock error interrupt */
#define RNG_IT_SEI   RNG_SR_SEIS  /*!< Seed error interrupt  */
/**
  * @}
  */

/** @defgroup RNG_Exported_Constants_Group2 RNG Flag definition
  * @{
  */
#define RNG_FLAG_DRDY   RNG_SR_DRDY  /*!< Data ready                 */
#define RNG_FLAG_CECS   RNG_SR_CECS  /*!< Clock error current status */
#define RNG_FLAG_SECS   RNG_SR_SECS  /*!< Seed error current status  */
/**
  * @}
  */

/** @defgroup RNG_Exported_Constants_Group3 RNG Clock Error Detection
  * @{
  */
#define RNG_CED_ENABLE          0x00000000U /*!< Clock error detection Enabled  */
#define RNG_CED_DISABLE         RNG_CR_CED  /*!< Clock error detection Disabled */
/**
  * @}
  */

/** @defgroup RNG_Error_Definition   RNG Error Definition
  * @{
  */
#define  HAL_RNG_ERROR_NONE             0x00000000U    /*!< No error          */
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
#define  HAL_RNG_ERROR_INVALID_CALLBACK 0x00000001U    /*!< Invalid Callback error  */
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */
#define  HAL_RNG_ERROR_TIMEOUT          0x00000002U    /*!< Timeout error     */
#define  HAL_RNG_ERROR_BUSY             0x00000004U    /*!< Busy error        */
#define  HAL_RNG_ERROR_SEED             0x00000008U    /*!< Seed error        */
#define  HAL_RNG_ERROR_CLOCK            0x00000010U    /*!< Clock error       */
/**
  * @}
  */

/**
  * @}
  */

/* Exported macros -----------------------------------------------------------*/
/** @defgroup RNG_Exported_Macros RNG Exported Macros
  * @{
  */

/** @brief Reset RNG handle state
  * @param  __HANDLE__ RNG Handle
  * @retval None
  */
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
#define __HAL_RNG_RESET_HANDLE_STATE(__HANDLE__)  do{                                                   \
                                                       (__HANDLE__)->State = HAL_RNG_STATE_RESET;       \
                                                       (__HANDLE__)->MspInitCallback = NULL;            \
                                                       (__HANDLE__)->MspDeInitCallback = NULL;          \
                                                    } while(0U)
#else
#define __HAL_RNG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_RNG_STATE_RESET)
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */

/**
  * @brief  Enables the RNG peripheral.
  * @param  __HANDLE__ RNG Handle
  * @retval None
  */
#define __HAL_RNG_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |=  RNG_CR_RNGEN)

/**
  * @brief  Disables the RNG peripheral.
  * @param  __HANDLE__ RNG Handle
  * @retval None
  */
#define __HAL_RNG_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~RNG_CR_RNGEN)

/**
  * @brief  Check the selected RNG flag status.
  * @param  __HANDLE__ RNG Handle
  * @param  __FLAG__ RNG flag
  *          This parameter can be one of the following values:
  *            @arg RNG_FLAG_DRDY:  Data ready
  *            @arg RNG_FLAG_CECS:  Clock error current status
  *            @arg RNG_FLAG_SECS:  Seed error current status
  * @retval The new state of __FLAG__ (SET or RESET).
  */
#define __HAL_RNG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__))

/**
  * @brief  Clears the selected RNG flag status.
  * @param  __HANDLE__ RNG handle
  * @param  __FLAG__ RNG flag to clear
  * @note   WARNING: This is a dummy macro for HAL code alignment,
  *         flags RNG_FLAG_DRDY, RNG_FLAG_CECS and RNG_FLAG_SECS are read-only.
  * @retval None
  */
#define __HAL_RNG_CLEAR_FLAG(__HANDLE__, __FLAG__)                      /* dummy  macro */

/**
  * @brief  Enables the RNG interrupts.
  * @param  __HANDLE__ RNG Handle
  * @retval None
  */
#define __HAL_RNG_ENABLE_IT(__HANDLE__) ((__HANDLE__)->Instance->CR |=  RNG_CR_IE)

/**
  * @brief  Disables the RNG interrupts.
  * @param  __HANDLE__ RNG Handle
  * @retval None
  */
#define __HAL_RNG_DISABLE_IT(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~RNG_CR_IE)

/**
  * @brief  Checks whether the specified RNG interrupt has occurred or not.
  * @param  __HANDLE__ RNG Handle
  * @param  __INTERRUPT__ specifies the RNG interrupt status flag to check.
  *         This parameter can be one of the following values:
  *            @arg RNG_IT_DRDY: Data ready interrupt
  *            @arg RNG_IT_CEI: Clock error interrupt
  *            @arg RNG_IT_SEI: Seed error interrupt
  * @retval The new state of __INTERRUPT__ (SET or RESET).
  */
#define __HAL_RNG_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->SR & (__INTERRUPT__)) == (__INTERRUPT__))

/**
  * @brief  Clear the RNG interrupt status flags.
  * @param  __HANDLE__ RNG Handle
  * @param  __INTERRUPT__ specifies the RNG interrupt status flag to clear.
  *          This parameter can be one of the following values:
  *            @arg RNG_IT_CEI: Clock error interrupt
  *            @arg RNG_IT_SEI: Seed error interrupt
  * @note   RNG_IT_DRDY flag is read-only, reading RNG_DR register automatically clears RNG_IT_DRDY.
  * @retval None
  */
#define __HAL_RNG_CLEAR_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->SR) = ~(__INTERRUPT__))

/**
  * @}
  */

#if defined (RNG_CR_CONDRST)
/* Include RNG HAL Extended module */
#include "stm32h7xx_hal_rng_ex.h"
#endif  /* RNG_CR_CONDRST */
/* Exported functions --------------------------------------------------------*/
/** @defgroup RNG_Exported_Functions RNG Exported Functions
  * @{
  */

/** @defgroup RNG_Exported_Functions_Group1 Initialization and configuration functions
  * @{
  */
HAL_StatusTypeDef HAL_RNG_Init(RNG_HandleTypeDef *hrng);
HAL_StatusTypeDef HAL_RNG_DeInit(RNG_HandleTypeDef *hrng);
void HAL_RNG_MspInit(RNG_HandleTypeDef *hrng);
void HAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng);

/* Callbacks Register/UnRegister functions  ***********************************/
#if (USE_HAL_RNG_REGISTER_CALLBACKS == 1)
HAL_StatusTypeDef HAL_RNG_RegisterCallback(RNG_HandleTypeDef *hrng, HAL_RNG_CallbackIDTypeDef CallbackID,
                                           pRNG_CallbackTypeDef pCallback);
HAL_StatusTypeDef HAL_RNG_UnRegisterCallback(RNG_HandleTypeDef *hrng, HAL_RNG_CallbackIDTypeDef CallbackID);

HAL_StatusTypeDef HAL_RNG_RegisterReadyDataCallback(RNG_HandleTypeDef *hrng, pRNG_ReadyDataCallbackTypeDef pCallback);
HAL_StatusTypeDef HAL_RNG_UnRegisterReadyDataCallback(RNG_HandleTypeDef *hrng);
#endif /* USE_HAL_RNG_REGISTER_CALLBACKS */

/**
  * @}
  */

/** @defgroup RNG_Exported_Functions_Group2 Peripheral Control functions
  * @{
  */
HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber(RNG_HandleTypeDef *hrng, uint32_t *random32bit);
HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber_IT(RNG_HandleTypeDef *hrng);
uint32_t HAL_RNG_ReadLastRandomNumber(RNG_HandleTypeDef *hrng);

void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng);
void HAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng);
void HAL_RNG_ReadyDataCallback(RNG_HandleTypeDef *hrng, uint32_t random32bit);

/**
  * @}
  */

/** @defgroup RNG_Exported_Functions_Group3 Peripheral State functions
  * @{
  */
HAL_RNG_StateTypeDef HAL_RNG_GetState(RNG_HandleTypeDef *hrng);
uint32_t             HAL_RNG_GetError(RNG_HandleTypeDef *hrng);
/**
  * @}
  */

/**
  * @}
  */

/* Private macros ------------------------------------------------------------*/
/** @defgroup RNG_Private_Macros RNG Private Macros
  * @{
  */
#define IS_RNG_IT(IT) (((IT) == RNG_IT_CEI) || \
                       ((IT) == RNG_IT_SEI))

#define IS_RNG_FLAG(FLAG) (((FLAG) == RNG_FLAG_DRDY) || \
                           ((FLAG) == RNG_FLAG_CECS) || \
                           ((FLAG) == RNG_FLAG_SECS))

/**
  * @brief Verify the RNG Clock Error Detection mode.
  * @param __MODE__ RNG Clock Error Detection mode
  * @retval SET (__MODE__ is valid) or RESET (__MODE__ is invalid)
  */
#define IS_RNG_CED(__MODE__)   (((__MODE__) == RNG_CED_ENABLE) || \
                                ((__MODE__) == RNG_CED_DISABLE))
/**
  * @}
  */

#if defined(RNG_CR_CONDRST)
/* Private functions ---------------------------------------------------------*/
/** @defgroup RNG_Private_Functions RNG Private functions
  * @{
  */
HAL_StatusTypeDef RNG_RecoverSeedError(RNG_HandleTypeDef *hrng);
/**
  * @}
  */
#endif /* RNG_CR_CONDRST */
/**
  * @}
  */

#endif /* RNG */

/**
  * @}
  */

#ifdef __cplusplus
}
#endif

#endif /* STM32H7xx_HAL_RNG_H */

redpajama_set_name: RedPajamaGithub


text:
@interface SwitchTableViewCell()

@end

@implementation SwitchTableViewCell

-(instancetype)init
{
	self = [super init];
	if(self)
	{
		self.backgroundColor = [UIColor whiteColor];

		self.leftLabel = [UILabel new];
		self.leftLabel.translatesAutoresizingMaskIntoConstraints = NO;
		self.leftLabel.font = [UIFont piwigoFontNormal];
		self.leftLabel.textColor = [UIColor piwigoGray];
		self.leftLabel.textAlignment = NSTextAlignmentLeft;
		self.leftLabel.adjustsFontSizeToFitWidth = YES;
		self.leftLabel.minimumScaleFactor = 0.5;
		self.leftLabel.numberOfLines = 2;
		self.leftLabel.preferredMaxLayoutWidth = 150;
		[self.contentView addSubview:self.leftLabel];

		self.cellSwitch = [UISwitch new];
		self.cellSwitch.translatesAutoresizingMaskIntoConstraints = NO;
		[self.contentView addSubview:self.cellSwitch];
		[self.cellSwitch addTarget:self action:@selector(switchChanged) forControlEvents:UIControlEventValueChanged];

		[self setupConstraints];
	}
	return self;
}

-(void)setupConstraints
{
	NSDictionary *views = @{
							@"label" : self.leftLabel,
							@"switch" : self.cellSwitch
							};

	[self.contentView addConstraint:[NSLayoutConstraint constraintCenterHorizontalView:self.leftLabel]];
	[self.contentView addConstraint:[NSLayoutConstraint constraintCenterHorizontalView:self.cellSwitch]];

	[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-15-[label][switch]-15-|"
																			 options:kNilOptions
																			 metrics:nil
																			   views:views]];
}

-(void)switchChanged
{
	if(self.cellSwitchBlock)
	{
		self.cellSwitchBlock(self.cellSwitch.isOn);
	}
}

@end


text:
<?php

namespace BackupMe\MainBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * ApiClient
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="BackupMe\MainBundle\Entity\ApiClientRepository")
 * @UniqueEntity(fields="name", message="Ce nom existe déjà.")
 * @UniqueEntity(fields="iPAddress", message="Cette adresse IP est déjà déclaré.")
 */
class ApiClient
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, unique=true)
     * @Assert\NotBlank(message="Ce champ ne peut être vide.")
     * @Assert\Type(type="string", message="La valeur {{ value }} n'est pas un type {{ type }} valide.")
     * @Assert\Length(
     *      min = "3",
     *      max = "255",
     *      minMessage = "Le nom FQDN doit faire au moins {{ limit }} caractères",
     *      maxMessage = "Le nom FQDN ne peut pas être plus long que {{ limit }} caractères"
     * )
     * @Assert\Regex(
     *     pattern = "/(?=^.{1,254}$)(^(((?!-)[a-zA-Z0-9-]{1,63}(?<!-))|((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63})$)/",
     *     match = true,
     *     message = "Le nom FQDN n'est pas valide"
     * )
     */
    private $name;

    /**
     * @var string
     *
     * @ORM\Column(name="IPAdress", type="string", length=255, unique=true)
     * @Assert\NotBlank(message="Ce champ ne peut être vide.")
     * @Assert\Ip(
     *      version = "all",
     *      message = "La valeur {{ value }} n'est pas une adresse IPv4 ou IPv6 valide"
     * )
     */
    private $iPAddress;

    /**
     * @var string
     *
     * @ORM\Column(name="type", type="string", length=255)
     * @Assert\NotBlank(message="Ce champ ne peut être vide.")
     * @Assert\Choice(
     *      choices = {"internal", "external"},
     *      message = "La valeur {{ value }} n'est pas un ApiClientType valide.")
     */
    private $type;

    /**
     * @var boolean
     *
     * @ORM\Column(name="IsActive", type="boolean")
     * @Assert\Type(type="bool", message="La valeur {{ value }} n'est pas un type {{ type }} valide.")
     */
    private $isActive;

    /**
    * @ORM\ManyToMany(targetEntity="BackupMe\MainBundle\Entity\Contact", inversedBy="ApiClients", cascade={"persist"})
    */
    private $contacts;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->isActive = true;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set isActive
     *
     * @param boolean $isActive
     * @return ApiClient
     */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;

        return $this;
    }

    /**
     * Get isActive
     *
     * @return boolean
     */
    public function getIsActive()
    {
        return $this->isActive;
    }

    /**
     * Set type
     *
     * @param string $type
     * @return ApiClient
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return ApiClient
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set iPAddress
     *
     * @param string $iPAddress
     * @return ApiClient
     */
    public function setIPAddress($iPAddress)
    {
        $this->iPAddress = $iPAddress;

        return $this;
    }

    /**
     * Get iPAddress
     *
     * @return string
     */
    public function getIPAddress()
    {
        return $this->iPAddress;
    }

    /**
     * Add contacts
     *
     * @param \BackupMe\MainBundle\Entity\Contact $contacts
     * @return ApiClient
     */
    public function addContact(\BackupMe\MainBundle\Entity\Contact $contacts)
    {
        $this->contacts[] = $contacts;

        return $this;
    }

    /**
     * Remove contacts
     *
     * @param \BackupMe\MainBundle\Entity\Contact $contacts
     */
    public function removeContact(\BackupMe\MainBundle\Entity\Contact $contacts)
    {
        $this->contacts->removeElement($contacts);
    }

    /**
     * Get contacts
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getContacts()
    {
        return $this->contacts;
    }
}


text:
import pytest

from neo4j._exceptions import (
    BoltConnectionBroken,
    BoltConnectionClosed,
    BoltConnectionError,
    BoltError,
    BoltFailure,
    BoltHandshakeError,
    BoltProtocolError,
    BoltSecurityError,
)
from neo4j._sync.io import Bolt
from neo4j.exceptions import (
    AuthConfigurationError,
    AuthError,
    CertificateConfigurationError,
    CLASSIFICATION_CLIENT,
    CLASSIFICATION_DATABASE,
    CLASSIFICATION_TRANSIENT,
    ClientError,
    ConfigurationError,
    ConstraintError,
    CypherSyntaxError,
    CypherTypeError,
    DatabaseError,
    DatabaseUnavailable,
    DriverError,
    Forbidden,
    ForbiddenOnReadOnlyDatabase,
    IncompleteCommit,
    Neo4jError,
    NotALeader,
    ReadServiceUnavailable,
    ResultConsumedError,
    RoutingServiceUnavailable,
    ServiceUnavailable,
    SessionExpired,
    TransactionError,
    TransactionNestingError,
    TransientError,
    WriteServiceUnavailable,
)

def test_bolt_error():
    with pytest.raises(BoltError) as e:
        error = BoltError("Error Message", address="localhost")
        assert repr(error) == "BoltError('Error Message')"
        assert str(error) == "Error Message"
        assert error.args == ("Error Message",)
        assert error.address == "localhost"
        raise error

    # The regexp parameter of the match method is matched with the re.search function.
    with pytest.raises(AssertionError):
        e.match("FAIL!")

    assert e.match("Error Message")

def test_bolt_protocol_error():
    with pytest.raises(BoltProtocolError) as e:
        error = BoltProtocolError("Driver does not support Bolt protocol version: 0x%06X%02X" % (2, 5), address="localhost")
        assert error.address == "localhost"
        raise error

    # The regexp parameter of the match method is matched with the re.search function.
    with pytest.raises(AssertionError):
        e.match("FAIL!")

    e.match("Driver does not support Bolt protocol version: 0x00000205")

def test_bolt_handshake_error():
    handshake = b"\x00\x00\x00\x04\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00"
    response = b"\x00\x00\x00\x00"
    supported_versions = Bolt.protocol_handlers().keys()

    with pytest.raises(BoltHandshakeError) as e:
        error = BoltHandshakeError("The Neo4J server does not support communication with this driver. Supported Bolt Protocols {}".format(supported_versions), address="localhost", request_data=handshake, response_data=response)
        assert error.address == "localhost"
        assert error.request_data == handshake
        assert error.response_data == response
        raise error

    e.match("The Neo4J server does not support communication with this driver. Supported Bolt Protocols ")

def test_serviceunavailable():
    with pytest.raises(ServiceUnavailable) as e:
        error = ServiceUnavailable("Test error message")
        raise error

    assert e.value.__cause__ is None

def test_serviceunavailable_raised_from_bolt_protocol_error_with_implicit_style():
    error = BoltProtocolError("Driver does not support Bolt protocol version: 0x%06X%02X" % (2, 5), address="localhost")
    with pytest.raises(ServiceUnavailable) as e:
        assert error.address == "localhost"
        try:
            raise error
        except BoltProtocolError as error_bolt_protocol:
            raise ServiceUnavailable(str(error_bolt_protocol)) from error_bolt_protocol

    # The regexp parameter of the match method is matched with the re.search function.
    with pytest.raises(AssertionError):
        e.match("FAIL!")

    e.match("Driver does not support Bolt protocol version: 0x00000205")
    assert e.value.__cause__ is error

def test_serviceunavailable_raised_from_bolt_protocol_error_with_explicit_style():
    error = BoltProtocolError("Driver does not support Bolt protocol version: 0x%06X%02X" % (2, 5), address="localhost")

    with pytest.raises(ServiceUnavailable) as e:
        assert error.address == "localhost"
        try:
            raise error
        except BoltProtocolError as error_bolt_protocol:
            error_nested = ServiceUnavailable(str(error_bolt_protocol))
            error_nested.__cause__ = error_bolt_protocol
            raise error_nested

    # The regexp parameter of the match method is matched with the re.search function.
    with pytest.raises(AssertionError):
        e.match("FAIL!")

    e.match("Driver does not support Bolt protocol version: 0x00000205")
    assert e.value.__cause__ is error

def test_neo4jerror_hydrate_with_no_args():
    error = Neo4jError.hydrate()

    assert isinstance(error, DatabaseError)
    assert error.classification == CLASSIFICATION_DATABASE
    assert error.category == "General"
    assert error.title == "UnknownError"
    assert error.metadata == {}
    assert error.message == "An unknown error occurred"
    assert error.code == "Neo.DatabaseError.General.UnknownError"

def test_neo4jerror_hydrate_with_message_and_code_rubish():
    error = Neo4jError.hydrate(message="Test error message", code="ASDF_asdf")

    assert isinstance(error, DatabaseError)
    assert error.classification == CLASSIFICATION_DATABASE
    assert error.category == "General"
    assert error.title == "UnknownError"
    assert error.metadata == {}
    assert error.message == "Test error message"
    assert error.code == "ASDF_asdf"

def test_neo4jerror_hydrate_with_message_and_code_database():
    error = Neo4jError.hydrate(message="Test error message", code="Neo.DatabaseError.General.UnknownError")

    assert isinstance(error, DatabaseError)
    assert error.classification == CLASSIFICATION_DATABASE
    assert error.category == "General"
    assert error.title == "UnknownError"
    assert error.metadata == {}
    assert error.message == "Test error message"
    assert error.code == "Neo.DatabaseError.General.UnknownError"

def test_neo4jerror_hydrate_with_message_and_code_transient():
    error = Neo4jError.hydrate(message="Test error message", code="Neo.TransientError.General.TestError")
    # error = Neo4jError.hydrate(message="Test error message", code="Neo.{}.General.TestError".format(CLASSIFICATION_TRANSIENT))

    assert isinstance(error, TransientError)
    assert error.classification == CLASSIFICATION_TRANSIENT
    assert error.category == "General"
    assert error.title == "TestError"
    assert error.metadata == {}
    assert error.message == "Test error message"
    assert error.code == "Neo.{}.General.TestError".format(CLASSIFICATION_TRANSIENT)

def test_neo4jerror_hydrate_with_message_and_code_client():
    error = Neo4jError.hydrate(message="Test error message", code="Neo.{}.General.TestError".format(CLASSIFICATION_CLIENT))

    assert isinstance(error, ClientError)
    assert error.classification == CLASSIFICATION_CLIENT
    assert error.category == "General"
    assert error.title == "TestError"
    assert error.metadata == {}
    assert error.message == "Test error message"
    assert error.code == "Neo.{}.General.TestError".format(CLASSIFICATION_CLIENT)

@pytest.mark.parametrize(
    ("code", "expected_cls", "expected_code"),
    (
        (
            "Neo.TransientError.Transaction.Terminated",
            ClientError,
            "Neo.ClientError.Transaction.Terminated"
        ),
        (
            "Neo.ClientError.Transaction.Terminated",
            ClientError,
            "Neo.ClientError.Transaction.Terminated"
        ),
        (
            "Neo.TransientError.Transaction.LockClientStopped",
            ClientError,
            "Neo.ClientError.Transaction.LockClientStopped"
        ),
        (
            "Neo.ClientError.Transaction.LockClientStopped",
            ClientError,
            "Neo.ClientError.Transaction.LockClientStopped"
        ),
        (
            "Neo.ClientError.Security.AuthorizationExpired",
            TransientError,
            "Neo.ClientError.Security.AuthorizationExpired"
        ),
        (
            "Neo.TransientError.General.TestError",
            TransientError,
            "Neo.TransientError.General.TestError"
        )
    )
)
def test_error_rewrite(code, expected_cls, expected_code):
    message = "Test error message"
    error = Neo4jError.hydrate(message=message, code=code)

    expected_retryable = expected_cls is TransientError
    assert error.__class__ is expected_cls
    assert error.code == expected_code
    assert error.message == message
    assert error.is_retryable() is expected_retryable
    with pytest.warns(DeprecationWarning, match=".*is_retryable.*"):
        assert error.is_retriable() is expected_retryable

@pytest.mark.parametrize(
    ("code", "message", "expected_cls", "expected_str"),
    (
        (
            "Neo.ClientError.General.UnknownError",
            "Test error message",
            ClientError,
            "{code: Neo.ClientError.General.UnknownError} "
            "{message: Test error message}"
        ),
        (
            None,
            "Test error message",
            DatabaseError,
            "{code: Neo.DatabaseError.General.UnknownError} "
            "{message: Test error message}"
        ),
        (
            "",
            "Test error message",
            DatabaseError,
            "{code: Neo.DatabaseError.General.UnknownError} "
            "{message: Test error message}"
        ),
        (
            "Neo.ClientError.General.UnknownError",
            None,
            ClientError,
            "{code: Neo.ClientError.General.UnknownError} "
            "{message: An unknown error occurred}"
        ),
        (
            "Neo.ClientError.General.UnknownError",
            "",
            ClientError,
            "{code: Neo.ClientError.General.UnknownError} "
            "{message: An unknown error occurred}"
        ),
    )
)
def test_neo4j_error_from_server_as_str(code, message, expected_cls,
                                        expected_str):
    error = Neo4jError.hydrate(code=code, message=message)

    assert type(error) == expected_cls
    assert str(error) == expected_str

@pytest.mark.parametrize("cls", (Neo4jError, ClientError))
def test_neo4j_error_from_code_as_str(cls):
    error = cls("Generated somewhere in the driver")

    assert type(error)== cls
    assert str(error) == "Generated somewhere in the driver"


text:
use chrono::{DateTime, Utc};
use url::Url;

/// Trait to define conversion to [`Url`]
pub trait TryIntoUrl {
    fn into_url(self) -> Result<Url, url::ParseError>;
}

impl TryIntoUrl for Url {
    fn into_url(self) -> Result<Url, url::ParseError> {
        Ok(self)
    }
}

impl TryIntoUrl for &str {
    fn into_url(self) -> Result<Url, url::ParseError> {
        Url::parse(self)
    }
}

impl TryIntoUrl for String {
    fn into_url(self) -> Result<Url, url::ParseError> {
        self.as_str().into_url()
    }
}

/// Trait to define conversion to [`DateTime`]
pub trait TryIntoTime {
    fn into_time(self) -> Result<DateTime<Utc>, chrono::ParseError>;
}

impl TryIntoTime for DateTime<Utc> {
    fn into_time(self) -> Result<DateTime<Utc>, chrono::ParseError> {
        Ok(self)
    }
}

impl TryIntoTime for &str {
    fn into_time(self) -> Result<DateTime<Utc>, chrono::ParseError> {
        Ok(DateTime::<Utc>::from(DateTime::parse_from_rfc3339(self)?))
    }
}

impl TryIntoTime for String {
    fn into_time(self) -> Result<DateTime<Utc>, chrono::ParseError> {
        self.as_str().into_time()
    }
}

/// The URI-reference type.
///
/// The URI reference can be a URI, or just a relative path.
///
/// As the [`url::Url`] type can only represent an absolute URL, we are falling back to a string
/// here.
///
/// Also see:
/// * <https://github.com/cloudevents/spec/blob/v1.0.1/spec.md#type-system>
/// * <https://tools.ietf.org/html/rfc3986#section-4.1>
pub type UriReference = String;


text:
.class public Lcom/android/server/content/SyncQueue;
.super Ljava/lang/Object;
.source "SyncQueue.java"

# static fields
.field private static final TAG:Ljava/lang/String; = "SyncManager"

# instance fields
.field private final mOperationsMap:Ljava/util/HashMap;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/HashMap",
            "<",
            "Ljava/lang/String;",
            "Lcom/android/server/content/SyncOperation;",
            ">;"
        }
    .end annotation
.end field

.field private final mPackageManager:Landroid/content/pm/PackageManager;

.field private final mSyncAdapters:Landroid/content/SyncAdaptersCache;

.field private final mSyncStorageEngine:Lcom/android/server/content/SyncStorageEngine;

# direct methods
.method public constructor <init>(Landroid/content/pm/PackageManager;Lcom/android/server/content/SyncStorageEngine;Landroid/content/SyncAdaptersCache;)V
    .registers 5
    .param p1    # Landroid/content/pm/PackageManager;
    .param p2    # Lcom/android/server/content/SyncStorageEngine;
    .param p3    # Landroid/content/SyncAdaptersCache;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    invoke-static {}, Lcom/google/android/collect/Maps;->newHashMap()Ljava/util/HashMap;

    move-result-object v0

    iput-object v0, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    iput-object p1, p0, Lcom/android/server/content/SyncQueue;->mPackageManager:Landroid/content/pm/PackageManager;

    iput-object p2, p0, Lcom/android/server/content/SyncQueue;->mSyncStorageEngine:Lcom/android/server/content/SyncStorageEngine;

    iput-object p3, p0, Lcom/android/server/content/SyncQueue;->mSyncAdapters:Landroid/content/SyncAdaptersCache;

    return-void
.end method

.method private add(Lcom/android/server/content/SyncOperation;Lcom/android/server/content/SyncStorageEngine$PendingOperation;)Z
    .registers 16
    .param p1    # Lcom/android/server/content/SyncOperation;
    .param p2    # Lcom/android/server/content/SyncStorageEngine$PendingOperation;

    iget-object v12, p1, Lcom/android/server/content/SyncOperation;->key:Ljava/lang/String;

    iget-object v0, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    invoke-virtual {v0, v12}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v9

    check-cast v9, Lcom/android/server/content/SyncOperation;

    if-eqz v9, :cond_27

    const/4 v8, 0x0

    invoke-virtual {p1, v9}, Lcom/android/server/content/SyncOperation;->compareTo(Ljava/lang/Object;)I

    move-result v0

    if-gtz v0, :cond_26

    iget-boolean v0, p1, Lcom/android/server/content/SyncOperation;->expedited:Z

    iput-boolean v0, v9, Lcom/android/server/content/SyncOperation;->expedited:Z

    iget-wide v0, v9, Lcom/android/server/content/SyncOperation;->latestRunTime:J

    iget-wide v2, p1, Lcom/android/server/content/SyncOperation;->latestRunTime:J

    invoke-static {v0, v1, v2, v3}, Ljava/lang/Math;->min(JJ)J

    move-result-wide v10

    iput-wide v10, v9, Lcom/android/server/content/SyncOperation;->latestRunTime:J

    iget-wide v0, p1, Lcom/android/server/content/SyncOperation;->flexTime:J

    iput-wide v0, v9, Lcom/android/server/content/SyncOperation;->flexTime:J

    const/4 v8, 0x1

    :cond_26
    :goto_26
    return v8

    :cond_27
    iput-object p2, p1, Lcom/android/server/content/SyncOperation;->pendingOperation:Lcom/android/server/content/SyncStorageEngine$PendingOperation;

    iget-object v0, p1, Lcom/android/server/content/SyncOperation;->pendingOperation:Lcom/android/server/content/SyncStorageEngine$PendingOperation;

    if-nez v0, :cond_64

    new-instance p2, Lcom/android/server/content/SyncStorageEngine$PendingOperation;

    iget-object v1, p1, Lcom/android/server/content/SyncOperation;->account:Landroid/accounts/Account;

    iget v2, p1, Lcom/android/server/content/SyncOperation;->userId:I

    iget v3, p1, Lcom/android/server/content/SyncOperation;->reason:I

    iget v4, p1, Lcom/android/server/content/SyncOperation;->syncSource:I

    iget-object v5, p1, Lcom/android/server/content/SyncOperation;->authority:Ljava/lang/String;

    iget-object v6, p1, Lcom/android/server/content/SyncOperation;->extras:Landroid/os/Bundle;

    iget-boolean v7, p1, Lcom/android/server/content/SyncOperation;->expedited:Z

    move-object v0, p2

    invoke-direct/range {v0 .. v7}, Lcom/android/server/content/SyncStorageEngine$PendingOperation;-><init>(Landroid/accounts/Account;IIILjava/lang/String;Landroid/os/Bundle;Z)V

    iget-object v0, p0, Lcom/android/server/content/SyncQueue;->mSyncStorageEngine:Lcom/android/server/content/SyncStorageEngine;

    invoke-virtual {v0, p2}, Lcom/android/server/content/SyncStorageEngine;->insertIntoPending(Lcom/android/server/content/SyncStorageEngine$PendingOperation;)Lcom/android/server/content/SyncStorageEngine$PendingOperation;

    move-result-object p2

    if-nez p2, :cond_62

    new-instance v0, Ljava/lang/IllegalStateException;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "error adding pending sync operation "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V

    throw v0

    :cond_62
    iput-object p2, p1, Lcom/android/server/content/SyncOperation;->pendingOperation:Lcom/android/server/content/SyncStorageEngine$PendingOperation;

    :cond_64
    iget-object v0, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    invoke-virtual {v0, v12, p1}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    const/4 v8, 0x1

    goto :goto_26
.end method

# virtual methods
.method public add(Lcom/android/server/content/SyncOperation;)Z
    .registers 3
    .param p1    # Lcom/android/server/content/SyncOperation;

    const/4 v0, 0x0

    invoke-direct {p0, p1, v0}, Lcom/android/server/content/SyncQueue;->add(Lcom/android/server/content/SyncOperation;Lcom/android/server/content/SyncStorageEngine$PendingOperation;)Z

    move-result v0

    return v0
.end method

.method public addPendingOperations(I)V
    .registers 27
    .param p1    # I

    move-object/from16 v0, p0

    iget-object v5, v0, Lcom/android/server/content/SyncQueue;->mSyncStorageEngine:Lcom/android/server/content/SyncStorageEngine;

    invoke-virtual {v5}, Lcom/android/server/content/SyncStorageEngine;->getPendingOperations()Ljava/util/ArrayList;

    move-result-object v5

    invoke-virtual {v5}, Ljava/util/ArrayList;->iterator()Ljava/util/Iterator;

    move-result-object v21

    :cond_c
    :goto_c
    invoke-interface/range {v21 .. v21}, Ljava/util/Iterator;->hasNext()Z

    move-result v5

    if-eqz v5, :cond_ee

    invoke-interface/range {v21 .. v21}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v22

    check-cast v22, Lcom/android/server/content/SyncStorageEngine$PendingOperation;

    move-object/from16 v0, v22

    iget v5, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->userId:I

    move/from16 v0, p1

    if-ne v5, v0, :cond_c

    move-object/from16 v0, p0

    iget-object v5, v0, Lcom/android/server/content/SyncQueue;->mSyncStorageEngine:Lcom/android/server/content/SyncStorageEngine;

    move-object/from16 v0, v22

    iget-object v6, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->account:Landroid/accounts/Account;

    move-object/from16 v0, v22

    iget v7, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->userId:I

    move-object/from16 v0, v22

    iget-object v8, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->authority:Ljava/lang/String;

    invoke-virtual {v5, v6, v7, v8}, Lcom/android/server/content/SyncStorageEngine;->getBackoff(Landroid/accounts/Account;ILjava/lang/String;)Landroid/util/Pair;

    move-result-object v20

    move-object/from16 v0, p0

    iget-object v5, v0, Lcom/android/server/content/SyncQueue;->mSyncAdapters:Landroid/content/SyncAdaptersCache;

    move-object/from16 v0, v22

    iget-object v6, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->authority:Ljava/lang/String;

    move-object/from16 v0, v22

    iget-object v7, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->account:Landroid/accounts/Account;

    iget-object v7, v7, Landroid/accounts/Account;->type:Ljava/lang/String;

    invoke-static {v6, v7}, Landroid/content/SyncAdapterType;->newKey(Ljava/lang/String;Ljava/lang/String;)Landroid/content/SyncAdapterType;

    move-result-object v6

    move-object/from16 v0, v22

    iget v7, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->userId:I

    invoke-virtual {v5, v6, v7}, Landroid/content/SyncAdaptersCache;->getServiceInfo(Ljava/lang/Object;I)Landroid/content/pm/RegisteredServicesCache$ServiceInfo;

    move-result-object v23

    if-nez v23, :cond_7b

    const-string v5, "SyncManager"

    new-instance v6, Ljava/lang/StringBuilder;

    invoke-direct {v6}, Ljava/lang/StringBuilder;-><init>()V

    const-string v7, "Missing sync adapter info for authority "

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    move-object/from16 v0, v22

    iget-object v7, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->authority:Ljava/lang/String;

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    const-string v7, ", userId "

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v6

    move-object/from16 v0, v22

    iget v7, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->userId:I

    invoke-virtual {v6, v7}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v6

    invoke-virtual {v6}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v6

    invoke-static {v5, v6}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/String;)I

    goto :goto_c

    :cond_7b
    new-instance v4, Lcom/android/server/content/SyncOperation;

    move-object/from16 v0, v22

    iget-object v5, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->account:Landroid/accounts/Account;

    move-object/from16 v0, v22

    iget v6, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->userId:I

    move-object/from16 v0, v22

    iget v7, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->reason:I

    move-object/from16 v0, v22

    iget v8, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->syncSource:I

    move-object/from16 v0, v22

    iget-object v9, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->authority:Ljava/lang/String;

    move-object/from16 v0, v22

    iget-object v10, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->extras:Landroid/os/Bundle;

    const-wide/16 v11, 0x0

    const-wide/16 v13, 0x0

    if-eqz v20, :cond_eb

    move-object/from16 v0, v20

    iget-object v15, v0, Landroid/util/Pair;->first:Ljava/lang/Object;

    check-cast v15, Ljava/lang/Long;

    invoke-virtual {v15}, Ljava/lang/Long;->longValue()J

    move-result-wide v15

    :goto_a5
    move-object/from16 v0, p0

    iget-object v0, v0, Lcom/android/server/content/SyncQueue;->mSyncStorageEngine:Lcom/android/server/content/SyncStorageEngine;

    move-object/from16 v17, v0

    move-object/from16 v0, v22

    iget-object v0, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->account:Landroid/accounts/Account;

    move-object/from16 v18, v0

    move-object/from16 v0, v22

    iget v0, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->userId:I

    move/from16 v19, v0

    move-object/from16 v0, v22

    iget-object v0, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->authority:Ljava/lang/String;

    move-object/from16 v24, v0

    move-object/from16 v0, v17

    move-object/from16 v1, v18

    move/from16 v2, v19

    move-object/from16 v3, v24

    invoke-virtual {v0, v1, v2, v3}, Lcom/android/server/content/SyncStorageEngine;->getDelayUntilTime(Landroid/accounts/Account;ILjava/lang/String;)J

    move-result-wide v17

    move-object/from16 v0, v23

    iget-object v0, v0, Landroid/content/pm/RegisteredServicesCache$ServiceInfo;->type:Ljava/lang/Object;

    move-object/from16 v19, v0

    check-cast v19, Landroid/content/SyncAdapterType;

    invoke-virtual/range {v19 .. v19}, Landroid/content/SyncAdapterType;->allowParallelSyncs()Z

    move-result v19

    invoke-direct/range {v4 .. v19}, Lcom/android/server/content/SyncOperation;-><init>(Landroid/accounts/Account;IIILjava/lang/String;Landroid/os/Bundle;JJJJZ)V

    move-object/from16 v0, v22

    iget-boolean v5, v0, Lcom/android/server/content/SyncStorageEngine$PendingOperation;->expedited:Z

    iput-boolean v5, v4, Lcom/android/server/content/SyncOperation;->expedited:Z

    move-object/from16 v0, v22

    iput-object v0, v4, Lcom/android/server/content/SyncOperation;->pendingOperation:Lcom/android/server/content/SyncStorageEngine$PendingOperation;

    move-object/from16 v0, p0

    move-object/from16 v1, v22

    invoke-direct {v0, v4, v1}, Lcom/android/server/content/SyncQueue;->add(Lcom/android/server/content/SyncOperation;Lcom/android/server/content/SyncStorageEngine$PendingOperation;)Z

    goto/16 :goto_c

    :cond_eb
    const-wide/16 v15, 0x0

    goto :goto_a5

    :cond_ee
    return-void
.end method

.method public dump(Ljava/lang/StringBuilder;)V
    .registers 10
    .param p1    # Ljava/lang/StringBuilder;

    invoke-static {}, Landroid/os/SystemClock;->elapsedRealtime()J

    move-result-wide v1

    const-string v4, "SyncQueue: "

    invoke-virtual {p1, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget-object v5, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    invoke-virtual {v5}, Ljava/util/HashMap;->size()I

    move-result v5

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, " operation(s)\n"

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    iget-object v4, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    invoke-virtual {v4}, Ljava/util/HashMap;->values()Ljava/util/Collection;

    move-result-object v4

    invoke-interface {v4}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v0

    :goto_23
    invoke-interface {v0}, Ljava/util/Iterator;->hasNext()Z

    move-result v4

    if-eqz v4, :cond_63

    invoke-interface {v0}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v3

    check-cast v3, Lcom/android/server/content/SyncOperation;

    const-string v4, "  "

    invoke-virtual {p1, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    iget-wide v4, v3, Lcom/android/server/content/SyncOperation;->effectiveRunTime:J

    cmp-long v4, v4, v1

    if-gtz v4, :cond_55

    const-string v4, "READY"

    invoke-virtual {p1, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    :goto_3f
    const-string v4, " - "

    invoke-virtual {p1, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    iget-object v4, p0, Lcom/android/server/content/SyncQueue;->mPackageManager:Landroid/content/pm/PackageManager;

    const/4 v5, 0x0

    invoke-virtual {v3, v4, v5}, Lcom/android/server/content/SyncOperation;->dump(Landroid/content/pm/PackageManager;Z)Ljava/lang/String;

    move-result-object v4

    invoke-virtual {p1, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, "\n"

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    goto :goto_23

    :cond_55
    iget-wide v4, v3, Lcom/android/server/content/SyncOperation;->effectiveRunTime:J

    sub-long/2addr v4, v1

    const-wide/16 v6, 0x3e8

    div-long/2addr v4, v6

    invoke-static {v4, v5}, Landroid/text/format/DateUtils;->formatElapsedTime(J)Ljava/lang/String;

    move-result-object v4

    invoke-virtual {p1, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    goto :goto_3f

    :cond_63
    return-void
.end method

.method public getOperations()Ljava/util/Collection;
    .registers 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/Collection",
            "<",
            "Lcom/android/server/content/SyncOperation;",
            ">;"
        }
    .end annotation

    iget-object v0, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    invoke-virtual {v0}, Ljava/util/HashMap;->values()Ljava/util/Collection;

    move-result-object v0

    return-object v0
.end method

.method public onBackoffChanged(Landroid/accounts/Account;ILjava/lang/String;J)V
    .registers 9
    .param p1    # Landroid/accounts/Account;
    .param p2    # I
    .param p3    # Ljava/lang/String;
    .param p4    # J

    iget-object v2, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    invoke-virtual {v2}, Ljava/util/HashMap;->values()Ljava/util/Collection;

    move-result-object v2

    invoke-interface {v2}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v0

    :cond_a
    :goto_a
    invoke-interface {v0}, Ljava/util/Iterator;->hasNext()Z

    move-result v2

    if-eqz v2, :cond_34

    invoke-interface {v0}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/android/server/content/SyncOperation;

    iget-object v2, v1, Lcom/android/server/content/SyncOperation;->account:Landroid/accounts/Account;

    invoke-virtual {v2, p1}, Landroid/accounts/Account;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_a

    iget-object v2, v1, Lcom/android/server/content/SyncOperation;->authority:Ljava/lang/String;

    invoke-virtual {v2, p3}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_a

    iget v2, v1, Lcom/android/server/content/SyncOperation;->userId:I

    if-ne v2, p2, :cond_a

    invoke-static {p4, p5}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;

    move-result-object v2

    iput-object v2, v1, Lcom/android/server/content/SyncOperation;->backoff:Ljava/lang/Long;

    invoke-virtual {v1}, Lcom/android/server/content/SyncOperation;->updateEffectiveRunTime()V

    goto :goto_a

    :cond_34
    return-void
.end method

.method public onDelayUntilTimeChanged(Landroid/accounts/Account;Ljava/lang/String;J)V
    .registers 8
    .param p1    # Landroid/accounts/Account;
    .param p2    # Ljava/lang/String;
    .param p3    # J

    iget-object v2, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    invoke-virtual {v2}, Ljava/util/HashMap;->values()Ljava/util/Collection;

    move-result-object v2

    invoke-interface {v2}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v0

    :cond_a
    :goto_a
    invoke-interface {v0}, Ljava/util/Iterator;->hasNext()Z

    move-result v2

    if-eqz v2, :cond_2c

    invoke-interface {v0}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/android/server/content/SyncOperation;

    iget-object v2, v1, Lcom/android/server/content/SyncOperation;->account:Landroid/accounts/Account;

    invoke-virtual {v2, p1}, Landroid/accounts/Account;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_a

    iget-object v2, v1, Lcom/android/server/content/SyncOperation;->authority:Ljava/lang/String;

    invoke-virtual {v2, p2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_a

    iput-wide p3, v1, Lcom/android/server/content/SyncOperation;->delayUntil:J

    invoke-virtual {v1}, Lcom/android/server/content/SyncOperation;->updateEffectiveRunTime()V

    goto :goto_a

    :cond_2c
    return-void
.end method

.method public remove(Landroid/accounts/Account;ILjava/lang/String;)V
    .registers 10
    .param p1    # Landroid/accounts/Account;
    .param p2    # I
    .param p3    # Ljava/lang/String;

    iget-object v4, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    invoke-virtual {v4}, Ljava/util/HashMap;->entrySet()Ljava/util/Set;

    move-result-object v4

    invoke-interface {v4}, Ljava/util/Set;->iterator()Ljava/util/Iterator;

    move-result-object v0

    :cond_a
    :goto_a
    invoke-interface {v0}, Ljava/util/Iterator;->hasNext()Z

    move-result v4

    if-eqz v4, :cond_5f

    invoke-interface {v0}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Ljava/util/Map$Entry;

    invoke-interface {v1}, Ljava/util/Map$Entry;->getValue()Ljava/lang/Object;

    move-result-object v3

    check-cast v3, Lcom/android/server/content/SyncOperation;

    if-eqz p1, :cond_26

    iget-object v4, v3, Lcom/android/server/content/SyncOperation;->account:Landroid/accounts/Account;

    invoke-virtual {v4, p1}, Landroid/accounts/Account;->equals(Ljava/lang/Object;)Z

    move-result v4

    if-eqz v4, :cond_a

    :cond_26
    if-eqz p3, :cond_30

    iget-object v4, v3, Lcom/android/server/content/SyncOperation;->authority:Ljava/lang/String;

    invoke-virtual {v4, p3}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v4

    if-eqz v4, :cond_a

    :cond_30
    iget v4, v3, Lcom/android/server/content/SyncOperation;->userId:I

    if-ne p2, v4, :cond_a

    invoke-interface {v0}, Ljava/util/Iterator;->remove()V

    iget-object v4, p0, Lcom/android/server/content/SyncQueue;->mSyncStorageEngine:Lcom/android/server/content/SyncStorageEngine;

    iget-object v5, v3, Lcom/android/server/content/SyncOperation;->pendingOperation:Lcom/android/server/content/SyncStorageEngine$PendingOperation;

    invoke-virtual {v4, v5}, Lcom/android/server/content/SyncStorageEngine;->deleteFromPending(Lcom/android/server/content/SyncStorageEngine$PendingOperation;)Z

    move-result v4

    if-nez v4, :cond_a

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "unable to find pending row for "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v2

    const-string v4, "SyncManager"

    new-instance v5, Ljava/lang/IllegalStateException;

    invoke-direct {v5, v2}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V

    invoke-static {v4, v2, v5}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_a

    :cond_5f
    return-void
.end method

.method public remove(Lcom/android/server/content/SyncOperation;)V
    .registers 6
    .param p1    # Lcom/android/server/content/SyncOperation;

    iget-object v2, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    iget-object v3, p1, Lcom/android/server/content/SyncOperation;->key:Ljava/lang/String;

    invoke-virtual {v2, v3}, Ljava/util/HashMap;->remove(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/android/server/content/SyncOperation;

    if-nez v1, :cond_d

    :cond_c
    :goto_c
    return-void

    :cond_d
    iget-object v2, p0, Lcom/android/server/content/SyncQueue;->mSyncStorageEngine:Lcom/android/server/content/SyncStorageEngine;

    iget-object v3, v1, Lcom/android/server/content/SyncOperation;->pendingOperation:Lcom/android/server/content/SyncStorageEngine$PendingOperation;

    invoke-virtual {v2, v3}, Lcom/android/server/content/SyncStorageEngine;->deleteFromPending(Lcom/android/server/content/SyncStorageEngine$PendingOperation;)Z

    move-result v2

    if-nez v2, :cond_c

    new-instance v2, Ljava/lang/StringBuilder;

    invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

    const-string v3, "unable to find pending row for "

    invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    const-string v2, "SyncManager"

    new-instance v3, Ljava/lang/IllegalStateException;

    invoke-direct {v3, v0}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V

    invoke-static {v2, v0, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I

    goto :goto_c
.end method

.method public removeUser(I)V
    .registers 6
    .param p1    # I

    new-instance v2, Ljava/util/ArrayList;

    invoke-direct {v2}, Ljava/util/ArrayList;-><init>()V

    iget-object v3, p0, Lcom/android/server/content/SyncQueue;->mOperationsMap:Ljava/util/HashMap;

    invoke-virtual {v3}, Ljava/util/HashMap;->values()Ljava/util/Collection;

    move-result-object v3

    invoke-interface {v3}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v0

    :cond_f
    :goto_f
    invoke-interface {v0}, Ljava/util/Iterator;->hasNext()Z

    move-result v3

    if-eqz v3, :cond_23

    invoke-interface {v0}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/android/server/content/SyncOperation;

    iget v3, v1, Lcom/android/server/content/SyncOperation;->userId:I

    if-ne v3, p1, :cond_f

    invoke-virtual {v2, v1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z

    goto :goto_f

    :cond_23
    invoke-virtual {v2}, Ljava/util/ArrayList;->iterator()Ljava/util/Iterator;

    move-result-object v0

    :goto_27
    invoke-interface {v0}, Ljava/util/Iterator;->hasNext()Z

    move-result v3

    if-eqz v3, :cond_37

    invoke-interface {v0}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/android/server/content/SyncOperation;

    invoke-virtual {p0, v1}, Lcom/android/server/content/SyncQueue;->remove(Lcom/android/server/content/SyncOperation;)V

    goto :goto_27

    :cond_37
    return-void
.end method


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit
 *  ==========
 *  Copyright (C) 2015-2022 The Fluent Bit 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.
 */

#ifndef FLB_OUT_GELF_H
#define FLB_OUT_GELF_H

#define FLB_GELF_UDP 0
#define FLB_GELF_TCP 1
#define FLB_GELF_TLS 2

#include <fluent-bit/flb_output_plugin.h>

struct flb_out_gelf_config {

    struct flb_gelf_fields fields;

    /* Upstream connection to the backend server */
    struct flb_upstream *u;
    flb_sockfd_t fd;

    int pckt_size;
    char *pckt_buf;
    int compress;
    unsigned int seed;

    int mode;

    struct flb_output_instance *ins;
};

#endif


text:
class CreateMemberships < ActiveRecord::Migration
  def change
    create_table :memberships do |t|
      t.references :user, index: true
      t.references :group, index: true

      t.timestamps
    end
  end
end


text:
/*•	Write methods that calculate the surface of a triangle by given:
    o	Side and an altitude to it;
    o	Three sides;
    o	Two sides and an angle between them;
  •	Use System.Math.*/

using System;

class TriangleSurface
{
    static decimal SideAltitudeSurface(decimal a,decimal h)
    {
        return (a * h) / 2;
    }
    static decimal ThreeSidesSurface(decimal a,decimal b,decimal c)
    {
        decimal perimeter = (a + b + c) / 2;
        decimal result =(decimal) Math.Sqrt((double)(perimeter * (perimeter - a) * (perimeter - b) * (perimeter - c)));
        return result;
    }
    static decimal SideAndAngleSurface(decimal a,decimal b,decimal angle)
    {
        decimal result=a * b * (decimal)Math.Sin((double)angle)/ 2;
        return result;
    }
    static void Main()
    {
        Console.WriteLine("Please choose how you want to calculate the triangle surface:");
        Console.WriteLine(new string('-',60));
        Console.WriteLine("Press 1 to calculate the surface by side and altitude to it");
        Console.WriteLine("Press 2 to calculate the surface by three sides");
        Console.WriteLine("Press 3 to calculate the surface by two sides and an angle");
        Console.WriteLine(new string('-', 60));
        var pressedButton = Console.ReadKey();
        Console.Clear();
        switch (pressedButton.KeyChar)
        {
            case'1':
                Console.Write("Enter side: ");
                decimal side = decimal.Parse(Console.ReadLine());
                Console.Write("Enter altitude: ");
                decimal altitude = decimal.Parse(Console.ReadLine());

                if (side<0||altitude<0)
                {
                throw new ArgumentOutOfRangeException("side,altitude","must be positive");
                }
                else
                {
                decimal resultA = SideAltitudeSurface(side, altitude);
                Console.WriteLine("The surface of triangle with side {0} and altitude {1} is {2:F2}",side,altitude,resultA);
                }
                break;
            case'2':
                Console.Write("Enter first side: ");
                decimal first = decimal.Parse(Console.ReadLine());
                Console.Write("Enter second side: ");
                decimal second = decimal.Parse(Console.ReadLine());
                Console.Write("Enter third side: ");
                decimal third = decimal.Parse(Console.ReadLine());

                if (first < 0 || second < 0 || third < 0)
                {
                throw new ArgumentOutOfRangeException("sides", "must be positive");
                }
                else
                {
                decimal resultB = ThreeSidesSurface(first, second, third);
                Console.WriteLine("The surface of triangle with sides {0}, {1} and {2} is {3:F2}", first, second, third, resultB);
                }
                break;
            case'3':
                Console.Write("Enter first side: ");
                decimal firstSideSize = decimal.Parse(Console.ReadLine());
                Console.Write("Enter second side: ");
                decimal secondSideSize = decimal.Parse(Console.ReadLine());
                Console.Write("Enter angle: ");
                decimal angle = decimal.Parse(Console.ReadLine());

                if (firstSideSize<0||secondSideSize<0||angle<0)
                {
                throw new ArgumentOutOfRangeException("side,angle", "must be positive");
                }
                else
                {
                decimal resultC = SideAndAngleSurface(firstSideSize,secondSideSize, angle);
                Console.WriteLine("The surface of triangle with sides {0} and {1} and angle {2} is {3:F2}", firstSideSize,secondSideSize,angle, resultC);
                }
                break;
            default:
                Console.WriteLine("Invalid input.Press 1, 2 or 3!");
                break;
        }
    }
}


text:
namespace TraktApiSharp.Objects.Post.Users.HiddenItems
{
    using Get.Movies;

    public class TraktUserHiddenItemsPostMovie : ITraktUserHiddenItemsPostMovie
    {
        public string Title { get; set; }

        public int? Year { get; set; }

        public ITraktMovieIds Ids { get; set; }
    }
}


text:
module Azure::Reservations::Mgmt
    VERSION = '0.20.0'
end


text:
FROM php:7.4-apache

# Install additionnal PHP extensions
RUN apt-get update && apt-get install -y \
    && docker-php-ext-install pdo_mysql \
    && docker-php-ext-install pcntl

ENV APACHE_DOCUMENT_ROOT /project/web

RUN sed -ri -e 's!/var/www/html!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/sites-available/*.conf
RUN sed -ri -e 's!/var/www/!${APACHE_DOCUMENT_ROOT}!g' /etc/apache2/apache2.conf /etc/apache2/conf-available/*.conf

RUN echo "memory_limit = -1" >> "/usr/local/etc/php/conf.d/custom.ini"

WORKDIR /project


text:
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "impeller/archivist/archive_class_registration.h"

#include <sstream>

#include "impeller/archivist/archive_database.h"
#include "impeller/archivist/archive_statement.h"
#include "impeller/base/validation.h"

namespace impeller {

static constexpr const char* kArchivePrimaryKeyColumnName = "primary_key";

ArchiveClassRegistration::ArchiveClassRegistration(ArchiveDatabase& database,
                                                   ArchiveDef definition)
    : database_(database), definition_(std::move(definition)) {
  for (size_t i = 0; i < definition.members.size(); i++) {
    // The first index entry is the primary key. So add one to the index.
    column_map_[definition.members[i]] = i + 1;
  }
  is_valid_ = CreateTable();
}

const std::string& ArchiveClassRegistration::GetClassName() const {
  return definition_.table_name;
}

size_t ArchiveClassRegistration::GetMemberCount() const {
  return column_map_.size();
}

bool ArchiveClassRegistration::IsValid() const {
  return is_valid_;
}

std::optional<size_t> ArchiveClassRegistration::FindColumnIndex(
    const std::string& member) const {
  auto found = column_map_.find(member);
  if (found == column_map_.end()) {
    VALIDATION_LOG << "No member named '" << member << "' in class '"
                   << definition_.table_name
                   << "'. Did you forget to register it?";
    return std::nullopt;
  }
  return found->second;
}

bool ArchiveClassRegistration::CreateTable() {
  if (definition_.table_name.empty() || definition_.members.empty()) {
    return false;
  }

  std::stringstream stream;

  /*
   *  Table names cannot participate in parameter substitution, so we prepare
   *  a statement and check its validity before running.
   */
  stream << "CREATE TABLE IF NOT EXISTS " << definition_.table_name << " ("
         << kArchivePrimaryKeyColumnName << " INTEGER PRIMARY KEY, ";

  for (size_t i = 0, columns = definition_.members.size(); i < columns; i++) {
    stream << definition_.members[i];
    if (i != columns - 1) {
      stream << ", ";
    }
  }
  stream << ");";

  auto statement = database_.CreateStatement(stream.str());

  if (!statement.IsValid()) {
    return false;
  }

  if (!statement.Reset()) {
    return false;
  }

  return statement.Execute() == ArchiveStatement::Result::kDone;
}

ArchiveStatement ArchiveClassRegistration::CreateQueryStatement(
    bool single) const {
  std::stringstream stream;
  stream << "SELECT " << kArchivePrimaryKeyColumnName << ", ";
  for (size_t i = 0, columns = definition_.members.size(); i < columns; i++) {
    stream << definition_.members[i];
    if (i != columns - 1) {
      stream << ",";
    }
  }
  stream << " FROM " << definition_.table_name;

  if (single) {
    stream << " WHERE " << kArchivePrimaryKeyColumnName << " = ?";
  } else {
    stream << " ORDER BY  " << kArchivePrimaryKeyColumnName << " ASC";
  }

  stream << ";";

  return database_.CreateStatement(stream.str());
}

ArchiveStatement ArchiveClassRegistration::CreateInsertStatement() const {
  std::stringstream stream;
  stream << "INSERT OR REPLACE INTO " << definition_.table_name
         << " VALUES ( ?, ";
  for (size_t i = 0, columns = definition_.members.size(); i < columns; i++) {
    stream << "?";
    if (i != columns - 1) {
      stream << ", ";
    }
  }
  stream << ");";

  return database_.CreateStatement(stream.str());
}

}  // namespace impeller


text:
'use strict';

var util = require('util');
var assert = require('assert-plus');
var Transform = require('stream').Transform;

function ModelTransformStream(transformer) {
	assert.func(transformer, 'transformer');
	Transform.call(this, { objectMode: true});
	this.transformer = transformer;
}
util.inherits(ModelTransformStream, Transform);

Object.defineProperties(ModelTransformStream.prototype, {

	_transform: {
		value: function _transform(data, encoding, done) {
			var model = this.transformer(data);
			this.push(model, encoding);
			done();
		},
		enumerable: true,
		writable: true
	}

});

module.exports = ModelTransformStream;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class com.badlogic.gdx.graphics.g3d.model.MeshPart (libgdx API)</title>
<meta name="date" content="2013-11-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.badlogic.gdx.graphics.g3d.model.MeshPart

Packages that use MeshPart

Package
Description

com.badlogic.gdx.graphics.g3d

com.badlogic.gdx.graphics.g3d.model

com.badlogic.gdx.graphics.g3d.utils

Uses of MeshPart in com.badlogic.gdx.graphics.g3d

Fields in com.badlogic.gdx.graphics.g3d with type parameters of type MeshPart

Modifier and Type
Field and Description

Array<MeshPart>
Model.meshParts

parts of meshes, used by nodes that have a graphical representation FIXME not sure if superfluous, stored in Nodes as well, could be useful to create bullet meshes

Uses of MeshPart in com.badlogic.gdx.graphics.g3d.model

Fields in com.badlogic.gdx.graphics.g3d.model declared as MeshPart

Modifier and Type
Field and Description

MeshPart
NodePart.meshPart

Constructors in com.badlogic.gdx.graphics.g3d.model with parameters of type MeshPart

Constructor and Description

NodePart(MeshPart meshPart,
        Material material)

Uses of MeshPart in com.badlogic.gdx.graphics.g3d.utils

Methods in com.badlogic.gdx.graphics.g3d.utils that return MeshPart

Modifier and Type
Method and Description

MeshPart
MeshBuilder.getMeshPart()

MeshPart
MeshPartBuilder.getMeshPart()

MeshPart
MeshBuilder.part(java.lang.String id,
    int primitiveType)

Starts a new MeshPart.

MeshPart
ModelBuilder.part(java.lang.String id,
    Mesh mesh,
    int primitiveType,
    int offset,
    int size,
    Material material)

Adds the specified mesh part to the current node.

MeshPart
ModelBuilder.part(java.lang.String id,
    Mesh mesh,
    int primitiveType,
    Material material)

Adds the specified mesh part to the current node.

Methods in com.badlogic.gdx.graphics.g3d.utils with parameters of type MeshPart

Modifier and Type
Method and Description

void
ModelBuilder.part(MeshPart meshpart,
    Material material)

Adds the specified MeshPart to the current Node.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev

Next

Frames

No Frames

All Classes

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
<?php

declare(strict_types=1);

namespace phpDocumentor\Pipeline\Stage\Cache;

use phpDocumentor\Descriptor\Cache\ProjectDescriptorMapper;
use phpDocumentor\Pipeline\Stage\Parser\Payload;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

final class StoreProjectDescriptorToCache
{
    /** @var ProjectDescriptorMapper */
    private $descriptorMapper;

    /** @var LoggerInterface */
    private $logger;

    public function __construct(ProjectDescriptorMapper $descriptorMapper, LoggerInterface $logger)
    {
        $this->descriptorMapper = $descriptorMapper;
        $this->logger = $logger;
    }

    public function __invoke(Payload $payload) : Payload
    {
        $projectDescriptor = $payload->getBuilder()->getProjectDescriptor();
        $this->log('Storing cache .. ', LogLevel::NOTICE);
        $projectDescriptor->getSettings()->clearModifiedFlag();
        $this->descriptorMapper->save($projectDescriptor);
        $this->log('OK');

        return $payload;
    }

    /**
     * Dispatches a logging request.
     *
     * @param string $priority The logging priority as declared in the LogLevel PSR-3 class.
     * @param string[] $parameters
     */
    private function log(string $message, string $priority = LogLevel::INFO, array $parameters = []) : void
    {
        $this->logger->log($priority, $message, $parameters);
    }
}


text:
import tests.model_control.test_ozone_custom_models_enabled as testmod

testmod.build_model( ['Quantization'] , ['MovingMedian'] , ['Seasonal_Second'] , ['AR'] );


text:
Reports any calls to a variable arity method where the call has a primitive array in
the variable arity parameter position (e.g System.out.printf("%s", new int[]{1, 2, 3}) ).
Such a primitive-array argument may be confusing, as it will be wrapped as a single-element array, rather than each individual
element being boxed, as might be expected.


text:
package rounding

import (
	"math/big"
)

// RoundingMode describes how to round a given number.
// sign is the sign of the number (needed when n is zero)
// n is the integer that should be rounded such that the last digit is zero.
// l is the current last digit of n.
// r indicates whether the rest of the original number, after last digit, is non-zero
// NOTE: This method is only called when rounding is necessary, so if l == 0 it
// means there was more precision that was already truncated (so r is true).
// For most cases you shouldn't need to implement this yourself, use one of
// the provided implementations in the rounding package.
type RoundingMode func(sign int, n, l *big.Int, r bool)

func roundUp(sign int, n, l *big.Int, _ bool) {
	li := l.Int64()
	if sign >= 0 {
		n.Add(n, l.SetInt64(10-li))
	} else {
		n.Sub(n, l.SetInt64(10-li))
	}
}

func roundDown(sign int, n, l *big.Int, _ bool) {
	if sign > 0 {
		n.Sub(n, l)
	} else {
		n.Add(n, l)
	}
}

func roundCeil(sign int, n, l *big.Int, _ bool) {
	if sign > 0 {
		li := l.Int64()
		n.Add(n, l.SetInt64(10-li))
	} else {
		n.Add(n, l)
	}
}

func roundFloor(sign int, n, l *big.Int, _ bool) {
	if sign > 0 {
		n.Sub(n, l)
	} else {
		li := l.Int64()
		n.Sub(n, l.SetInt64(10-li))
	}
}

func roundHalfUp(sign int, n, l *big.Int, r bool) {
	if l.Int64() >= 5 {
		roundUp(sign, n, l, r)
	} else {
		roundDown(sign, n, l, r)
	}
}

func roundHalfDown(sign int, n, l *big.Int, r bool) {
	if l.Int64() > 5 {
		roundUp(sign, n, l, r)
	} else if l.Int64() <= 4 {
		roundDown(sign, n, l, r)
	} else {
		// l.Int64() == 5
		if r {
			roundUp(sign, n, l, r)
		} else {
			roundDown(sign, n, l, r)
		}
	}
}

func roundHalfEven(sign int, n, l *big.Int, r bool) {
	li := l.Int64()
	if li == 5 {
		if !r {
			k := new(big.Int).Rem(n, big100)
			ki := k.Int64() / 10
			if ki%2 == 0 {
				roundDown(sign, n, l, r)
			} else {
				roundUp(sign, n, l, r)
			}
		} else {
			roundUp(sign, n, l, r)
		}
	} else if li > 5 {
		roundUp(sign, n, l, r)
	} else {
		roundDown(sign, n, l, r)
	}
}

var (
	// Up rounds away from zero.
	Up RoundingMode = roundUp

	// Down rounds towards zero.
	Down RoundingMode = roundDown

	// Ceil rounds towards positive infinity.
	Ceil RoundingMode = roundCeil

	// Floor rounds towards negative infinity.
	Floor RoundingMode = roundFloor

	// HalfUp rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
	HalfUp RoundingMode = roundHalfUp

	// HalfDown rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
	HalfDown RoundingMode = roundHalfDown

	// HalfEven rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor.
	HalfEven RoundingMode = roundHalfEven
)

// Round sets x to its value rounded to the given precision using the given rounding mode.
// Returns x, which was modified in place.
func Round(x *big.Rat, prec int, method RoundingMode) *big.Rat {
	sign := x.Sign()
	orig := new(big.Rat).Set(x)
	trunc(x, prec+1)
	n, d := x.Num(), x.Denom()
	l := new(big.Int).Rem(n, big10)
	l.Abs(l)

	r := x.Cmp(orig) != 0
	// Only run the rounding method if just truncating won't suffice
	if l.Sign() != 0 || r {
		method(sign, n, l, r)
	}

	// To force renormalization
	return x.SetFrac(n, d)
}


text:
layout: post
title: Why the Underscores in init?
---

You have probably seen this before:

```objc

- (instancetype) init
{
  self = [super init];
  if (self)
  {
    _friends = [[NSArray alloc] init];
  }
  return self;
}
```

The little underscores in front of variables. If you pay closer attention you will notice that they only occur in two possible places. Either in accessor methods or in the `init` method. The underscore is a convention that means this variable is an [instance variable](http://blog.ablepear.com/2010/04/objective-c-tuesdays-instance-variables.html). Accessing the instance variable in an accessor makes sense...that's kind of their job. Accessing them from `init` makes a lot less sense. As up standing object oriented programmers we know that you should only access instance variables through accessor methods specifically made for that purpose. In Objective-C this means we generally access the instance variables using the `@property` directive with code like `self.firstName`. Lets take a dive into why we use instance variables in our `init` methods.

# Because Apple Said So

> The only places you shouldn't use accessor methods to set an instance variable are in initializer methods and dealloc.

[Apple said](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html) so is a really great reason to do things. While I'm not advocating blindly following someone for any reason, Apple generally knows what they are doing when it comes to iOS. Either way, just following what someone says isn't good enough for me. I wanted to go deeper.

# Nobody Expects The Subclass's Setter

The main reason we use instance variables instead of the actual setter is because of subclassing. Here is an example of things going poorly by using setters instead of directly accessing the instance variable. If we think of a class called `Animal` with a property called `noise` we would initialize this class like this:

```objc
- (instancetype) init
{
  self = [super init];
  if (self)
  {
    self.noise = @"rawr";
  }
  return self;
}
```

This will probably work without any odd side-effects or anything going wrong. That is until we subclass our `Animal` class with `Dog`. Let's say in `Dog` we modify the setter to do a bit more work then just setting the variable. Let's make the `Dog` class's noise setter to grab it's name and include that in the noise it makes. Something like this:

```objc
- (void) setNoise: (NSString *)noise
{
  NSString *dogNoise = [NSString stringWithFormat:@"%@ %@ %@", noise, self.name, noise]; // for fido outputs "noise fido noise"
  [super setNoise:dogNoise];
}
```

Now let's write the `init` method for our `Dog` class.

```objc
- (instancetype) init
{
  self = [super init];
  if (self)
  {
    self.name = @"Fido";
  }
  return self;
}
```

Now in our code let's do `Dog *fido = [[Dog alloc] init];`. If we take a look at what the `noise` property is of `fido` is we see it's `@"rawr (null) rawr"`. That's unexpected! This can be a bit hard to understand what happened but let's follow the chain of methods that we created. First things first we call the `init` instance method on the Dog class. We are then encountered with this line of code: `self = [super init]`. This kicks us up to the `init` instance method in the `Animal` class which calls the `noise` setter on `self`. The question is...what is `self` in this case? `Self` is an instance of the `Dog` class! So that brings us to the setter created in the `Dog` class. The setter in the `Dog` class grabs the `name` property...which hasn't been set yet. That's how you get the `nil` in for the name.

## Semi-Completed Self

So the first issue here is you are never sure when a class you write will get subclassed. We need to be aware of those possible issues like the one above. To do this we just never use `self` until `self` is completely finished being created. During our `init` method we are in a state of flux. Our instance has just started being created, but hasn't finished. Because of this, we can't rely on `self` being completely set up like we can elsewhere in our class. So, in the `init` method, we *must never* use a method on `self`.

There is also a ton of design considerations about writing a setter such as that...but that's another issue. You never know who's subclassing your code!


text:
package au.gov.dva.sopapi.interfaces.model;

import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.util.Optional;

public interface Deployment extends HasDateRange {
  String getOperationName();
  String getEvent();

}


text:
namespace apollo {

namespace detail {

template <typename MemberPtr>
struct member_ptr_traits;

template <typename C, typename T>
struct member_ptr_traits<T C::*> {
private:
    using ql_member_t = remove_cvr<T>;
    using is_ptr_t = std::integral_constant<bool,
        pointer_traits<ql_member_t>::is_valid>;
    static bool const is_ptr = is_ptr_t::value;
public:
    using cls_t = C;
    using member_t = T;
    using ptr_t = typename std::conditional<is_ptr,
        const member_t&, member_t*>::type;
    using const_ptr_t = typename std::conditional<
            std::is_pointer<ql_member_t>::value,
            typename std::remove_pointer<ql_member_t>::type const*,
            typename std::conditional<is_ptr, void, member_t const*>::type
        >::type;

    static ptr_t as_ptr(C& c, T C::* m)
    {
        return as_ptr_impl(c, m, is_ptr_t());
    }

    static const_ptr_t as_ptr(C const& c, T C::* m)
    {
        return as_ptr_impl(c, m, is_ptr_t());
    }

private:
    static ptr_t as_ptr_impl(C const& c, T C::* m, std::true_type)
    {
        return c.*m;
    }

    static ptr_t as_ptr_impl(C& c, T C::* m, std::false_type)
    {
        return &(c.*m);
    }

    static const_ptr_t as_ptr_impl(C const& c, T C::* m, std::false_type)
    {
        return &(c.*m);
    }
};
} // namespace detail

template <typename MemberPtr, MemberPtr Member>
typename detail::member_ptr_traits<MemberPtr>::member_t const&
member_getter(
    typename detail::member_ptr_traits<MemberPtr>::cls_t const& c)
{
    return c.*Member;
}

template <
    typename MemberPtr, MemberPtr Member,
    typename ReturnedPtr =
        typename detail::member_ptr_traits<MemberPtr>::ptr_t>
ReturnedPtr
member_ptr_getter(
    typename detail::member_ptr_traits<MemberPtr>::cls_t& c)
{
    return static_cast<ReturnedPtr>(
        detail::member_ptr_traits<MemberPtr>::as_ptr(c, Member));
}

template <
    typename MemberPtr, MemberPtr Member,
    typename ReturnedPtr =
        typename detail::member_ptr_traits<MemberPtr>::const_ptr_t>
ReturnedPtr
member_cptr_getter(
    typename detail::member_ptr_traits<MemberPtr>::cls_t const& c)
{
    return static_cast<ReturnedPtr>(
        detail::member_ptr_traits<MemberPtr>::as_ptr(c, Member));
}

template <typename MemberPtr, MemberPtr Member>
void
member_setter(
    typename detail::member_ptr_traits<MemberPtr>::cls_t& c,
    typename detail::member_ptr_traits<MemberPtr>::member_t const& v)
{
    c.*Member = v;
}

#define APOLLO_DETAIL_PROP(t, ...) \
    (::apollo::member_##t<decltype(&__VA_ARGS__), &__VA_ARGS__>)
#define APOLLO_MEMBER_GETTER(...) APOLLO_DETAIL_PROP(getter, __VA_ARGS__)
#define APOLLO_MEMBER_PTR_GETTER(...) \
    APOLLO_DETAIL_PROP(ptr_getter, __VA_ARGS__)
#define APOLLO_MEMBER_CPTR_GETTER(...) \
    APOLLO_DETAIL_PROP(cptr_getter, __VA_ARGS__)
#define APOLLO_MEMBER_SETTER(...) APOLLO_DETAIL_PROP(setter, __VA_ARGS__)

} // namespace apollo

#endif // APOLLO_PROPERTY_HPP_INCLUDED