text:
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#ifndef OPENTITAN_SW_DEVICE_LIB_DIF_DIF_SYSRST_CTRL_H_
#define OPENTITAN_SW_DEVICE_LIB_DIF_DIF_SYSRST_CTRL_H_

/**
 * @file
 * @brief System Reset Controller Device
 * Interface Functions
 */

#include "sw/device/lib/dif/autogen/dif_sysrst_ctrl_autogen.h"
#include "sysrst_ctrl_regs.h"  // Generated.

#ifdef __cplusplus
extern "C" {
#endif  // __cplusplus

/**
 * A System Reset Controller key combination.
 */
typedef enum dif_sysrst_ctrl_key_combo {
  /**
   * Key combination 0.
   */
  kDifSysrstCtrlKeyCombo0 = 1U << 0,
  /**
   * Key combination 1.
   */
  kDifSysrstCtrlKeyCombo1 = 1U << 1,
  /**
   * Key combination 2.
   */
  kDifSysrstCtrlKeyCombo2 = 1U << 2,
  /**
   * Key combination 3.
   */
  kDifSysrstCtrlKeyCombo3 = 1U << 3,
  /**
   * All key combination ORed together.
   *
   * This is useful when clearing all key combination IRQ causes at once, e.g.,
   * when initializing the System Reset Controller.
   */
  kDifSysrstCtrlKeyComboAll = (1U << 4) - 1,
} dif_sysrst_ctrl_key_combo_t;

/**
 * System Reset Controller keys that can form a key combination.
 */
typedef enum dif_sysrst_ctrl_key {
  /**
   * Key 0.
   */
  kDifSysrstCtrlKey0 = 1U << 0,
  /**
   * Key 1.
   */
  kDifSysrstCtrlKey1 = 1U << 1,
  /**
   * Key 2.
   */
  kDifSysrstCtrlKey2 = 1U << 2,
  /**
   * Power button key.
   */
  kDifSysrstCtrlKeyPowerButton = 1U << 3,
  /**
   * AC power preset key.
   */
  kDifSysrstCtrlKeyAcPowerPresent = 1U << 4,
  /**
   * All keys ORed together.
   */
  kDifSysrstCtrlKeyAll = (1U << 5) - 1,
} dif_sysrst_ctrl_key_t;

/**
 * System Reset Controller key combination detection actions.
 */
typedef enum dif_sysrst_ctrl_key_combo_action {
  /**
   * Disable / disconnect battery.
   */
  kDifSysrstCtrlKeyComboActionBatteryDisable = 1U << 0,
  /**
   * Issue an interrupt to the processor.
   */
  kDifSysrstCtrlKeyComboActionInterrupt = 1U << 1,
  /**
   * Assert the embedded controller reset for a specified duration.
   */
  kDifSysrstCtrlKeyComboActionEcReset = 1U << 2,
  /**
   * Issue a reset request to the reset manager block.
   */
  kDifSysrstCtrlKeyComboActionSelfReset = 1U << 3,
  /**
   * All actions.
   */
  kDifSysrstCtrlKeyComboActionAll = (1U << 4) - 1,
} dif_sysrst_ctrl_key_combo_action_t;

/**
 * Runtime configuration for the System Reset Controller key combination
 * detection feature.
 */
typedef struct dif_sysrst_ctrl_key_combo_config {
  /**
   * The keys that comprise the key combination to detect (i.e., one or more
   * `dif_sysrst_ctrl_key_t`s ORed together).
   */
  uint32_t keys;
  /**
   * The duration the key combination should be pressed to trigger an action.
   *
   * Units: increments of 5us; [0, 2^32) represents [0, 60) seconds.
   */
  uint32_t detection_time_threshold;
  /**
   * The actions to trigger after detecting the key press combination (one or
   * more `dif_sysrst_ctrl_key_combo_action_t`s ORed together).
   */
  uint32_t actions;
  /**
   * The embedded controller's reset pulse width.
   *
   * Note: only applicable if the `kDifSysrstCtrlKeyComboActionEcReset` action
   * is enabled for the key combination.
   *
   * Units: increments of 5us; [0, 2^16) represents [10, 200) milliseconds.
   */
  uint16_t embedded_controller_reset_duration;
} dif_sysrst_ctrl_key_combo_config_t;

/**
 * System Reset Controller input signal changes that may be detected.
 */
typedef enum dif_sysrst_ctrl_input_change {
  /**
   * Power button input signal high-to-low.
   */
  kDifSysrstCtrlInputPowerButtonH2L = 1U << 0,
  /**
   * Key 0 input signal high-to-low.
   */
  kDifSysrstCtrlInputKey0H2L = 1U << 1,
  /**
   * Key 1 input signal high-to-low.
   */
  kDifSysrstCtrlInputKey1H2L = 1U << 2,
  /**
   * Key 2 input signal high-to-low.
   */
  kDifSysrstCtrlInputKey2H2L = 1U << 3,
  /**
   * AC power present input signal high-to-low.
   */
  kDifSysrstCtrlInputAcPowerPresetH2L = 1U << 4,
  /**
   * Embedded controller reset input signal high-to-low.
   */
  kDifSysrstCtrlInputEcResetH2L = 1U << 5,
  /**
   * Flash write protect input signal high-to-low.
   */
  kDifSysrstCtrlInputFlashWriteProtectH2L = 1U << 6,
  /**
   * Power button input signal low-to-high.
   */
  kDifSysrstCtrlInputPowerButtonL2H = 1U << 8,
  /**
   * Key 0 input signal low-to-high.
   */
  kDifSysrstCtrlInputKey0L2H = 1U << 9,
  /**
   * Key 1 input signal low-to-high.
   */
  kDifSysrstCtrlInputKey1L2H = 1U << 10,
  /**
   * Key 2 input signal low-to-high.
   */
  kDifSysrstCtrlInputKey2L2H = 1U << 11,
  /**
   * AC power present input signal low-to-high.
   */
  kDifSysrstCtrlInputAcPowerPresetL2H = 1U << 12,
  /**
   * Embedded controller reset input signal low-to-high.
   */
  kDifSysrstCtrlInputEcResetL2H = 1U << 13,
  /**
   * Flash write protect input signal low-to-high.
   */
  kDifSysrstCtrlInputFlashWriteProtectL2H = 1U << 14,
  /**
   * All input signal transitions.
   */
  kDifSysrstCtrlInputAll = ((1U << 15) - 1) & ~(1U << 7),
} dif_sysrst_ctrl_input_change_t;

/**
 * System Reset Controller key interrupt sources.
 */
typedef enum dif_sysrst_ctrl_key_intr_src {
  /**
   * Power button input signal high-to-low.
   */
  kDifSysrstCtrlKeyIntrStatusInputPowerButtonH2L =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_PWRB_H2L_BIT,
  /**
   * Key 0 input signal high-to-low.
   */
  kDifSysrstCtrlKeyIntrStatusInputKey0H2L =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_KEY0_IN_H2L_BIT,
  /**
   * Key 1 input signal high-to-low.
   */
  kDifSysrstCtrlKeyIntrStatusInputKey1H2L =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_KEY1_IN_H2L_BIT,
  /**
   * Key 2 input signal high-to-low.
   */
  kDifSysrstCtrlKeyIntrStatusInputKey2H2L =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_KEY2_IN_H2L_BIT,
  /**
   * AC power present input signal high-to-low.
   */
  kDifSysrstCtrlKeyIntrStatusInputAcPowerPresetH2L =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_AC_PRESENT_H2L_BIT,
  /**
   * Embedded controller reset input signal high-to-low.
   */
  kDifSysrstCtrlKeyIntrStatusInputEcResetH2L =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_EC_RST_L_H2L_BIT,
  /**
   * Flash write protect input signal high-to-low.
   */
  kDifSysrstCtrlKeyIntrStatusInputFlashWriteProtectH2L =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_FLASH_WP_L_H2L_BIT,
  /**
   * Power button input signal low-to-high.
   */
  kDifSysrstCtrlKeyIntrStatusInputPowerButtonL2H =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_PWRB_L2H_BIT,
  /**
   * Key 0 input signal low-to-high.
   */
  kDifSysrstCtrlKeyIntrStatusInputKey0L2H =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_KEY0_IN_L2H_BIT,
  /**
   * Key 1 input signal low-to-high.
   */
  kDifSysrstCtrlKeyIntrStatusInputKey1L2H =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_KEY1_IN_L2H_BIT,
  /**
   * Key 2 input signal low-to-high.
   */
  kDifSysrstCtrlKeyIntrStatusInputKey2L2H =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_KEY2_IN_L2H_BIT,
  /**
   * AC power present input signal low-to-high.
   */
  kDifSysrstCtrlKeyIntrStatusInputAcPowerPresetL2H =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_AC_PRESENT_L2H_BIT,
  /**
   * Embedded controller reset input signal low-to-high.
   */
  kDifSysrstCtrlKeyIntrStatusInputEcResetL2H =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_EC_RST_L_L2H_BIT,
  /**
   * Flash write protect input signal low-to-high.
   */
  kDifSysrstCtrlKeyIntrStatusInputFlashWriteProtectL2H =
      1U << SYSRST_CTRL_KEY_INTR_STATUS_FLASH_WP_L_L2H_BIT,
} dif_sysrst_ctrl_key_intr_src_t;

/**
 * System Reset Controller combo interrupt sources.
 */
typedef enum dif_sysrst_ctrl_combo_intr_src {
  /**
   * Power button input signal high-to-low.
   */
  kDifSysrstCtrlComboIntrStatusCombo0H2L =
      1U << SYSRST_CTRL_COMBO_INTR_STATUS_COMBO0_H2L_BIT,
  /**
   * Key 0 input signal high-to-low.
   */
  kDifSysrstCtrlComboIntrStatusCombo1H2L =
      1U << SYSRST_CTRL_COMBO_INTR_STATUS_COMBO1_H2L_BIT,
  /**
   * Key 1 input signal high-to-low.
   */
  kDifSysrstCtrlComboIntrStatusCombo2H2L =
      1U << SYSRST_CTRL_COMBO_INTR_STATUS_COMBO2_H2L_BIT,
  /**
   * Key 2 input signal high-to-low.
   */
  kDifSysrstCtrlComboIntrStatusCombo3H2L =
      1U << SYSRST_CTRL_COMBO_INTR_STATUS_COMBO3_H2L_BIT,
} dif_sysrst_ctrl_combo_intr_src_t;

/**
 * Runtime configuration for the System Reset Controller input signal change
 * detection feature.
 */
typedef struct dif_sysrst_ctrl_input_change_config {
  /**
   * A combination of input signal changes to detect (one or more
   * `dif_sysrst_ctrl_input_change_t`s ORed together).
   */
  uint32_t input_changes;
  /**
   * The time to allow the input signal to stabilize before reevaluating its
   * value to decide whether to trigger an interrupt.
   *
   * Units: increments of 5us; [0, 2^16) represents [0, 200) milliseconds.
   */
  uint16_t debounce_time_threshold;
} dif_sysrst_ctrl_input_change_config_t;

/**
 * Runtime configuration for the System Reset Controller key signal
 * auto-override feature.
 *
 * Upon detection of a Power Button high-to-low transition, the signals from
 * generic keys 0 through 2 may be overriden with specified values.
 */
typedef struct dif_sysrst_ctrl_auto_override_config {
  /**
   * The time to allow the Power Button signal to stabilize before reevaluating
   * its value to decide whether it was pressed.
   *
   * Units: increments of 5us; [0, 2^16) represents [0, 200) milliseconds.
   */
  uint16_t debounce_time_threshold;
  /**
   * Whether to override the key 0 signal.
   */
  dif_toggle_t override_key_0;
  /**
   * The value to override onto the key 0 signal.
   */
  bool key_0_override_value;
  /**
   * Whether to override the key 1 signal.
   */
  dif_toggle_t override_key_1;
  /**
   * The value to override onto the key 1 signal.
   */
  bool key_1_override_value;
  /**
   * Whether to override the key 2 signal.
   */
  dif_toggle_t override_key_2;
  /**
   * The value to override onto the key 2 signal.
   */
  bool key_2_override_value;
} dif_sysrst_ctrl_auto_override_config_t;

/**
 * System Reset Controller pins that can be inverted, read, or overridden.
 */
typedef enum dif_sysrst_ctrl_pin {
  /**
   * Key 0 input.
   */
  kDifSysrstCtrlPinKey0In = 1U << 0,
  /**
   * Key 0 output.
   */
  kDifSysrstCtrlPinKey0Out = 1U << 1,
  /**
   * Key 1 input.
   */
  kDifSysrstCtrlPinKey1In = 1U << 2,
  /**
   * Key 1 output.
   */
  kDifSysrstCtrlPinKey1Out = 1U << 3,
  /**
   * Key 2 input.
   */
  kDifSysrstCtrlPinKey2In = 1U << 4,
  /**
   * Key 2 output.
   */
  kDifSysrstCtrlPinKey2Out = 1U << 5,
  /**
   * Power button input.
   */
  kDifSysrstCtrlPinPowerButtonIn = 1U << 6,
  /**
   * Power button output.
   */
  kDifSysrstCtrlPinPowerButtonOut = 1U << 7,
  /**
   * AC power preset input.
   */
  kDifSysrstCtrlPinAcPowerPresentIn = 1U << 8,
  /**
   * Battery disable output.
   */
  kDifSysrstCtrlPinBatteryDisableOut = 1U << 9,
  /**
   * Lid open input.
   */
  kDifSysrstCtrlPinLidOpenIn = 1U << 10,
  /**
   * Z3 Wakeup output.
   */
  kDifSysrstCtrlPinZ3WakeupOut = 1U << 11,
  /**
   * Embedded controller reset inout.
   */
  kDifSysrstCtrlPinEcResetInOut = 1U << 12,
  /**
   * Flash write protect inout.
   */
  kDifSysrstCtrlPinFlashWriteProtectInOut = 1U << 13,
  /**
   * All non open drain pins.
   */
  kDifSysrstCtrlPinAllNonOpenDrain = (1U << 12) - 1,
} dif_sysrst_ctrl_pin_t;

/**
 * Runtime configuration for the System Reset Controller output pin override
 * feature.
 */
typedef struct dif_sysrst_ctrl_pin_config_t {
  /**
   * The enablement of the output pin's override feature.
   */
  dif_toggle_t enabled;
  /**
   * Whether to allow overriding the output pin with a value of 0.
   */
  bool allow_zero;
  /**
   * Whether to allow overriding the output pin with a value of 1.
   */
  bool allow_one;
  /**
   * The override value to write.
   *
   * Note: writing a non-allowable value will cause
   * `dif_sysrst_ctrl_output_pin_override_configure()` to return `kDifBadArg`.
   */
  bool override_value;
} dif_sysrst_ctrl_pin_config_t;

/**
 * Runtime configuration for the System Reset Controller ultra-low-power (ULP)
 * wakeup feature.
 *
 * When enabled, detection of any of the following conditions:
 *
 * 1. HIGH level on the AC Power present signal, or
 * 2. HIGH --> LOW transition on the Power Button signal, or
 * 3. LOW --> HIGH transition on the Lid Open signal,
 *
 * will cause the System Reset Controller to assert the Z3 Wakeup output signal
 * and trigger an interrupt, which will also issue a wakeup request to the power
 * manager.
 */
typedef struct dif_sysrst_ctrl_ulp_wakeup_config_t {
  /**
   * The enablement of the ULP wakeup feature.
   */
  dif_toggle_t enabled;
  /**
   * The time to allow the AC Power present signal to stabilize before
   * reevaluating its value to decide whether it was activated.
   *
   * Units: increments of 5us; [0, 2^16) represents [10, 200) milliseconds.
   */
  uint16_t ac_power_debounce_time_threshold;
  /**
   * The time to allow the Lid Open signal to stabilize before reevaluating its
   * value to decide whether it was activated.
   *
   * Units: increments of 5us; [0, 2^16) represents [10, 200) milliseconds.
   */
  uint16_t lid_open_debounce_time_threshold;
  /**
   * The time to allow the Power Button signal to stabilize before reevaluating
   * its value to decide whether it was pressed.
   *
   * Units: increments of 5us; [0, 2^16) represents [10, 200) milliseconds.
   */
  uint16_t power_button_debounce_time_threshold;
} dif_sysrst_ctrl_ulp_wakeup_config_t;

/**
 * Configures a System Reset Controller's key combination detection feature.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param key_combo Key combination to configure.
 * @param config Runtime configuration parameters.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_key_combo_detect_configure(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_key_combo_t key_combo,
    dif_sysrst_ctrl_key_combo_config_t config);

/**
 * Configures a System Reset Controller's input signal change detection feature.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param config Runtime configuration parameters.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_input_change_detect_configure(
    const dif_sysrst_ctrl_t *sysrst_ctrl,
    dif_sysrst_ctrl_input_change_config_t config);

/**
 * Configures a System Reset Controller's output pin override feature.
 *
 * Note, only output (or inout) pins may be overriden, i.e., set to a specific
 * value. Attempting to configure the override feature for input pins will
 * return `kDifBadArg`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param output_pin Output pin to configure.
 * @param config Output pin override configuration parameters.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_output_pin_override_configure(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_pin_t output_pin,
    dif_sysrst_ctrl_pin_config_t config);

/**
 * Configures a System Reset Controller's key signal auto-override feature.
 *
 * Upon detection of a Power Button high-to-low transition, the signals from
 * generic keys 0 through 2 may be overriden with specified values.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param config Runtime configuration parameters.
 * @param enabled Whether to enable the feature or not.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_auto_override_configure(
    const dif_sysrst_ctrl_t *sysrst_ctrl,
    dif_sysrst_ctrl_auto_override_config_t config, dif_toggle_t enabled);

/**
 * Configures a System Reset Controller's ultra-low-power (ULP) wakeup feature.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param config Runtime configuration parameters.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_ulp_wakeup_configure(
    const dif_sysrst_ctrl_t *sysrst_ctrl,
    dif_sysrst_ctrl_ulp_wakeup_config_t config);

/**
 * Sets the enablement state of a System Reset Controller's ultra-low-power
 * (ULP) wakeup feature.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param enabled The enablement state to configure the ULP wakeup feature in.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_ulp_wakeup_set_enabled(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_toggle_t enabled);

/**
 * Gets the enablement state of a System Reset Controller's ultra-low-power
 * (ULP) wakeup feature.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param[out] is_enabled The enablement state of the ULP wakeup feature.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_ulp_wakeup_get_enabled(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_toggle_t *is_enabled);

/**
 * Sets the inversion state a System Reset Controller's input and output pins.
 *
 * Note, only input and output (NOT inout) pins may be inverted. Attempting
 * to set the inversion state of inout pins will return `kDifBadArg`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param pins The input and output pins to set the inverted state of (i.e., one
 *             or more `dif_sysrst_ctrl_pin_t`s ORed together).
 * @param inverted The inverted state to configure for the pins.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_pins_set_inverted(
    const dif_sysrst_ctrl_t *sysrst_ctrl, uint32_t pins, bool inverted);

/**
 * Gets the inversion state a System Reset Controller's input and output pins.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param[out] inverted_pins The input and output pins that are inverted (i.e.,
 *                           one or more `dif_sysrst_ctrl_pin_t`s ORed
 *                           together).
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_pins_get_inverted(
    const dif_sysrst_ctrl_t *sysrst_ctrl, uint32_t *inverted_pins);

/**
 * Sets allowable override values for a System Reset Controller's output pin.
 *
 * Note, only output (or inout) pins may be overriden, i.e., set to a specific
 * value. Attempting to set the allowable override values for input pins will
 * return `kDifBadArg`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param pin The output pin whose allowable override values should be set.
 * @param allow_zero Whether to allow overriding the pin's value to 0.
 * @param allow_one Whether to allow overriding the pin's value to 1.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_output_pin_override_set_allowed(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_pin_t pin,
    bool allow_zero, bool allow_one);

/**
 * Gets allowable override values for a System Reset Controller's output pin.
 *
 * Note, only output (or inout) pins may be overriden, i.e., set to a specific
 * value. Attempting to get the allowable override values for input pins will
 * return `kDifBadArg`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param pin The allowable override values to get for an output pin.
 * @param[out] allow_zero Whether overriding the pin's value to 0 is allowed.
 * @param[out] allow_one Whether overriding the pin's value to 1 is allowed.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_output_pin_override_get_allowed(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_pin_t pin,
    bool *allow_zero, bool *allow_one);

/**
 * Sets the enablement of a System Reset Controller's output pin override
 * feature.
 *
 * Note, only output (or inout) pins may be overriden, i.e., set to a specific
 * value. Attempting to set the enablement of the override feature for input
 * pins will return `kDifBadArg`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param pin The output pin whose override feature should be set.
 * @param enabled The enablement state to configure the override feature in.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_output_pin_override_set_enabled(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_pin_t pin,
    dif_toggle_t enabled);

/**
 * Gets the enablement of a System Reset Controller's output pin override
 * feature.
 *
 * Note, only output (or inout) pins may be overriden, i.e., set to a specific
 * value. Attempting to get the enablement of the override feature for input
 * pins will return `kDifBadArg`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param pin The output pin whose override feature should be set.
 * @param[out] is_enabled The enablement state the override feature is
 * configured in.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_output_pin_override_get_enabled(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_pin_t pin,
    dif_toggle_t *is_enabled);

/**
 * Sets the override value of a System Reset Controller's output pin (like
 * writing to a GPIO pin).
 *
 * Note, only output (or inout) pins may be overriden, i.e., set to a specific
 * value. Attempting to set the override value of an input pin will return
 * `kDifBadArg`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param pin The output pin to override.
 * @param value The override value to set on the pin.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_output_pin_set_override(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_pin_t pin,
    bool value);

/**
 * Gets the override value of a System Reset Controller's output pin (like
 * writing to a GPIO pin).
 *
 * Note, only output (or inout) pins may be overriden, i.e., set to a specific
 * value. Attempting to get the override value of an input pin will return
 * `kDifBadArg`.
 *
 * Additionally, this will return the configured override value of an output pin
 * regardless if the override function is enabled or the override value is
 * allowed.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param pin The output pin to override.
 * @param[out] value The override value set on the pin.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_output_pin_get_override(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_pin_t pin,
    bool *value);

/**
 * Reads a System Reset Controller's input pin (like a GPIO pin).
 *
 * Note, only input (or inout) pins may be read. Attempting to read the value of
 * an output pin will return `kDifBadArg`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param pin The pin to read.
 * @param[out] value The value set on the pin.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_input_pin_read(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_pin_t pin,
    bool *value);

/**
 * Sets the enablement of a System Reset Controller's key signal auto-override
 * feature.
 *
 * Note, this feature is only available for keys 0, 1, and 2. Attempting to
 * enable the auto-override feature on non-supported keys will return
 * `kDifBadArg`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param key The key to enable the override feature for.
 * @param enabled Whether to enable the feature or not.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_auto_override_set_enabled(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_key_t key,
    dif_toggle_t enabled);

/**
 * Gets the enablement of a System Reset Controller's key signal auto-override
 * feature.
 *
 * Note, this feature is only available for keys 0, 1, and 2. Attempting to
 * check whether the auto-override feature is enabled non-supported keys will
 * return `kDifBadArg`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param key The key the override feature is enabled for.
 * @param[out] is_enabled Whether the feature is enabled or not.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_auto_override_get_enabled(
    const dif_sysrst_ctrl_t *sysrst_ctrl, dif_sysrst_ctrl_key_t key,
    dif_toggle_t *is_enabled);

/**
 * Gets the cause(s) of a key combination detection IRQ.
 *
 * @param sysrst_ctrl An sysrst_ctrl handle.
 * @param[out] causes The causes of the IRQ (one or more
 *             `dif_sysrst_ctrl_key_combo_t`s ORed together).
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_key_combo_irq_get_causes(
    const dif_sysrst_ctrl_t *sysrst_ctrl, uint32_t *causes);

/**
 * Clears the cause(s) of a key combination detection IRQ.
 *
 * @param sysrst_ctrl An sysrst_ctrl handle.
 * @param causes The causes of the IRQ (one or more
 *               `dif_sysrst_ctrl_key_combo_t`s ORed together).
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_key_combo_irq_clear_causes(
    const dif_sysrst_ctrl_t *sysrst_ctrl, uint32_t causes);

/**
 * Gets the cause(s) of an input signal change detection IRQ.
 *
 * @param sysrst_ctrl An sysrst_ctrl handle.
 * @param[out] causes The causes of the IRQ (one or more
 *             `dif_sysrst_ctrl_input_change_t`s ORed together).
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_input_change_irq_get_causes(
    const dif_sysrst_ctrl_t *sysrst_ctrl, uint32_t *causes);

/**
 * Clears the cause(s) of an input signal change detection IRQ.
 *
 * @param sysrst_ctrl An sysrst_ctrl handle.
 * @param causes The causes of the IRQ (one or more
 *               `dif_sysrst_ctrl_input_change_t`s ORed together).
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_input_change_irq_clear_causes(
    const dif_sysrst_ctrl_t *sysrst_ctrl, uint32_t causes);

/**
 * Gets the ultra-low-power wakeup status.
 *
 * @param sysrst_ctrl An sysrst_ctrl handle.
 * @param[out] wakeup_detected The ULP wakeup detection state.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_ulp_wakeup_get_status(
    const dif_sysrst_ctrl_t *sysrst_ctrl, bool *wakeup_detected);

/**
 * Clears the ultra-low-power wakeup status.
 *
 * @param sysrst_ctrl An sysrst_ctrl handle.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_ulp_wakeup_clear_status(
    const dif_sysrst_ctrl_t *sysrst_ctrl);

/**
 * Locks System Reset Controller configurations.
 *
 * This function is reentrant: calling it while locked will have no effect and
 * return `kDifOk`.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_lock(const dif_sysrst_ctrl_t *sysrst_ctrl);

/**
 * Checks whether System Reset Controller configurations are locked.
 *
 * @param sysrst_ctrl A System Reset Controller handle.
 * @param[out] is_locked Out-param for the locked state.
 * @return The result of the operation.
 */
OT_WARN_UNUSED_RESULT
dif_result_t dif_sysrst_ctrl_is_locked(const dif_sysrst_ctrl_t *sysrst_ctrl,
                                       bool *is_locked);

#ifdef __cplusplus
}  // extern "C"
#endif  // __cplusplus

#endif  // OPENTITAN_SW_DEVICE_LIB_DIF_DIF_SYSRST_CTRL_H_


text:
module Events where

import Graphics.Gloss.Interface.IO.Game
import System.Random
import WorldState
import Config
import Lib
import Debug.Trace
import Data.Maybe

type WorldMod m = WorldState -> m WorldState

eventHandler :: Event -> WorldMod IO
eventHandler (EventKey (Char k) Down _ _) w@Running {paddleMovement = movOld, moveOnce = movO} = let
  movement = case k of
    'a' -> MLeft
    'd' -> MRight
    _   -> movOld in
  return $ dropTopOfStack k $ w { paddleMovement = movement, moveOnce = if movOld == movement then movO else movement }
eventHandler (EventKey (Char k) Up _ _) w@Running {paddleMovement = mov} = let
  movement = case (k, mov) of
    ('a', MLeft)  -> MStay
    ('d', MRight) -> MStay
    _   -> mov in
  return $ w {paddleMovement = movement}
eventHandler _ w = return w

dropTopOfStack :: Char -> WorldState -> WorldState
dropTopOfStack 's' w@Running{paddlePosition = pos, paddleStack = ps, stackingArea = sa} =
  if null ps then w else
  let stackCol = sa !! pos in
  if isJust $ head stackCol then w else let
  block = Just $ head ps
  (emty, blcks) = break isJust stackCol
  stackCol' = tail emty ++ [block] ++ blcks in
  w {stackingArea = replaceNth pos stackCol' sa, paddleStack = tail ps}
dropTopOfStack  _  w = w

onTick :: Float -> WorldMod IO
onTick timePassed world@Running { timeElapsed = timeOld } = let
  totalTimePassed = timePassed + timeOld
  newTimePassed = totalTimePassed `mod'` tickLength in
  return (run world totalTimePassed) { timeElapsed = newTimePassed } where
  run :: WorldState -> Float -> WorldState
  run w@Running{
    pause = paus,
    lastBlock = lb,
    lastBlockMovement = lbm,
    lanes = l,
    paddlePosition = pos,
    paddleStack = ps,
    paddleMovement = mov,
    moveOnce = movO,
    nextKlaxToRemove = nextKlax } t
    | t < tickLength  = w
    | otherwise       = let
    mov' = if movO == MStay then mov else movO
    pos' = case mov' of
      MLeft  -> max 0 (pos - 1)
      MRight -> min (lanesCount - 1) (pos + 1)
      MStay  -> pos
    w1 = w { paddlePosition = pos', moveOnce = MStay } in
    if paus > 0 then trace (show paus) $ run (w1 {pause = paus - 1}) (t - tickLength) else
    case nextKlax of
    Just klax -> run (compressStack $ deleteKlax klax w1 { nextKlaxToRemove = Nothing }) (t - tickLength)
    _ -> case klaxAchieved w1 of
      klax@(Just _) -> run (w1 { pause = 2, nextKlaxToRemove = klax }) (t - tickLength)
      _ -> let
        (w2, newBlocks) = if lb == blockEvery - 1 then generateBlocks w1 else (w1, replicate lanesCount Nothing)
        w3 = w2 { lastBlock = (lb + 1) `mod` blockEvery }
        (lanes', stackTop) = if lbm == blockSpeed - 1 then tickLanes newBlocks l else (l, replicate lanesCount Nothing)
        w4 = w3 { lanes = lanes' }
        w5 = w4 { lastBlockMovement = (lbm + 1) `mod` blockSpeed }
        psBlock = stackTop !! pos
        ps' = case psBlock of
          Just b | length ps < paddleStackHeight -> b : ps
          _                                      -> ps in
        run (w5 {paddleStack = ps'}) (t - tickLength)

tickLanes :: Lane -> [Lane] -> ([Lane], Lane)
tickLanes lnew ls = (zipWith (\b lane -> tail lane ++ [b]) lnew ls, map head ls)

generateBlocks :: WorldState -> (WorldState, Lane)
generateBlocks w@Running {_rand = r} = let
  (newBlock, r') = random r
  pos :: Int
  (pos, r'') = randomR (0, lanesCount - 1) r'
  l = take lanesCount $ replicate pos Nothing ++ [Just newBlock] ++ repeat Nothing in
  (w{_rand = r''}, l)

deleteKlax :: [Position] -> WorldState -> WorldState
deleteKlax [] w = w
deleteKlax ((x, y):pos) w@Running{stackingArea = sa} = deleteKlax pos (w {stackingArea = replaceNth' x (replaceNth y Nothing) sa})

compressStack :: WorldState -> WorldState
compressStack w@Running{ stackingArea = sa } = w { stackingArea = map compress sa } where
  compress xs = let
    (space1, rest1) = break isJust xs
    (blocks1, rest2) = break isNothing rest1
    (space2, blocks2) = break isJust rest2 in
    space1 ++ space2 ++ blocks1 ++ blocks2

redpajama_set_name: RedPajamaGithub


text:
package org.midao.jdbc.core.handlers.output;

import org.midao.jdbc.core.MjdbcConfig;
import org.midao.jdbc.core.exception.MjdbcException;
import org.midao.jdbc.core.handlers.model.QueryParameters;
import org.midao.jdbc.core.processor.QueryOutputProcessor;

/**
 * Converts query output into Map of Beans.
 *

 * Example:
 * Query output:
 * new Object[]{"jack", "sheriff", 36}
 * new Object[]{"henry", "mechanic", 36}
 * new Object[]{"alison", "agent", 30}
 *

 * If we will create class Character and specify first column as key we would receive:
 * Map:
 * k: jack v: Character {"jack", "sheriff", 36};
 * k: henry v: Character {"henry", mechanic, 36}
 * k: alison v: Character {"alison", agent, 30}
 */
public class BeanMapOutputHandler<K, V> extends AbstractKeyedOutputHandler<K, V> {

    /**
     * Bean Class description
     */
    private final Class<V> type;

    /**
     * Creates new BeanMapOutputHandler instance.
     *
     * @param type Bean Class description
     */
    public BeanMapOutputHandler(Class<V> type) {
        this(type, MjdbcConfig.getDefaultQueryOutputProcessor(), 0, null);
    }

    /**
     * Creates new BeanMapOutputHandler instance.
     *
     * @param type      Bean Class description
     * @param processor Query output processor
     */
    public BeanMapOutputHandler(Class<V> type, QueryOutputProcessor processor) {
        this(type, processor, 0, null);
    }

    /**
     * Creates new BeanMapOutputHandler instance.
     *
     * @param type        Bean Class description
     * @param columnIndex Index of the column which would be used as Key for result Map
     */
    public BeanMapOutputHandler(Class<V> type, int columnIndex) {
        this(type, MjdbcConfig.getDefaultQueryOutputProcessor(), columnIndex, null);
    }

    /**
     * Creates new BeanMapOutputHandler instance.
     *
     * @param type       Bean Class description
     * @param columnName Name of the column which would be used as Key for result Map
     */
    public BeanMapOutputHandler(Class<V> type, String columnName) {
        this(type, MjdbcConfig.getDefaultQueryOutputProcessor(), 0, columnName);
    }

    /**
     * Creates new BeanMapOutputHandler instance.
     *
     * @param type        Bean Class description
     * @param processor   Query output processor
     * @param columnIndex Index of the column which would be used as Key for result Map. Used only if @columnName is null
     * @param columnName  Name of the column which would be used as Key for result Map
     */
    private BeanMapOutputHandler(Class<V> type, QueryOutputProcessor processor,
                                 int columnIndex, String columnName) {

        super(processor, columnIndex, columnName);

        this.type = type;
    }

    /**
     * Converts query output into Map of Beans.
     *
     * @param params query output row
     * @return Map of Beans converted from query output
     * @throws org.midao.jdbc.core.exception.MjdbcException
     */
    @Override
    protected V createRow(QueryParameters params) throws MjdbcException {
        return this.outputProcessor.toBean(params, type);
    }

}


text:
// @optional core/polyfills/polyfills.js
// @optional core/shims/shims.js
// @require core/lodash/lodash.js
// @require core/jquery/jquery.js
// @require core/modernizr/modernizr.js

(function () {

  /* SVELTO */

  let Svelto = {

    VERSION: '[pacco.svelto.version]',
    ENVIRONMENT: '[pacco.environment[0]]',
    DEVELOPMENT: '[pacco.environment[0]]' === 'development',

    /* DEPENDENCIES */

    _: window._,
    $: window.$,
    Modernizr: window.Modernizr,

    /* NAMESPACES */

    Instances: {},
    Templates: {},
    Widgets: {}

  };

  /* EXPORT */

  window.Svelto = Svelto;

}());


text:
use ::physics::{RigidBody, StaticRigidBody, CollisionModel, ForceGenerator};
use ::render::{SceneRenderable};
use ::core::Transform;

pub struct EntityBlueprint {
    pub rigid_body: Option<RigidBody>,
    pub collision: Option<CollisionModel>,
    pub renderable: Option<SceneRenderable>,
    pub transform: Option<Transform>,
    pub force: Option<ForceGenerator>
}

impl EntityBlueprint {
    pub fn empty() -> Self {
        EntityBlueprint {
            rigid_body: None,
            collision: None,
            renderable: None,
            transform: None,
            force: None
        }
    }

    pub fn make_static(mut self) -> Self {
        if let Some(RigidBody::Dynamic(rb)) = self.rigid_body {
            let static_rb = StaticRigidBody {
                position: rb.state.position,
                orientation: rb.state.orientation
            };
            self.rigid_body = Some(RigidBody::Static(static_rb));
        }
        self
    }
}


text:
<?php

final class PhabricatorSystemActionLog extends PhabricatorSystemDAO {

  protected $actorHash;
  protected $actorIdentity;
  protected $action;
  protected $score;
  protected $epoch;

  public function getConfiguration() {
    return array(
      self::CONFIG_TIMESTAMPS => false,
    ) + parent::getConfiguration();
  }

  public function setActorIdentity($identity) {
    $this->setActorHash(PhabricatorHash::digestForIndex($identity));
    return parent::setActorIdentity($identity);
  }

}


text:
ES5Harness.registerTest( {
id: "15.2.3.2-2-9",

path: "TestCases/chapter15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-9.js",

description: "Object.getPrototypeOf returns the [[Prototype]] of its parameter (Date)",

test: function testcase() {
  if (Object.getPrototypeOf(Date) === Function.prototype) {
    return true;
  }
 },

precondition: function prereq() {
  return fnExists(Object.getPrototypeOf);
 }
});


text: package lookoutmetrics


text:
package org.saddle.groupby

import org.saddle._

/**
 * Helper class to do combine or transform after a groupBy
 */
class FrameGrouper[Z: ST: ORD, X: ST: ORD, Y: ST: ORD, T: ST](
  ix: Index[Z], frame: Frame[X, Y, T], sorted: Boolean = true) {

  private lazy val uniq: Array[Z] = {
    val arr = ix.uniques.toArray
    if (sorted && !ix.isMonotonic)
      array.take(arr, array.argsort(arr), sys.error("Logic error in sorting group index"))
    else
      arr
  }

  def keys: Array[Z] = uniq

  def groups: Array[(Z, Array[Int])] = for (k <- keys) yield (k, ix.get(k))

  def combine[U: ST](fn: (Z, Vec[T]) => U): Frame[Z, Y, U] =
    Frame(frame.values.map(SeriesGrouper.combine(ix, keys, _, fn)) : _*)
      .setRowIndex(keys)
      .setColIndex(frame.colIx)

  // less powerful combine, ignores group key
  def combine[U: ST: ORD](fn: Vec[T] => U): Frame[Z, Y, U] =
    combine( (k, v) => fn(v) )

  def transform[U: ST](fn: (Z, Vec[T]) => Vec[U]): Frame[X, Y, U] =
    Frame(frame.values.map(SeriesGrouper.transform(_, groups, fn)), frame.rowIx, frame.colIx)

  // less powerful transform, ignores group key
  def transform[U: ST](fn: Vec[T] => Vec[U]): Frame[X, Y, U] =
    transform( (k, v) => fn(v) )
}

object FrameGrouper {
  def apply[Z: ST: ORD, Y: ST: ORD, T: ST](frame: Frame[Z, Y, T]) =
    new FrameGrouper(frame.rowIx, frame)

  def apply[Z: ST: ORD, X: ST: ORD, Y: ST: ORD, T: ST](
    ix: Index[Z], frame: Frame[X, Y, T]) = new FrameGrouper(ix, frame)
}


text:
package org.edx.indonesiax.view;

import android.app.ActionBar;
import android.content.res.Configuration;
import android.view.View;

import org.edx.indonesiax.R;
import org.edx.indonesiax.view.custom.DisableableViewPager;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.util.ActivityController;

import static org.assertj.android.api.Assertions.assertThat;
import static org.junit.Assert.*;

// I don't understand the data model cycle behind this, and I couldn't run
// the demo sandbox to see this Activity, so I'm not writing tests for the
// adapter interactions yet
@RunWith(RobolectricGradleTestRunner.class)
public class CourseUnitNavigationActivityTest extends CourseBaseActivityTest {
    /**
     * Method for defining the subclass of {@link CourseUnitNavigationActivity}
     * that is being tested. Should be overridden by subclasses.
     *
     * @return The {@link CourseUnitNavigationActivity} subclass that is being tested
     */
    @Override
    protected Class<? extends CourseUnitNavigationActivity> getActivityClass() {
        return CourseUnitNavigationActivity.class;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected boolean appliesPrevTransitionOnRestart() {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Test
    @Override
    public void initializeTest() {
        super.initializeTest();

        ActivityController<? extends CourseUnitNavigationActivity> controller =
                Robolectric.buildActivity(getActivityClass());
        CourseUnitNavigationActivity activity = controller.get();

        controller.create();
        assertNotNull(activity.findViewById(R.id.course_unit_nav_bar));
        assertNotNull(activity.findViewById(R.id.goto_prev));
        assertNotNull(activity.findViewById(R.id.goto_next));
    }

    /**
     * Generic method for asserting proper setup for the current orientation
     *
     * @param activity The current activity
     */
    private void assertOrientationSetup(CourseUnitNavigationActivity activity) {
        boolean isLandscape = activity.getResources().getConfiguration().orientation ==
                Configuration.ORIENTATION_LANDSCAPE;
        ActionBar bar = activity.getActionBar();
        if (bar != null) {
            assertEquals(!isLandscape, bar.isShowing());
        }
        View courseUnitNavBar = activity.findViewById(R.id.course_unit_nav_bar);
        assertNotNull(courseUnitNavBar);
        if (isLandscape) {
            assertThat(courseUnitNavBar).isNotVisible();
        } else {
            assertThat(courseUnitNavBar).isVisible();
        }
        View pagerView = activity.findViewById(R.id.pager);
        assertNotNull(pagerView);
        assertThat(pagerView).isInstanceOf(DisableableViewPager.class);
        assertEquals(!isLandscape, ((DisableableViewPager) pagerView).isPagingEnabled());
    }

    /**
     * Generic method for testing the setup for the specified orientation
     *
     * @param orientation The orientation to be tested
     */
    public void testOrientationSetup(int orientation) {
        ActivityController<? extends CourseUnitNavigationActivity> controller =
                Robolectric.buildActivity(getActivityClass());
        CourseUnitNavigationActivity activity = controller.get();
        activity.getResources().getConfiguration().orientation = orientation;
        controller.create();
        assertOrientationSetup(activity);
    }

    /**
     * Testing setup for different orientations
     */
    @Test
    public void orientationsSetupTest() {
        testOrientationSetup(Configuration.ORIENTATION_PORTRAIT);
        testOrientationSetup(Configuration.ORIENTATION_LANDSCAPE);
    }

    /**
     * Generic method for testing setup on orientation changes
     *
     * @param activity The current activity
     * @param orientation The orientation change to test
     */
    private void testOrientationChange(
            CourseUnitNavigationActivity activity, int orientation) {
        Configuration config = activity.getResources().getConfiguration();
        assertNotEquals(orientation, config.orientation);
        config.orientation = orientation;
        activity.onConfigurationChanged(config);
        assertOrientationSetup(activity);
    }

    /**
     * Testing orientation changes
     */
    @Test
    public void orientationChangeTest() {
        CourseUnitNavigationActivity activity =
                Robolectric.setupActivity(CourseUnitNavigationActivity.class);
        assertNotEquals(Configuration.ORIENTATION_LANDSCAPE,
                activity.getResources().getConfiguration().orientation);
        assertOrientationSetup(activity);

        testOrientationChange(activity, Configuration.ORIENTATION_LANDSCAPE);
        testOrientationChange(activity, Configuration.ORIENTATION_PORTRAIT);
    }

    /**
     * Ignoring functionality testing upon receiving a DownloadEvent, as
     * {@link CourseUnitNavigationActivity} also overrides and ignores it
     */
    @Override
    @Ignore
    @Test
    public void downloadEventTest() {}
}


text:
"""
Module contains factories to initializes various applications
of monasca-log-api
"""

import six

import falcon
from oslo_log import log

from monasca_log_api.app.base import error_handlers
from monasca_log_api.app.base import request
from monasca_log_api.app.controller import healthchecks
from monasca_log_api.app.controller.v2 import logs as v2_logs
from monasca_log_api.app.controller.v3 import logs as v3_logs
from monasca_log_api.app.controller import versions
from monasca_log_api import config

def error_trap(app_name):
    """Decorator trapping any error during application boot time"""

    @six.wraps(error_trap)
    def _wrapper(func):

        @six.wraps(_wrapper)
        def _inner_wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception:
                logger = log.getLogger(__name__)
                logger.exception('Failed to load application \'%s\'', app_name)
                raise

        return _inner_wrapper

    return _wrapper

def singleton_config(func):
    """Decorator ensuring that configuration is loaded only once."""

    @six.wraps(singleton_config)
    def _wrapper(global_config, **local_conf):
        config.parse_args()
        return func(global_config, **local_conf)

    return _wrapper

@error_trap('version')
def create_version_app(global_conf, **local_conf):
    """Creates Version application"""

    ctrl = versions.Versions()
    controllers = {
        '/': ctrl,   # redirect http://host:port/ down to Version app
                     # avoid conflicts with actual pipelines and 404 error
        '/version': ctrl,  # list all the versions
        '/version/{version_id}': ctrl  # display details of the version
    }

    wsgi_app = falcon.API(
        request_type=request.Request
    )
    wsgi_app.req_options.strip_url_path_trailing_slash = True
    for route, ctrl in controllers.items():
        wsgi_app.add_route(route, ctrl)
    return wsgi_app

@error_trap('healthcheck')
def create_healthcheck_app(global_conf, **local_conf):
    """Creates Healthcheck application"""

    ctrl = healthchecks.HealthChecks()
    controllers = {
        '/': ctrl
    }

    wsgi_app = falcon.API(
        request_type=request.Request
    )
    for route, ctrl in controllers.items():
        wsgi_app.add_route(route, ctrl)
    return wsgi_app

@error_trap('api')
@singleton_config
def create_api_app(global_conf, **local_conf):
    """Creates MainAPI application"""

    controllers = {}
    api_version = global_conf.get('api_version')

    if api_version == 'v2.0':
        controllers.update({
            '/log/single': v2_logs.Logs()
        })
    elif api_version == 'v3.0':
        controllers.update({
            '/logs': v3_logs.Logs()
        })

    wsgi_app = falcon.API(
        request_type=request.Request
    )

    for route, ctrl in controllers.items():
        wsgi_app.add_route(route, ctrl)

    error_handlers.register_error_handlers(wsgi_app)

    return wsgi_app


text:
const r = require('./db/r');
const mtime = require('./db/model/mtime');

function* logEvent(next) {
    try {
        switch (this.req.method) {
            case "POST":
                yield logActivityEvent(this.params, this.reqctx.user, 'create');
                break;
            case "PUT":
                yield logActivityEvent(this.params, this.reqctx.user, 'update');
                break;
            case "PATCH":
                yield logActivityEvent(this.params, this.reqctx.user, 'update');
                break;
            case "DELETE":
                // yield logDeleteEvent(this.params);
                break;
        }
    } catch (error) {
        console.log('Error logging event', this.params, error);
    }

    yield next;
}

function* logActivityEvent(params, user, eventType) {
    yield updateMTimesBaseOnParams(params);

    if (!params.project_id) {
        return false;
    }

    let activity = new Activity(params.project_id, user, eventType);
    yield addActivityEvent(activity, params);

    return true;
}

function* addActivityEvent(activity, params) {
    if (params.file_id) {
        yield addFileEvent(activity, params.file_id);
    } else if (params.sample_id) {
        yield addSampleEvent(activity, params.sample_id);
    } else if (params.template_id) {
        yield addProcessTemplateEvent(activity,params.template_id);
    } else if (params.process_id) {
        yield addProcessEvent(activity, params.process_id);
    } else if (params.experiment_id) {
        yield addExperimentEvent(activity, params.experiment_id);
    } else {
        yield addProjectEvent(activity, params.project_id);
    }
}

function* addFileEvent(activity, fileId) {
    yield addEvent('datafiles', fileId, 'file', activity);
}

function* addSampleEvent(activity, sampleId) {
    yield addEvent('samples', sampleId, 'sample', activity);
}

function* addProcessEvent(activity, processId) {
    yield addEvent('processes', processId, 'process', activity);
}

function* addExperimentEvent(activity, experimentId) {
    yield addEvent('experiments', experimentId, 'experiment', activity);
}

function* addProjectEvent(activity, projectId) {
    yield addEvent('projects', projectId, 'project', activity);
}

function* addProcessTemplateEvent(activity, templateId) {
    yield addEvent('templates', templateId, 'process-create', activity);
}

function* addEvent(table, id, itemType, activity) {
    const item = yield r.table(table).get(id);
    activity.itemType(itemType).itemName(item.name).itemId(id);
    yield r.table('events').insert(activity);
}

function* updateMTimesBaseOnParams(params) {
    if (params.project_id) {
        yield mtime.update('projects', params.project_id);
    }

    if (params.experiment_id) {
        yield mtime.update('experiments', params.experiment_id);
    }

    if (params.process_id) {
        yield mtime.update('processes', params.process_id);
    }

    if (params.sample_id) {
        yield mtime.update('samples', params.sample_id);
    }

    if (params.file_id) {
        yield mtime.update('datafiles', params.file_id);
    }

    if (params.directory_id) {
        yield mtime.update('datadirs', params.directory_id);
    }
}

function* logDeleteEvent(params) {
}

class Activity {
    constructor(projectId, user, eventType) {
        this.project_id = projectId;
        this.item_type = '';
        this.item_id = '';
        this.item_name = '';
        this.birthtime = r.now();
        this.event_type = eventType;
        this.user = {
            id: user.id,
            name: user.fullname
        };
    }

    itemType(itemType) {
        this.item_type = itemType;
        return this;
    }

    itemName(itemName) {
        this.item_name = itemName;
        return this;
    }

    itemId(itemId) {
        this.item_id = itemId;
        return this;
    }

    eventType(eventType) {
        this.event_type = eventType;
        return this;
    }
}

module.exports = {
    logEvent
};


text:
#ifndef __DEBUGGER_ELF_TYPES_H__
#define __DEBUGGER_ELF_TYPES_H__

#include <inttypes.h>

namespace debugger {

typedef uint64_t   ElfAddr64;
typedef uint64_t   ElfOff64;
typedef unsigned short ElfHalf;
typedef signed   int   ElfSword;
typedef unsigned int   ElfWord;
typedef uint64_t       ElfDWord;

typedef unsigned int   ElfAddr32;
typedef unsigned int   ElfOff32;

static const char MAGIC_BYTES[]  = {0x7f,'E','L','F',0};

enum E_EI {
    EI_MAG0,
    EI_MAG1,
    EI_MAG2,
    EI_MAG3,
    EI_CLASS,
    EI_DATA,
    EI_VERSION,
    EI_PAD,
    EI_NIDENT=16
};
static const uint8_t ELFCLASSNONE = 0;
static const uint8_t ELFCLASS32   = 1;
static const uint8_t ELFCLASS64   = 2;

static const uint8_t ELFDATANONE  = 0;
static const uint8_t ELFDATA2LSB  = 1;
static const uint8_t ELFDATA2MSB  = 2;

static const uint8_t EV_NONE      = 0;          // Invalid version
static const uint8_t EV_CURRENT   = 1;          // Current version
//etype values:
static const ElfHalf ET_NONE      = 0;       // no file type
static const ElfHalf ET_REL       = 1;       // rellocatable file
static const ElfHalf ET_EXEC      = 2;       // executable file
static const ElfHalf ET_DYN       = 3;       // shared object file
static const ElfHalf ET_CORE      = 4;       // core file
static const ElfHalf ET_LOPROC    = 0xff00;  // Processor-specific
static const ElfHalf ET_HIPROC    = 0xffff;  // Processor-specific
//emachine values:
static const ElfHalf EM_NONE      = 0;       // No machine
static const ElfHalf EM_M32       = 1;       // AT&T WE 32100
static const ElfHalf EM_SPARC     = 2;       // SPARC
static const ElfHalf EM_386       = 3;       // Intel 386
static const ElfHalf EM_68K       = 4;       // Motorola 68000
static const ElfHalf EM_88K       = 5;       // Motorola 88000
static const ElfHalf EM_860       = 7;       // Intel 80860
static const ElfHalf EM_MIPS      = 8;       // MIPS RS3000

struct Elf32_Ehdr {
    unsigned char e_ident[EI_NIDENT];
    ElfHalf e_type;      // Shared/Executable/Rellocalable etc
    ElfHalf e_machine;   // SPARC, X86 etc
    ElfWord e_version;   //
    ElfAddr32 e_entry;     // entry point
    ElfOff32  e_phoff;     // Program header offset
    ElfOff32  e_shoff;     // Section Header offset
    ElfWord e_flags;
    ElfHalf e_ehsize;
    ElfHalf e_phentsize; // size of one entry in the Program header. All entries are the same size
    ElfHalf e_phnum;     // number of entries in a Program header
    ElfHalf e_shentsize; // entry size in the section header table. all entries are the same size
    ElfHalf e_shnum;     // number of section header entries
    ElfHalf e_shstrndx;
};

struct Elf64_Ehdr {
    unsigned char e_ident[EI_NIDENT];
    ElfHalf e_type;      // Shared/Executable/Rellocalable etc
    ElfHalf e_machine;   // SPARC, X86 etc
    ElfWord e_version;   //
    ElfAddr64 e_entry;     // entry point
    ElfOff64  e_phoff;     // Program header offset
    ElfOff64  e_shoff;     // Section Header offset
    ElfWord e_flags;
    ElfHalf e_ehsize;
    ElfHalf e_phentsize; // size of one entry in the Program header. All entries are the same size
    ElfHalf e_phnum;     // number of entries in a Program header
    ElfHalf e_shentsize; // entry size in the section header table. all entries are the same size
    ElfHalf e_shnum;     // number of section header entries
    ElfHalf e_shstrndx;
};

static ElfHalf SwapBytes(ElfHalf v) {
     v = ((v>>8)&0xff) | ((v&0xFF)<<8);
     return v;
}

static ElfWord SwapBytes(ElfWord v) {
    v = ((v >> 24) & 0xff) | ((v >> 8) & 0xff00)
      | ((v << 8) & 0xff0000) | ((v & 0xFF) << 24);
    return v;
}

static ElfDWord SwapBytes(ElfDWord v) {
    v = ((v >> 56) & 0xffull) | ((v >> 48) & 0xff00ull)
      | ((v >> 40) & 0xff0000ull) | ((v >> 32) & 0xff000000ull)
      | ((v << 8) & 0xff000000ull) | ((v << 16) & 0xff0000000000ull)
      | ((v << 24) & 0xff0000000000ull) | ((v << 32) & 0xff00000000000000ull);
    return v;
}

class ElfHeaderType {
 public:
    ElfHeaderType(uint8_t *img) {
        pimg_ = img;
        isElf_ = true;
        for (int i = 0; i < 4; i++) {
            if (pimg_[i] != MAGIC_BYTES[i]) {
                isElf_ = false;
            }
        }
        is32b_ = pimg_[EI_CLASS] == ELFCLASS32;
        isMsb_ = pimg_[EI_DATA] == ELFDATA2MSB;
        if (is32b_) {
            Elf32_Ehdr *h = reinterpret_cast<Elf32_Ehdr *>(pimg_);
            if (isMsb_) {
                e_shoff_ = SwapBytes(h->e_shoff);
                e_shnum_ = SwapBytes(h->e_shnum);
                e_phoff_ = SwapBytes(h->e_phoff);
            } else {
                e_shoff_ = h->e_shoff;
                e_shnum_ = h->e_shnum;
                e_phoff_ = h->e_phoff;
            }
        } else {
            Elf64_Ehdr *h = reinterpret_cast<Elf64_Ehdr *>(pimg_);
            if (isMsb_) {
                e_shoff_ = SwapBytes(h->e_shoff);
                e_shnum_ = SwapBytes(h->e_shnum);
                e_phoff_ = SwapBytes(h->e_phoff);
            } else {
                e_shoff_ = h->e_shoff;
                e_shnum_ = h->e_shnum;
                e_phoff_ = h->e_phoff;
            }
        }
    }

    virtual bool isElf() { return isElf_; }
    virtual bool isElf32() { return is32b_; }
    virtual bool isElfMsb() { return isMsb_; }
    virtual uint64_t get_shoff() { return e_shoff_; }
    virtual ElfHalf get_shnum() { return e_shnum_; }
    virtual uint64_t get_phoff() { return e_phoff_; }
 protected:
    uint8_t *pimg_;
    bool isElf_;
    bool is32b_;
    bool isMsb_;
    uint64_t e_shoff_;
    ElfHalf e_shnum_;
    uint64_t e_phoff_;
};

//sh_type:
static const ElfWord SHT_NULL      = 0;          // section header is inactive
static const ElfWord SHT_PROGBITS  = 1;          // section with CPU instructions
static const ElfWord SHT_SYMTAB    = 2;          // section contains symbols table (also as SHT_DYNSIM)
static const ElfWord SHT_STRTAB    = 3;          // section holds string table
static const ElfWord SHT_RELA      = 4;          // section with relocation data
static const ElfWord SHT_HASH      = 5;          // section with hash table. Must be for the dynamic lib
static const ElfWord SHT_DYNAMIC   = 6;          // section holds information for dynamic linking.
static const ElfWord SHT_NOTE      = 7;
static const ElfWord SHT_NOBITS    = 8;          // section with not initialized data
static const ElfWord SHT_REL       = 9;
static const ElfWord SHT_SHLIB     = 10;
static const ElfWord SHT_DYNSYM    = 11;         // section contains debug symbol table
static const ElfWord SHT_INIT_ARRAY    = 14;
static const ElfWord SHT_FINI_ARRAY    = 15;
static const ElfWord SHT_PREINIT_ARRAY = 16;
static const ElfWord SHT_LOPROC    = 0x70000000;
static const ElfWord SHT_HIPROC    = 0x7fffffff;
static const ElfWord SHT_HIUSER    = 0xffffffff;
//sh_flags:
static const ElfWord SHF_WRITE     = 0x1;        // section contains data that should be writable during process execution.
static const ElfWord SHF_ALLOC     = 0x2;        // section occupies memory during process execution.
static const ElfWord SHF_EXECINSTR = 0x4;        // section contains executable machine instructions.
static const ElfWord SHF_MASKPROC  = 0xf0000000; // processor-specific sematic

struct Elf32_Shdr {
    ElfWord    sh_name;//Index in a header section table (gives name of section)
    ElfWord    sh_type;
 	ElfWord	sh_flags;	/* SHF_... */
 	ElfAddr32	sh_addr;
 	ElfOff32	sh_offset;
 	ElfWord	sh_size;
    ElfWord    sh_link;
    ElfWord    sh_info;
    ElfWord   sh_addralign;
    ElfWord   sh_entsize;
};

struct Elf64_Shdr {
    ElfWord    sh_name;//Index in a header section table (gives name of section)
    ElfWord    sh_type;
    ElfDWord   sh_flags;
    ElfAddr64  sh_addr;
    ElfOff64   sh_offset;
    ElfDWord   sh_size;
    ElfWord    sh_link;
    ElfWord    sh_info;
    ElfDWord   sh_addralign;
    ElfDWord   sh_entsize;
};

class SectionHeaderType {
 public:
    SectionHeaderType(uint8_t *img, ElfHeaderType *h) {
        if (h->isElf32()) {
            Elf32_Shdr *sh = reinterpret_cast<Elf32_Shdr *>(img);
            if (h->isElfMsb()) {
                sh_name_ = SwapBytes(sh->sh_name);
                sh_type_ = SwapBytes(sh->sh_type);
                sh_flags_ = SwapBytes(sh->sh_flags);
                sh_addr_ = SwapBytes(sh->sh_addr);
                sh_offset_ = SwapBytes(sh->sh_offset);
                sh_size_ = SwapBytes(sh->sh_size);
                sh_entsize_ = SwapBytes(sh->sh_entsize);
            } else {
                sh_name_ = sh->sh_name;
                sh_type_ = sh->sh_type;
                sh_flags_ = sh->sh_flags;
                sh_addr_ = sh->sh_addr;
                sh_offset_ = sh->sh_offset;
                sh_size_ = sh->sh_size;
                sh_entsize_ = sh->sh_entsize;
            }
        } else {
            Elf64_Shdr *sh = reinterpret_cast<Elf64_Shdr *>(img);
            if (h->isElfMsb()) {
                sh_name_ = SwapBytes(sh->sh_name);
                sh_type_ = SwapBytes(sh->sh_type);
                sh_flags_ = SwapBytes(sh->sh_flags);
                sh_addr_ = SwapBytes(sh->sh_addr);
                sh_offset_ = SwapBytes(sh->sh_offset);
                sh_size_ = SwapBytes(sh->sh_size);
                sh_entsize_ = SwapBytes(sh->sh_entsize);
            } else {
                sh_name_ = sh->sh_name;
                sh_type_ = sh->sh_type;
                sh_flags_ = sh->sh_flags;
                sh_addr_ = sh->sh_addr;
                sh_offset_ = sh->sh_offset;
                sh_size_ = sh->sh_size;
                sh_entsize_ = sh->sh_entsize;
            }
        }
    }
    virtual ElfWord get_name() { return sh_name_; }
    virtual ElfWord get_type() { return sh_type_; }
    virtual uint64_t get_offset() { return sh_offset_; }
    virtual uint64_t get_size() { return sh_size_; }
    virtual uint64_t get_addr() { return sh_addr_; }
    virtual uint64_t get_flags() { return sh_flags_; }
    virtual uint64_t get_entsize() { return sh_entsize_; }
 protected:
    ElfWord sh_name_;
    ElfWord sh_type_;
    uint64_t sh_offset_;
    uint64_t sh_size_;
    uint64_t sh_addr_;
    uint64_t sh_flags_;
    uint64_t sh_entsize_;
};

#define ELF32_ST_BIND(i) ((i)>>4)
#define ELF32_ST_TYPE(i) ((i)&0xf)
#define ELF32_ST_INFO(b,t) (((b)<<4) + ((t)&0xf))

static const unsigned char STB_LOCAL   = 0;
static const unsigned char STB_GLOBAL  = 1;
static const unsigned char STB_WEAK    = 2;
static const unsigned char STB_LOPROC  = 13;
static const unsigned char STB_HIPROC  = 15;

static const unsigned char STT_NOTYPE  = 0;
static const unsigned char STT_OBJECT  = 1;
static const unsigned char STT_FUNC    = 2;
static const unsigned char STT_SECTION = 3;
static const unsigned char STT_FILE    = 4;
static const unsigned char STT_LOPROC  = 13;
static const unsigned char STT_HIPROC  = 15;

struct Elf32_Sym {
    ElfWord    st_name;
 	ElfAddr32	st_value;
 	ElfWord	st_size;
 	unsigned char	st_info;
 	unsigned char	st_other;
 	ElfHalf	st_shndx;
};

struct Elf64_Sym {
    ElfWord    st_name;
	unsigned char	st_info;
	unsigned char	st_other;
	ElfHalf	st_shndx;
	ElfAddr64	st_value;
	ElfDWord	st_size;
};

class SymbolTableType {
 public:
    SymbolTableType(uint8_t *img, ElfHeaderType *h) {
        if (h->isElf32()) {
            Elf32_Sym *st = reinterpret_cast<Elf32_Sym *>(img);
            if (h->isElfMsb()) {
                st_name_ = SwapBytes(st->st_name);
                st_value_ = SwapBytes(st->st_value);
                st_size_ = SwapBytes(st->st_size);
            } else {
                st_name_ = st->st_name;
                st_value_ = st->st_value;
                st_size_ = st->st_size;
            }
            st_info_ = st->st_info;
        } else {
            Elf64_Sym *st = reinterpret_cast<Elf64_Sym *>(img);
            if (h->isElfMsb()) {
                st_name_ = SwapBytes(st->st_name);
                st_value_ = SwapBytes(st->st_value);
                st_size_ = SwapBytes(st->st_size);
            } else {
                st_name_ = st->st_name;
                st_value_ = st->st_value;
                st_size_ = st->st_size;
            }
            st_info_ = st->st_info;
        }
    }
    virtual ~SymbolTableType() {}
    virtual ElfWord get_name() { return st_name_; }
    virtual uint64_t get_value() { return st_value_; }
    virtual uint64_t get_size() { return st_size_; }
    virtual unsigned char get_info() { return st_info_; }
 protected:
    ElfWord    st_name_;
    unsigned char st_info_;
    uint64_t st_value_;
    uint64_t st_size_;
};

//p_type:
static const ElfWord PT_NULL     = 0;
static const ElfWord PT_LOAD     = 1;
static const ElfWord PT_DYNAMIC  = 2;
static const ElfWord PT_INTERP   = 3;
static const ElfWord PT_NOTE     = 4;
static const ElfWord PT_SHLIB    = 5;
static const ElfWord PT_PHDR     = 6;
static const ElfWord PT_LOPROC   = 0x70000000;
static const ElfWord PT_HIPROC   = 0x7fffffff;

typedef struct ProgramHeaderType64
{
  uint32_t    p_type;
  uint32_t    p_offset;
  uint64_t    p_vaddr;
  uint64_t    p_paddr;
    ElfDWord	p_filesz;
    ElfDWord	p_memsz;
    ElfDWord	p_flags;
    ElfDWord	p_align;
} ProgramHeaderType64;

typedef struct ProgramHeaderType32
{
  uint32_t    p_type;
  uint32_t    p_offset;
  ElfAddr32    p_vaddr;
  ElfAddr32    p_paddr;
  ElfWord	p_filesz;
  ElfWord	p_memsz;
  ElfWord	p_flags;
  ElfWord	p_align;
} ProgramHeaderType32;

}  // namespace debugger

#endif  // __DEBUGGER_ELF_TYPES_H__


text:
  class HomePage < PageObject

    element :logo, {css: 'img[alt="Mercury Tours"]'}
    element :left_navigation_pane, {css: 'div table tbody tr td table tbody tr td table tbody tr td table tbody'}
    element :one_cool_summer, {css: 'td > img'}
    element :destinations,{css:"img[alt='Desinations']"}
    element :featured_destination,{css:"img[alt='Featured Destination: Aruba']"}
    element :specials,{css:"img[alt='Specials']"}
    element :tour_tips,{css:"img[alt='Tour Tips']"}
    element :links,{css:"img[alt='Links']"}
    element :vacations, {css:"img[alt='Vacations']"}
    element :register, {css:"img[alt='Register']"}
    element :sign_in, {css:"input[alt='Sign-In']"}
    element :cruise, {xpath: "//a[text()='Cruises']"}
    element :username_input, {xpath: "//input[@name='userName']"}
    element :password_input, {xpath: "//input[@name='password']"}

    def initialize(page_driver)
      @driver = page_driver
    end

    def go_to(url='http://newtours.demoaut.com/')
      driver.navigate.to(url)
      self
    end

    def is_current_page?
      driver.title.include? "Welcome: Mercury Tours"
    end

    def is_element_present?(element)
      send(element.downcase.gsub(' ','_')).displayed?
    end

    def select_an_element(element)
      send(element.downcase.gsub(' ','_')).click()
    end

    def get_title_of_page
      driver.title
    end

    def get_element_text(element)
      send(element.downcase.gsub(' ','_')).text
    end

    def get_link_element(link_text)
      @driver.find_element(link_text: link_text)
    end

    def is_link_present?(link_text)
      self.get_link_element(link_text).displayed?
    end

    def select_link_element_by_text(link_text)
      self.get_link_element(link_text).click
    end

    def login_with_existing_credentials(username='kelley_mills', password='Vo3sJ48kO')
      self.username_input.clear
      self.username_input.send_keys(username)
      self.password_input.send_keys(password)
      self.sign_in.click
    end

    def select_from_dropdown_by_text(element, text)
      Selenium::WebDriver::Support::Select.new(element).select_by(:text, text)
    end

  end


text:
#ifndef KAA_DISABLE_FEATURE_CONFIGURATION

#include "kaa_configuration_manager.h"

#include <stdbool.h>

#include "platform/stdio.h"
#include "platform/ext_sha.h"
#include "platform/ext_configuration_persistence.h"
#include "collections/kaa_list.h"
#include "kaa_common.h"
#include "kaa_status.h"
#include "kaa_defaults.h"
#include "kaa_platform_utils.h"
#include "kaa_platform_common.h"
#include "utilities/kaa_mem.h"
#include "utilities/kaa_log.h"
#include "avro_src/avro/io.h"

#define KAA_CONFIGURATION_RECEIVE_UPDATES_FLAG   0x01
#define KAA_CONFIGURATION_HASH_FLAG              0x02
#define KAA_CONFIGURATION_FULL_RESYNC_FLAG       0x04
#define KAA_CONFIGURATION_ALL_FLAGS              (KAA_CONFIGURATION_RECEIVE_UPDATES_FLAG | KAA_CONFIGURATION_HASH_FLAG | KAA_CONFIGURATION_FULL_RESYNC_FLAG)

#define KAA_CONFIGURATION_BODY_PRESENT           0x02

struct kaa_configuration_manager {
    kaa_digest                           configuration_hash;
    kaa_configuration_root_receiver_t    root_receiver;
    kaa_root_configuration_t            *root_record;
    kaa_status_t                        *status;
    kaa_logger_t                        *logger;
};

static kaa_root_configuration_t *kaa_configuration_manager_deserialize(char *buffer, size_t buffer_size)
{
    KAA_RETURN_IF_NIL2(buffer, buffer_size, NULL);

    avro_reader_t reader = avro_reader_memory(buffer, buffer_size);
    KAA_RETURN_IF_NIL(reader, NULL);
    kaa_root_configuration_t *result = KAA_CONFIGURATION_DESERIALIZE(reader);
    avro_reader_free(reader);
    return result;
}

kaa_error_t kaa_configuration_manager_create(kaa_configuration_manager_t **configuration_manager_p, kaa_status_t *status, kaa_logger_t *logger)
{
    KAA_RETURN_IF_NIL3(configuration_manager_p, status, logger, KAA_ERR_BADPARAM);
    kaa_configuration_manager_t *manager = (kaa_configuration_manager_t *) KAA_MALLOC(sizeof(kaa_configuration_manager_t));
    KAA_RETURN_IF_NIL(manager, KAA_ERR_NOMEM);

    manager->status = status;
    manager->logger = logger;
    manager->root_receiver = (kaa_configuration_root_receiver_t) { NULL, NULL };

    char *buffer = NULL;
    size_t buffer_size = 0;
    bool need_deallocation = false;
    ext_configuration_read(&buffer, &buffer_size, &need_deallocation);
    if (!buffer || !buffer_size) {
        need_deallocation = false;
#if KAA_CONFIGURATION_DATA_LENGTH > 0
        buffer = (char *)KAA_CONFIGURATION_DATA;
        buffer_size = KAA_CONFIGURATION_DATA_LENGTH;
#endif
    }

    if (buffer && buffer_size > 0) {
        ext_calculate_sha_hash(buffer, buffer_size, manager->configuration_hash);
        manager->root_record = kaa_configuration_manager_deserialize(buffer, buffer_size);

        if (!manager->root_record) {
            KAA_FREE(manager);
            if (need_deallocation && buffer)
                KAA_FREE(buffer);
            return KAA_ERR_NOMEM;
        }

        if (need_deallocation)
            KAA_FREE(buffer);
    }

    *configuration_manager_p = manager;
    return KAA_ERR_NONE;
}

void kaa_configuration_manager_destroy(kaa_configuration_manager_t *self)
{
    if (self) {
        if (self->root_record)
            self->root_record->destroy(self->root_record);
        KAA_FREE(self);
    }
}

kaa_error_t kaa_configuration_manager_get_size(kaa_configuration_manager_t *self, size_t *expected_size)
{
    KAA_RETURN_IF_NIL2(self, expected_size, KAA_ERR_BADPARAM);

    *expected_size = KAA_EXTENSION_HEADER_SIZE + sizeof(uint32_t) + SHA_1_DIGEST_LENGTH;

    return KAA_ERR_NONE;
}

kaa_error_t kaa_configuration_manager_request_serialize(kaa_configuration_manager_t *self, kaa_platform_message_writer_t *writer)
{
    KAA_RETURN_IF_NIL2(self, writer, KAA_ERR_BADPARAM);

    KAA_LOG_TRACE(self->logger, KAA_ERR_NONE, "Going to compile configuration client sync");

    uint32_t payload_size = sizeof(uint32_t) + SHA_1_DIGEST_LENGTH;

    kaa_platform_message_writer_t tmp_writer = *writer;
    kaa_error_t error_code = kaa_platform_message_write_extension_header(&tmp_writer, KAA_CONFIGURATION_EXTENSION_TYPE, KAA_CONFIGURATION_ALL_FLAGS, payload_size);
    if (error_code) {
        KAA_LOG_ERROR(self->logger, error_code, "Failed to write configuration extension header");
        return KAA_ERR_WRITE_FAILED;
    }

    *((uint32_t *) tmp_writer.current) = KAA_HTONL(self->status->config_seq_n);
    tmp_writer.current += sizeof(uint32_t);

    error_code = kaa_platform_message_write_aligned(&tmp_writer, self->configuration_hash, SHA_1_DIGEST_LENGTH);
    if (error_code) {
        KAA_LOG_ERROR(self->logger, error_code, "Failed to write configuration hash");
        return KAA_ERR_WRITE_FAILED;
    }

    *writer = tmp_writer;

    return KAA_ERR_NONE;
}

kaa_error_t kaa_configuration_manager_handle_server_sync(kaa_configuration_manager_t *self
                                                       , kaa_platform_message_reader_t *reader
                                                       , uint32_t extension_options
                                                       , size_t extension_length)
{
    KAA_RETURN_IF_NIL2(self, reader, KAA_ERR_BADPARAM);

    KAA_LOG_INFO(self->logger, KAA_ERR_NONE, "Received configuration server sync");

    if (extension_length >= sizeof(uint32_t)) {
        self->status->config_seq_n = KAA_NTOHL(*((uint32_t *) reader->current));
        reader->current += sizeof(uint32_t);
        if (extension_options & KAA_CONFIGURATION_BODY_PRESENT) {
            uint32_t body_size = KAA_NTOHL(*((uint32_t *) reader->current));
            reader->current += sizeof(uint32_t);

            char body[body_size];
            kaa_error_t error_code = kaa_platform_message_read_aligned(reader, body, body_size);
            if (error_code) {
                KAA_LOG_ERROR(self->logger, error_code, "Failed to read configuration body, size %u", body_size);
                return KAA_ERR_READ_FAILED;
            }
#if KAA_CONFIGURATION_DELTA_SUPPORT

#else
            if (self->root_record)
                self->root_record->destroy(self->root_record);

            self->root_record = kaa_configuration_manager_deserialize(body, body_size);
            if (!self->root_record) {
                KAA_LOG_ERROR(self->logger, KAA_ERR_READ_FAILED, "Failed to deserialize configuration body, size %u", body_size);
                return KAA_ERR_READ_FAILED;
            }

            ext_calculate_sha_hash(body, body_size, self->configuration_hash);
            ext_configuration_store(body, body_size);
#endif
            if (self->root_receiver.on_configuration_updated)
                self->root_receiver.on_configuration_updated(self->root_receiver.context, self->root_record);
        }
    }
    return KAA_ERR_NONE;
}

const kaa_root_configuration_t *kaa_configuration_manager_get_configuration(kaa_configuration_manager_t *self)
{
    return self ? self->root_record : NULL;
}

kaa_error_t kaa_configuration_manager_set_root_receiver(kaa_configuration_manager_t *self, const kaa_configuration_root_receiver_t *receiver)
{
    KAA_RETURN_IF_NIL2(self, receiver, KAA_ERR_BADPARAM);

    self->root_receiver = *receiver;

    return KAA_ERR_NONE;
}

#endif /* KAA_DISABLE_FEATURE_CONFIGURATION */


text:
var fs = require('co-fs'),
    fsp = require('co-fs-plus'),
    path = require('path'),
    logger = require('./../logger'),
    fileWriter = require('thoughtpad-fileWriter'),
    extend = require('util')._extend;

var compileLayout = function *(thoughtpad, pageName, layout, fullContent) {
    var ext = path.extname(thoughtpad.config.layouts[layout].url).replace('.', ''),
        layoutContents = thoughtpad.config.layouts[layout].contents,
        contents,
        document;

    thoughtpad.subscribe('html-compile-complete', 'layout', function *(res) {
        contents = res.contents;
    });

    document = extend({}, thoughtpad.config.pages[pageName]);
    // If we extend then we lose the reference to the main config obj. This is beneficial as then we can pass in the compiled layout content
    // whilst preserving the raw compiled content for other pages using different layouts. Dependent layouts can then use the previously compiled
    // contents without worrying that they will overwrite the main thoughtpad config page contents object
    if (fullContent) {
        document.content = fullContent;
    }

    yield thoughtpad.notify('html-compile-request', { ext: ext, contents: layoutContents, name: layout, data: { document: document } });

    // Clean up the subscription as this function will be called for each page
    thoughtpad.unsubscribe('html-compile-complete', 'layout');

    if (thoughtpad.config.layouts[layout].dependsOn) {
        thoughtpad.config.pages[pageName].fullContent = contents;
        yield compileLayout(thoughtpad, pageName, thoughtpad.config.layouts[layout].dependsOn, contents);
    } else  {
        thoughtpad.config.pages[pageName].fullContent = contents;
    }
},

postCompilePage = function *(thoughtpad, pageName) {

    thoughtpad.subscribe("html-postcompile-complete", function *(res) {
        thoughtpad.config.pages[pageName].fullContent = res.contents;
    });

    yield thoughtpad.notify('html-postcompile-request', { contents: thoughtpad.config.pages[pageName].fullContent });

},

compilePage = function *(thoughtpad, pageName, folder) {
    var ext = path.extname(thoughtpad.config.pages[pageName].url).replace('.', ''),
        friendlyUrl = thoughtpad.config.pages[pageName].friendlyUrl || pageName,
        filepath = thoughtpad.folders.posts + thoughtpad.config.pages[pageName].url,
        newFileName = thoughtpad.folders.preout + folder + friendlyUrl + '/' + "index.html",
        contents = thoughtpad.config.pages[pageName].content;

    if (!contents) {
        contents = yield fs.readFile(filepath, 'utf8');

        thoughtpad.subscribe('html-compile-complete', 'page', function *(res) {
            contents = res.contents;
        });

        yield thoughtpad.notify('html-compile-request', { ext: ext, contents: contents, name: pageName, data: { document: thoughtpad.config.pages[pageName] } });

        // Clean up the subscription as this function will be called for each page
        thoughtpad.unsubscribe('html-compile-complete', 'page');
    }

    if (thoughtpad.config.pages[pageName].layout) {
        thoughtpad.config.pages[pageName].content = contents;
        thoughtpad.config.pages[pageName].fullUrl = folder + friendlyUrl + '/';
        yield compileLayout(thoughtpad, pageName, thoughtpad.config.pages[pageName].layout);

        // Run the postcompile events (usually called to minify the contents)
        yield postCompilePage(thoughtpad, pageName);

        if (thoughtpad.config.pages[pageName].publish) {
            logger.clearCompiler("  Writing page to file system");
            yield fileWriter.writeFile(newFileName, thoughtpad.config.pages[pageName].fullContent, "pre_out/");
        }

        // The index is a special case page that sits in the topmost directory
        if (thoughtpad.config.pages[pageName].index) {
            exists = yield fs.exists(thoughtpad.folders.preout + "index.html");

            if (!exists) {
                yield fileWriter.writeFile(thoughtpad.folders.preout + "index.html", thoughtpad.config.pages[pageName].fullContent, "pre_out/");
            }
        }
    }
    return contents;
},

getLayoutData = function *(layouts, thoughtpad, dependsOn, layoutData) {
    var layout,
        contents,
        layoutData;

    if (!layoutData) {
        layoutData = {};
    }

    if (layouts) {
        for (layout in layouts) {
            contents = yield fs.readFile(thoughtpad.folders.layouts + layouts[layout].url, 'utf8');
            layoutData[layout] = { contents: contents, url: layouts[layout].url, dependsOn: dependsOn };
            if (layouts[layout].layouts) {
                layoutData = yield getLayoutData(layouts[layout].layouts, thoughtpad, layout, layoutData);
            }
        }
    }

    return layoutData;
},

sortPages = function (pages, pageName) {
    var i = 0,
        len,
        sortBy = pages[pageName].sortBy,
        order = (pages[pageName].sortOrder && pages[pageName].sortOrder === "asc") ? [1, -1] : [-1, 1],
        page = pages[pageName],
        sortedArr = [];

    if (page.pages && sortBy) {
        len = page.pages.length;
        for (i; i < len; i++) {
            if (pages[page.pages[i]][sortBy] && pages[page.pages[i]].publish) {
                sortedArr.push({ name: page.pages[i], value: pages[page.pages[i]][sortBy] });
            }
        }

        // By default the sort order is desc (so latest posts appear at the top)
        sortedArr.sort(function (a, b) {
            if (a.value > b.value) return order[0];
            if (a.value < b.value) return order[1];
            return 0;
        });
    }

    return sortedArr;
},

compilePages = function *(thoughtpad, pages, folder) {
    var i = 0,
        newFolder,
        len;

    if (!folder) {
        pages = thoughtpad.config.topPages || [];
        folder = thoughtpad.config.startFolder;
    }

    if (pages) {
        len = pages.length;
        for (i; i < len; i++) {
            // Compile the very bottom of the stack first so that when we go up we can dynamically add the content in
            if (thoughtpad.config.pages[pages[i]].ignoreBlockInUrl) {
                newFolder = folder;
            } else if (thoughtpad.config.pages[pages[i]].friendlyUrl) {
                newFolder = folder + thoughtpad.config.pages[pages[i]].friendlyUrl + '/';
            } else {
                newFolder = folder + pages[i] + '/';
            }
            yield compilePages(thoughtpad, thoughtpad.config.pages[pages[i]].pages, newFolder);

            // Sort the pages into the order specified by the config
            logger.clearCompiler("  Ordering the html pages");
            thoughtpad.config.pages[pages[i]].sortedPages = sortPages(thoughtpad.config.pages, pages[i]);

            // Now compile the current level as there will likely be a dependency, but only if we haven't compiled it already
            if (!thoughtpad.config.pages[pages[i]].fullUrl) {
                thoughtpad.config.pages[pages[i]].content = yield compilePage(thoughtpad, pages[i], folder);
            }
        }
    }
},

compile = function *(thoughtpad) {

    logger.compiler("\n  Reading layout data");

    // First save the layout data to memory (saves file io when compiling each page and it is unlikely to have many layouts)
    thoughtpad.config.layouts = yield getLayoutData(thoughtpad.config.layouts, thoughtpad);

    logger.clearCompiler("  Handling precompilation for html pages");
    yield thoughtpad.notify('html-precompile-all-request');

    // Compile each page in turn
    thoughtpad.subscribe('html-compile-all-request', function *(res) {
        yield compilePages(res.thoughtpad);
    });

    yield compilePages(thoughtpad);

    logger.clearCompiler("  Handling postcompilation for html pages");
    yield thoughtpad.notify('html-postcompile-all-request');

    logger.info(" Done!");
};

module.exports = {
    compile: compile
}


text:
from datetime import date, datetime

import config

def format_attachments(user):
    today = date.today().strftime('%b %d, %Y')
    attachments = []
    attachment = {}
    title = "*{0}* posted a status update for *{1}*".format(
        user.get('real_name') or user.get('name'), today)

    for i in range(len(config.QUESTIONS)):
        key = 'answer{0}'.format(i)
        answer = user[key]
        if answer:
            attachment['text'] = "*{0}*\n{1}".format(config.QUESTIONS[i]['text'], answer)
            attachment['color'] = config.QUESTIONS[i]['color']
            attachment['mrkdwn_in'] = ["text"]
            attachments.append(attachment)
            attachment = {}
        user[key] = None

    return title, attachments

class AnswerHandler:
    def __init__(self, post, post_report):
        self.post = post
        self.post_report = post_report

    def handle(self, event):
        text = event['text']
        user = event['user']
        channel = event['channel']

        if 'current_question' not in user or user['current_question'] is None:
            return False

        question_id = user['current_question']

        if text.lower() in ['nothing', 'none', 'nope', 'skip']:
            user['answer{0}'.format(question_id)] = None
            user['current_question'] = question_id + 1
        else:
            user['answer{0}'.format(question_id)] = text

        if question_id + 1 >= len(config.QUESTIONS):
            self.finish_report(channel, user)
            return True

        question_id += 1
        user['current_question'] = question_id
        self.ask_question(channel, question_id)

        return True

    def ask_question(self, channel, question_id):
        question = config.QUESTIONS[question_id]['text']
        self.post(channel, question)

    def finish_report(self, channel, user):
        title, attachments = format_attachments(user)
        user['current_question'] = None
        user['last_report'] = datetime.today()
        if len(attachments) == 0:
            self.post(channel, "I get it, you're not in the mood today.")
            return
        self.post(channel, "Thanks, keep rocking!")
        self.post_report(user, title, attachments)


text:
package org.italiangrid.voms.request.impl;

import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.italiangrid.voms.VOMSError;
import org.italiangrid.voms.request.VOMSACRequest;
import org.italiangrid.voms.request.VOMSServerInfo;
import org.italiangrid.voms.util.VOMSFQANNamingScheme;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;

/**
 *
 * This class builds VOMS XML requests starting from {@link VOMSACRequest}
 * objects.
 *
 * @author Andrea Ceccanti
 *
 */
public class VOMSRequestFactory {

  private static volatile VOMSRequestFactory instance = null;

  private String orderString;
  private String targetString;
  private long lifetime = 0;

  protected DocumentBuilder docBuilder;

  public synchronized static VOMSRequestFactory instance() {

    if (instance == null)
      instance = new VOMSRequestFactory();

    return instance;

  }

  private VOMSRequestFactory() {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringComments(true);
    factory.setNamespaceAware(false);
    factory.setValidating(false);

    try {
      docBuilder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      throw new VOMSError(e.getMessage());
    }

  }

  public long getLifetime() {

    return lifetime;
  }

  public void setLifetime(long lifetime) {

    this.lifetime = lifetime;
  }

  public String getOrderString() {

    return orderString;
  }

  public void setOrderString(String orderString) {

    this.orderString = orderString;
  }

  public String getTargetString() {

    return targetString;
  }

  public void setTargetString(String targetString) {

    this.targetString = targetString;
  }

  private void setOptionsForRequest(VOMSRequestFragment fragment) {

    if (orderString != null && orderString != "")
      fragment.buildOrderElement(orderString);

    if (targetString != null && targetString != "")
      fragment.buildTargetsElement(targetString);

    fragment.buildLifetime(lifetime);
  }

  private void loadOptions(VOMSACRequest options) {

    lifetime = options.getLifetime();
  }

  public Document buildRequest(VOMSACRequest acRequest, VOMSServerInfo endpoint) {

    loadOptions(acRequest);

    Document request = docBuilder.newDocument();
    VOMSRequestFragment frag = new VOMSRequestFragment(request);

    if (acRequest.getRequestedFQANs().isEmpty()) {

      frag.groupCommand("/" + endpoint.getVoName());
      setOptionsForRequest(frag);

      request.appendChild(frag.getFragment());
      return request;
    }

    Iterator<String> fqanIter = acRequest.getRequestedFQANs().iterator();
    frag.buildBase64();
    frag.buildVersion();

    while (fqanIter.hasNext()) {

      String FQAN = fqanIter.next();

      if (FQAN.equals("all")) {
        frag.allCommand();
      } else if (VOMSFQANNamingScheme.isGroup(FQAN)) {

        frag.groupCommand(FQAN);

      } else if (VOMSFQANNamingScheme.isRole(FQAN)) {

        frag.roleCommand(VOMSFQANNamingScheme.getRoleName(FQAN));

      } else if (VOMSFQANNamingScheme.isQualifiedRole(FQAN)) {

        frag.mappingCommand(VOMSFQANNamingScheme.getGroupName(FQAN),
          VOMSFQANNamingScheme.getRoleName(FQAN));
      }
    }

    setOptionsForRequest(frag);

    request.appendChild(frag.getFragment());
    return request;
  }

}

/**
 * Helper class to manage the creation of VOMS XML requests.
 *
 * @author andreaceccanti
 *
 */
class VOMSRequestFragment {

  private Document doc;

  DocumentFragment fragment;
  Element root;
  Element command;
  Element order;
  Element targets;
  Element lifetime;
  Element base64;
  Element version;

  public VOMSRequestFragment(Document doc) {

    this.doc = doc;

    fragment = doc.createDocumentFragment();
    buildRootElement();
  }

  protected void buildRootElement() {

    root = doc.createElement("voms");
    fragment.appendChild(root);

  }

  private void appendTextChild(Element e, String text) {

    e.appendChild(doc.createTextNode(text));
  }

  private String buildCompatibleOrderString(String s) {

    String[] FQANs = s.split(",");

    if (FQANs.length == 0)
      return "";

    for (int i = 0; i < FQANs.length; i++) {
      if (VOMSFQANNamingScheme.isQualifiedRole(FQANs[i]))
        FQANs[i] = VOMSFQANNamingScheme.toOldQualifiedRoleSyntax(FQANs[i]);
    }

    StringBuilder fqansString = new StringBuilder();

    for (int i = 0; i < FQANs.length; i++) {
      fqansString.append(FQANs);
      if (i < FQANs.length - 1)
        fqansString.append(",");
    }

    return fqansString.toString();
  }

  void buildCommandElement(String cmdString) {

    command = doc.createElement("command");
    appendTextChild(command, cmdString);
    root.appendChild(command);
  }

  void buildOrderElement(String orderString) {

    order = doc.createElement("order");

    // Temporary compatibility hack
    appendTextChild(order, buildCompatibleOrderString(orderString));

    root.appendChild(order);
  }

  void buildTargetsElement(String targetString) {

    targets = doc.createElement("targets");
    appendTextChild(targets, targetString);
    root.appendChild(targets);

  }

  void buildLifetime(long lifetime) {

    buildLifetime(Long.toString(lifetime));
  }

  void buildLifetime(String lifetimeString) {

    lifetime = doc.createElement("lifetime");
    appendTextChild(lifetime, lifetimeString);
    root.appendChild(lifetime);
  }

  void buildBase64() {

    base64 = doc.createElement("base64");
    appendTextChild(base64, "1");
    root.appendChild(base64);
  }

  void buildVersion() {

    version = doc.createElement("version");
    appendTextChild(version, "4");
    root.appendChild(version);
  }

  public DocumentFragment getFragment() {

    return fragment;
  }

  public void groupCommand(String groupName) {

    buildCommandElement("G" + groupName);
  }

  public void roleCommand(String roleName) {

    buildCommandElement("R" + roleName);

  }

  public void mappingCommand(String groupName, String roleName) {

    buildCommandElement("B" + groupName + ":" + roleName);

  }

  public void allCommand() {

    buildCommandElement("A");
  }

  public void listCommand() {

    buildCommandElement("N");
  }
}


text:
import {Component, Input, style, state, trigger, transition, animate} from '@angular/core';
import {AccordionComponent} from './accordion.component';

const animationTime = 300;

@Component({
    selector: 'sc-accord',
    template: `

                {{title}}

                    <ng-content></ng-content>

    `,
    animations: [
        trigger('anim', [
            state('open', style({height: '*'})),
            state('closed', style({height: 0})),
            transition('closed <=> open', animate(`${animationTime}ms ease-in-out`))
        ])
    ],
    styles:  [`
        .bar {
            width: 100%;
            height: 50px;
            border-bottom: 1px solid rgba(0, 0, 0, 0.12);
            border-top: 1px solid rgba(0, 0, 0, 0.12);
            cursor: pointer;
            background: #fff;
            user-select: none;
            -webkit-touch-callout: none;
            -webkit-user-select: none;
            -moz-user-select: none
        }

        span {
            line-height: 50px;
            padding: 0 1rem;
            font-size: 1.1rem;
            text-transform: uppercase;
        }

        .inner {
            display: block;
            background: #F6F6F6;
        }

        .inner.closed {
            overflow: hidden;
        }

        .pad {
            padding: 0.5rem 1rem;
        }
    `]
})

export class AccordComponent {

    @Input() title: string = 'Accord';
    @Input() locked: boolean = false;
    @Input() set active(act: boolean) {
        this.act = act;
        this.hasOverflow = !act;
        this.inner = act ? 'open' : 'closed';
    };

    act: boolean = false;
    inner: string = 'closed';
    hasOverflow: boolean = true;

    trigger() {
        this.hasOverflow = true;
        setTimeout(() => this.hasOverflow = this.inner === 'closed', animationTime);
        this.accordionComp.trigger(this);
    }

    constructor(
        private accordionComp: AccordionComponent
    ) {
        accordionComp.addAccord(this);
    }
}


text:
#import "NSObject.h"

#import "PSSettingsBoolDetail-Protocol.h"

@interface PSInvertColorsSettingsDetail : NSObject <PSSettingsBoolDetail>
{
}

+ (_Bool)isEnabled;
+ (void)setEnabled:(_Bool)arg1;
+ (id)iconImage;
+ (id)preferencesURL;

@end