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

import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import './print_preview_vars_css.js';
import '../strings.m.js';
import '../data/document_info.js';
import './sidebar.js';

import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js';
import {assert} from 'chrome://resources/js/assert_ts.js';
import {isMac, isWindows} from 'chrome://resources/js/cr.m.js';
import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js';
import {EventTracker} from 'chrome://resources/js/event_tracker.m.js';
import {hasKeyModifiers} from 'chrome://resources/js/util.m.js';
import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js';
import {PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {CloudPrintInterface, CloudPrintInterfaceErrorEventDetail, CloudPrintInterfaceEventType} from '../cloud_print_interface.js';
import {CloudPrintInterfaceImpl} from '../cloud_print_interface_impl.js';
import {Destination} from '../data/destination.js';
// <if expr="chromeos_ash or chromeos_lacros">
import {DestinationOrigin} from '../data/destination.js';
// </if>
import {getPrinterTypeForDestination, PrinterType} from '../data/destination_match.js';
import {DocumentSettings, PrintPreviewDocumentInfoElement} from '../data/document_info.js';
import {Margins} from '../data/margins.js';
import {MeasurementSystem} from '../data/measurement_system.js';
import {DuplexMode, PrintPreviewModelElement, whenReady} from '../data/model.js';
import {PrintableArea} from '../data/printable_area.js';
import {Size} from '../data/size.js';
import {Error, PrintPreviewStateElement, State} from '../data/state.js';
import {MetricsContext, PrintPreviewInitializationEvents} from '../metrics.js';
import {NativeInitialSettings, NativeLayer, NativeLayerImpl} from '../native_layer.js';
// <if expr="chromeos_ash or chromeos_lacros">
import {NativeLayerCros, NativeLayerCrosImpl} from '../native_layer_cros.js';
// </if>

import {getTemplate} from './app.html.js';
import {DestinationState} from './destination_settings.js';
import {PreviewAreaState, PrintPreviewPreviewAreaElement} from './preview_area.js';
import {SettingsMixin} from './settings_mixin.js';
import {PrintPreviewSidebarElement} from './sidebar.js';

export interface PrintPreviewAppElement {
  $: {
    documentInfo: PrintPreviewDocumentInfoElement,
    model: PrintPreviewModelElement,
    previewArea: PrintPreviewPreviewAreaElement,
    sidebar: PrintPreviewSidebarElement,
    state: PrintPreviewStateElement,
  };
}

const PrintPreviewAppElementBase =
    WebUIListenerMixin(SettingsMixin(PolymerElement));

export class PrintPreviewAppElement extends PrintPreviewAppElementBase {
  static get is() {
    return 'print-preview-app';
  }

  static get template() {
    return getTemplate();
  }

  static get properties() {
    return {
      state: {
        type: Number,
        observer: 'onStateChanged_',
      },

      cloudPrintErrorMessage_: String,

      cloudPrintInterface_: Object,

      controlsManaged_: {
        type: Boolean,
        computed: 'computeControlsManaged_(destinationsManaged_, ' +
            'settingsManaged_, maxSheets_)',
      },

      destination_: Object,

      destinationsManaged_: {
        type: Boolean,
        value: false,
      },

      destinationState_: {
        type: Number,
        observer: 'onDestinationStateChange_',
      },

      documentSettings_: Object,

      error_: Number,

      margins_: Object,

      pageSize_: Object,

      previewState_: {
        type: String,
        observer: 'onPreviewStateChange_',
      },

      printableArea_: Object,

      settingsManaged_: {
        type: Boolean,
        value: false,
      },

      measurementSystem_: {
        type: Object,
        value: null,
      },

      maxSheets_: Number,
    };
  }

  state: State;
  private cloudPrintErrorMessage_: string;
  private cloudPrintInterface_: CloudPrintInterface;
  private controlsManaged_: boolean;
  private destination_: Destination;
  private destinationsManaged_: boolean;
  private destinationState_: DestinationState;
  private documentSettings_: DocumentSettings;
  private error_: Error;
  private margins_: Margins;
  private pageSize_: Size;
  private previewState_: PreviewAreaState;
  private printableArea_: PrintableArea;
  private settingsManaged_: boolean;
  private measurementSystem_: MeasurementSystem|null;
  private maxSheets_: number;

  private nativeLayer_: NativeLayer|null = null;
  // <if expr="chromeos_ash or chromeos_lacros">
  private nativeLayerCros_: NativeLayerCros|null = null;
  // </if>
  private tracker_: EventTracker = new EventTracker();
  private cancelled_: boolean = false;
  private printRequested_: boolean = false;
  private startPreviewWhenReady_: boolean = false;
  private showSystemDialogBeforePrint_: boolean = false;
  private openPdfInPreview_: boolean = false;
  private isInKioskAutoPrintMode_: boolean = false;
  private whenReady_: Promise<void>|null = null;
  private openDialogs_: CrDialogElement[] = [];

  constructor() {
    super();

    // Regular expression that captures the leading slash, the content and the
    // trailing slash in three different groups.
    const CANONICAL_PATH_REGEX = /(^\/)([\/-\w]+)(\/$)/;
    const path = location.pathname.replace(CANONICAL_PATH_REGEX, '$1$2');
    if (path !== '/') {  // There are no subpages in Print Preview.
      window.history.replaceState(undefined /* stateObject */, '', '/');
    }
  }

  override ready() {
    super.ready();

    FocusOutlineManager.forDocument(document);
  }

  override connectedCallback() {
    super.connectedCallback();

    document.documentElement.classList.remove('loading');
    this.nativeLayer_ = NativeLayerImpl.getInstance();
    // <if expr="chromeos_ash or chromeos_lacros">
    this.nativeLayerCros_ = NativeLayerCrosImpl.getInstance();
    // </if>
    this.addWebUIListener('cr-dialog-open', this.onCrDialogOpen_.bind(this));
    this.addWebUIListener('close', this.onCrDialogClose_.bind(this));
    this.addWebUIListener('print-failed', this.onPrintFailed_.bind(this));
    this.addWebUIListener(
        'print-preset-options', this.onPrintPresetOptions_.bind(this));
    this.tracker_.add(window, 'keydown', this.onKeyDown_.bind(this));
    this.$.previewArea.setPluginKeyEventCallback(this.onKeyDown_.bind(this));
    this.whenReady_ = whenReady();
    this.nativeLayer_.getInitialSettings().then(
        this.onInitialSettingsSet_.bind(this));
    MetricsContext.getInitialSettings().record(
        PrintPreviewInitializationEvents.FUNCTION_INITIATED);
  }

  override disconnectedCallback() {
    super.disconnectedCallback();

    this.tracker_.removeAll();
    this.whenReady_ = null;
  }

  private onSidebarFocus_() {
    this.$.previewArea.hideToolbar();
  }

  /**
   * Consume escape and enter key presses and ctrl + shift + p. Delegate
   * everything else to the preview area.
   */
  private onKeyDown_(e: KeyboardEvent) {
    // Escape key closes the topmost dialog that is currently open within
    // Print Preview. If no such dialog exists, then the Print Preview dialog
    // itself is closed.
    if (e.key === 'Escape' && !hasKeyModifiers(e)) {
      // Don't close the Print Preview dialog if there is a child dialog open.
      if (this.openDialogs_.length !== 0) {
        // Manually cancel the dialog, since we call preventDefault() to prevent
        // views from closing the Print Preview dialog.
        const dialogToClose = this.openDialogs_[this.openDialogs_.length - 1];
        dialogToClose.cancel();
        e.preventDefault();
        return;
      }

      // On non-mac with toolkit-views, ESC key is handled by C++-side instead
      // of JS-side.
      if (isMac) {
        this.close_();
        e.preventDefault();
      }

      // <if expr="chromeos_ash or chromeos_lacros">
      if (this.destination_ &&
          this.destination_.origin === DestinationOrigin.CROS) {
        this.nativeLayerCros_!.recordPrinterStatusHistogram(
            this.destination_.printerStatusReason, false);
      }
      // </if>
      return;
    }

    // On Mac, Cmd+Period should close the print dialog.
    if (isMac && e.key === '.' && e.metaKey) {
      this.close_();
      e.preventDefault();
      return;
    }

    // Ctrl + Shift + p / Mac equivalent. Doesn't apply on Chrome OS.
    // On Linux/Windows, shift + p means that e.key will be 'P' with caps lock
    // off or 'p' with caps lock on.
    // On Mac, alt + p means that e.key will be unicode 03c0 (pi).
    // <if expr="not chromeos and not lacros">
    if (e.key === 'P' || e.key === 'p' || e.key === '\u03c0') {
      if ((isMac && e.metaKey && e.altKey && !e.shiftKey && !e.ctrlKey) ||
          (!isMac && e.shiftKey && e.ctrlKey && !e.altKey && !e.metaKey)) {
        // Don't use system dialog if the link isn't available.
        if (!this.$.sidebar.systemDialogLinkAvailable()) {
          return;
        }

        // Don't try to print with system dialog on Windows if the document is
        // not ready, because we send the preview document to the printer on
        // Windows.
        if (!isWindows || this.state === State.READY) {
          this.onPrintWithSystemDialog_();
        }
        e.preventDefault();
        return;
      }
    }
    // </if>

    if ((e.key === 'Enter' || e.key === 'NumpadEnter') &&
        this.state === State.READY && this.openDialogs_.length === 0) {
      const activeElementTag = (e.composedPath()[0] as HTMLElement).tagName;
      if (['CR-BUTTON', 'BUTTON', 'SELECT', 'A', 'CR-CHECKBOX'].includes(
              activeElementTag)) {
        return;
      }

      this.onPrintRequested_();
      e.preventDefault();
      return;
    }

    // Pass certain directional keyboard events to the PDF viewer.
    this.$.previewArea.handleDirectionalKeyEvent(e);
  }

  private onCrDialogOpen_(e: Event) {
    this.openDialogs_.push(e.composedPath()[0] as CrDialogElement);
  }

  private onCrDialogClose_(e: Event) {
    // Note: due to event re-firing in cr_dialog.js, this event will always
    // appear to be coming from the outermost child dialog.
    // TODO(rbpotter): Fix event re-firing so that the event comes from the
    // dialog that has been closed, and add an assertion that the removed
    // dialog matches e.composedPath()[0].
    if ((e.composedPath()[0] as HTMLElement).nodeName === 'CR-DIALOG') {
      this.openDialogs_.pop();
    }
  }

  private onInitialSettingsSet_(settings: NativeInitialSettings) {
    MetricsContext.getInitialSettings().record(
        PrintPreviewInitializationEvents.FUNCTION_SUCCESSFUL);
    if (!this.whenReady_) {
      // This element and its corresponding model were detached while waiting
      // for the callback. This can happen in tests; return early.
      return;
    }
    this.whenReady_.then(() => {
      // The cloud print interface should be initialized before initializing the
      // sidebar, so that cloud printers can be selected automatically.
      if (settings.cloudPrintURL) {
        this.initializeCloudPrint_(
            settings.cloudPrintURL, settings.isInAppKioskMode,
            settings.uiLocale);
      }
      this.$.documentInfo.init(
          settings.previewModifiable, settings.previewIsFromArc,
          settings.documentTitle, settings.documentHasSelection);
      this.$.model.setStickySettings(settings.serializedAppStateStr);
      this.$.model.setPolicySettings(settings.policies);
      this.measurementSystem_ = new MeasurementSystem(
          settings.thousandsDelimiter, settings.decimalDelimiter,
          settings.unitType);
      this.setSetting('selectionOnly', settings.shouldPrintSelectionOnly);
      this.$.sidebar.init(
          settings.isInAppKioskMode, settings.printerName,
          settings.serializedDefaultDestinationSelectionRulesStr,
          settings.pdfPrinterDisabled, settings.isDriveMounted || false);
      this.destinationsManaged_ = settings.destinationsManaged;
      this.isInKioskAutoPrintMode_ = settings.isInKioskAutoPrintMode;

      // This is only visible in the task manager.
      let title = document.head.querySelector('title');
      if (!title) {
        title = document.createElement('title');
        document.head.appendChild(title);
      }
      title.textContent = settings.documentTitle;
    });
  }

  /**
   * Called when Google Cloud Print integration is enabled.
   * @param cloudPrintUrl The URL to use for cloud print servers.
   * @param appKioskMode Whether the browser is in app kiosk mode.
   * @param uiLocale The UI locale.
   */
  private initializeCloudPrint_(
      cloudPrintUrl: string, appKioskMode: boolean, uiLocale: string) {
    assert(!this.cloudPrintInterface_);
    this.cloudPrintInterface_ = CloudPrintInterfaceImpl.getInstance();
    this.cloudPrintInterface_.configure(cloudPrintUrl, appKioskMode, uiLocale);
    this.tracker_.add(
        this.cloudPrintInterface_.getEventTarget(),
        CloudPrintInterfaceEventType.SUBMIT_DONE, this.close_.bind(this));
    this.tracker_.add(
        this.cloudPrintInterface_.getEventTarget(),
        CloudPrintInterfaceEventType.SUBMIT_FAILED,
        this.onCloudPrintError_.bind(this, appKioskMode));
  }

  /**
   * @return Whether any of the print preview settings or destinations
   *     are managed.
   */
  private computeControlsManaged_(): boolean {
    // If |this.maxSheets_| equals to 0, no sheets limit policy is present.
    return this.destinationsManaged_ || this.settingsManaged_ ||
        this.maxSheets_ > 0;
  }

  private onDestinationStateChange_() {
    switch (this.destinationState_) {
      case DestinationState.SELECTED:
      case DestinationState.SET:
        if (this.state !== State.NOT_READY &&
            this.state !== State.FATAL_ERROR) {
          this.$.state.transitTo(State.NOT_READY);
        }
        break;
      case DestinationState.UPDATED:
        if (!this.$.model.initialized()) {
          this.$.model.applyStickySettings();
        }

        this.$.model.applyDestinationSpecificPolicies();

        this.startPreviewWhenReady_ = true;
        this.$.state.transitTo(State.READY);
        break;
      case DestinationState.ERROR:
        let newState = State.ERROR;
        // <if expr="chromeos_ash or chromeos_lacros">
        if (this.error_ === Error.NO_DESTINATIONS) {
          newState = State.FATAL_ERROR;
        }
        // </if>
        this.$.state.transitTo(newState);
        break;
      default:
        break;
    }
  }

  /**
   * @param e Event containing the new sticky settings.
   */
  private onStickySettingChanged_(e: CustomEvent<string>) {
    this.nativeLayer_!.saveAppState(e.detail);
  }

  private onPreviewSettingChanged_() {
    if (this.state === State.READY) {
      this.$.previewArea.startPreview(false);
      this.startPreviewWhenReady_ = false;
    } else {
      this.startPreviewWhenReady_ = true;
    }
  }

  private onStateChanged_() {
    if (this.state === State.READY) {
      if (this.startPreviewWhenReady_) {
        this.$.previewArea.startPreview(false);
        this.startPreviewWhenReady_ = false;
      }
      if (this.isInKioskAutoPrintMode_ || this.printRequested_) {
        this.onPrintRequested_();
        // Reset in case printing fails.
        this.printRequested_ = false;
      }
    } else if (this.state === State.CLOSING) {
      this.remove();
      this.nativeLayer_!.dialogClose(this.cancelled_);
    } else if (this.state === State.HIDDEN) {
      if (this.destination_.isLocal &&
          getPrinterTypeForDestination(this.destination_) !==
              PrinterType.PDF_PRINTER) {
        // Only hide the preview for local, non PDF destinations.
        this.nativeLayer_!.hidePreview();
      }
    } else if (this.state === State.PRINTING) {
      const whenPrintDone =
          this.nativeLayer_!.print(this.$.model.createPrintTicket(
              this.destination_, this.openPdfInPreview_,
              this.showSystemDialogBeforePrint_));
      if (this.destination_.isLocal) {
        const onError = getPrinterTypeForDestination(this.destination_) ===
                PrinterType.PDF_PRINTER ?
            this.onFileSelectionCancel_.bind(this) :
            this.onPrintFailed_.bind(this);
        whenPrintDone.then(this.close_.bind(this), onError);
      } else {
        // Cloud print resolves when print data is returned to submit to cloud
        // print, or if print ticket cannot be read, no PDF data is found, or
        // PDF is oversized.
        whenPrintDone.then(
            data => this.onPrintToCloud_(data!),
            this.onPrintFailed_.bind(this));
      }
    }
  }

  private onPrintRequested_() {
    if (this.state === State.NOT_READY) {
      this.printRequested_ = true;
      return;
    }
    // <if expr="chromeos_ash or chromeos_lacros">
    if (this.destination_ &&
        this.destination_.origin === DestinationOrigin.CROS) {
      this.nativeLayerCros_!.recordPrinterStatusHistogram(
          this.destination_.printerStatusReason, true);
    }
    // </if>
    this.$.state.transitTo(
        this.$.previewArea.previewLoaded() ? State.PRINTING : State.HIDDEN);
  }

  private onCancelRequested_() {
    // <if expr="chromeos_ash or chromeos_lacros">
    if (this.destination_ &&
        this.destination_.origin === DestinationOrigin.CROS) {
      this.nativeLayerCros_!.recordPrinterStatusHistogram(
          this.destination_.printerStatusReason, false);
    }
    // </if>
    this.cancelled_ = true;
    this.$.state.transitTo(State.CLOSING);
  }

  /**
   * @param e The event containing the new validity.
   */
  private onSettingValidChanged_(e: CustomEvent<boolean>) {
    if (e.detail) {
      this.$.state.transitTo(State.READY);
    } else {
      this.error_ = Error.INVALID_TICKET;
      this.$.state.transitTo(State.ERROR);
    }
  }

  private onFileSelectionCancel_() {
    this.$.state.transitTo(State.READY);
  }

  /**
   * Called when the native layer has retrieved the data to print to Google
   * Cloud Print.
   * @param data The body to send in the HTTP request.
   */
  private onPrintToCloud_(data: string) {
    assert(
        this.cloudPrintInterface_ !== null,
        'Google Cloud Print is not enabled');
    this.cloudPrintInterface_.submit(
        this.destination_, this.$.model.createCloudJobTicket(this.destination_),
        this.documentSettings_.title, data);
  }

  // <if expr="not chromeos and not lacros">
  private onPrintWithSystemDialog_() {
    // <if expr="is_win">
    this.showSystemDialogBeforePrint_ = true;
    this.onPrintRequested_();
    // </if>
    // <if expr="not is_win">
    this.nativeLayer_!.showSystemDialog();
    this.$.state.transitTo(State.SYSTEM_DIALOG);
    // </if>
  }
  // </if>

  // <if expr="is_macosx">
  private onOpenPdfInPreview_() {
    this.openPdfInPreview_ = true;
    this.$.previewArea.setOpeningPdfInPreview();
    this.onPrintRequested_();
  }
  // </if>

  /**
   * Called when printing to a cloud, or extension printer fails.
   * @param httpError The HTTP error code, or -1 or a string describing
   *     the error, if not an HTTP error.
   */
  private onPrintFailed_(httpError: number|string) {
    console.warn('Printing failed with error code ' + httpError);
    this.error_ = Error.PRINT_FAILED;
    this.$.state.transitTo(State.FATAL_ERROR);
  }

  private onPreviewStateChange_() {
    switch (this.previewState_) {
      case PreviewAreaState.DISPLAY_PREVIEW:
      case PreviewAreaState.OPEN_IN_PREVIEW_LOADED:
        if (this.state === State.HIDDEN) {
          this.$.state.transitTo(State.PRINTING);
        }
        break;
      case PreviewAreaState.ERROR:
        if (this.state !== State.ERROR && this.state !== State.FATAL_ERROR) {
          this.$.state.transitTo(
              this.error_ === Error.INVALID_PRINTER ? State.ERROR :
                                                      State.FATAL_ERROR);
        }
        break;
      default:
        break;
    }
  }

  /**
   * Called when there was an error communicating with Google Cloud print.
   * Displays an error message in the print header.
   */
  private onCloudPrintError_(
      appKioskMode: boolean,
      event: CustomEvent<CloudPrintInterfaceErrorEventDetail>) {
    if (event.detail.status === 0 ||
        (event.detail.status === 403 && !appKioskMode)) {
      return;  // No internet connectivity or not signed in.
    }
    this.cloudPrintErrorMessage_ = event.detail.message;
    this.error_ = Error.CLOUD_PRINT_ERROR;
    this.$.state.transitTo(State.FATAL_ERROR);
    if (event.detail.status === 200) {
      console.warn(
          'Google Cloud Print Error: ' +
          `(${event.detail.errorCode}) ${event.detail.message}`);
    } else {
      console.warn(
          'Google Cloud Print Error: ' +
          `HTTP status ${event.detail.status}`);
    }
  }

  /**
   * Updates printing options according to source document presets.
   * @param disableScaling Whether the document disables scaling.
   * @param copies The default number of copies from the document.
   * @param duplex The default duplex setting from the document.
   */
  private onPrintPresetOptions_(
      disableScaling: boolean, copies: number, duplex: DuplexMode) {
    if (disableScaling) {
      this.$.documentInfo.updateIsScalingDisabled(true);
    }

    if (copies > 0 && this.getSetting('copies').available) {
      this.setSetting('copies', copies, true);
    }

    if (duplex === DuplexMode.UNKNOWN_DUPLEX_MODE) {
      return;
    }

    if (this.getSetting('duplex').available) {
      this.setSetting(
          'duplex',
          duplex === DuplexMode.LONG_EDGE || duplex === DuplexMode.SHORT_EDGE,
          true);
    }

    if (duplex !== DuplexMode.SIMPLEX &&
        this.getSetting('duplexShortEdge').available) {
      this.setSetting(
          'duplexShortEdge', duplex === DuplexMode.SHORT_EDGE, true);
    }
  }

  /**
   * @param e Contains the new preview request ID.
   */
  private onPreviewStart_(e: CustomEvent<number>) {
    this.$.documentInfo.inFlightRequestId = e.detail;
  }

  private close_() {
    this.$.state.transitTo(State.CLOSING);
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'print-preview-app': PrintPreviewAppElement;
  }
}

customElements.define(PrintPreviewAppElement.is, PrintPreviewAppElement);


text:
package com.epam.dlab.dto.aws;

import com.epam.dlab.dto.base.CloudSettings;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;

@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
public class AwsCloudSettings extends CloudSettings {

    @JsonProperty("aws_iam_user")
    private String awsIamUser;
    @JsonProperty("aws_region")
    private String awsRegion;
    @JsonProperty("aws_subnet_id")
    private String awsSubnetId;
    @JsonProperty("aws_security_groups_ids")
    private String awsSecurityGroupIds;
    @JsonProperty("aws_vpc_id")
    private String awsVpcId;
    @JsonProperty("conf_tag_resource_id")
    private String confTagResourceId;

    @Builder
    public AwsCloudSettings(String awsIamUser, String awsRegion, String awsSubnetId,
                            String awsSecurityGroupIds, String awsVpcId, String confTagResourceId) {

        this.awsIamUser = awsIamUser;
        this.awsRegion = awsRegion;
        this.awsSubnetId = awsSubnetId;
        this.awsSecurityGroupIds = awsSecurityGroupIds;
        this.awsVpcId = awsVpcId;
        this.confTagResourceId = confTagResourceId;
    }

    @Override
    @JsonIgnore
    public String getIamUser() {
        return awsIamUser;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"

/** @addtogroup STM32F1xx_HAL_Driver
  * @{
  */

#ifdef HAL_NAND_MODULE_ENABLED

#if defined (STM32F101xE) || defined(STM32F103xE) || defined(STM32F101xG) || defined(STM32F103xG)

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

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup NAND_Private_Constants NAND Private Constants
  * @{
  */

/**
  * @}
  */

/* Private macro -------------------------------------------------------------*/
/** @defgroup NAND_Private_Macros NAND Private Macros
  * @{
  */

/**
  * @}
  */

/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup NAND_Private_Functions NAND Private Functions
  * @{
  */
static uint32_t NAND_AddressIncrement(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef* Address);
/**
  * @}
  */

/* Exported functions ---------------------------------------------------------*/

/** @defgroup NAND_Exported_Functions NAND Exported Functions
  * @{
  */

/** @defgroup NAND_Exported_Functions_Group1 Initialization and de-initialization functions
  * @brief    Initialization and Configuration functions
  *
  @verbatim
  ==============================================================================
            ##### NAND Initialization and de-initialization functions #####
  ==============================================================================
  [..]
    This section provides functions allowing to initialize/de-initialize
    the NAND memory

@endverbatim
  * @{
  */

/**
  * @brief  Perform NAND memory Initialization sequence
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @param  ComSpace_Timing: pointer to Common space timing structure
  * @param  AttSpace_Timing: pointer to Attribute space timing structure
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_NAND_Init(NAND_HandleTypeDef *hnand, FSMC_NAND_PCC_TimingTypeDef *ComSpace_Timing, FSMC_NAND_PCC_TimingTypeDef *AttSpace_Timing)
{
  /* Check the NAND handle state */
  if(hnand == NULL)
  {
     return HAL_ERROR;
  }

  if(hnand->State == HAL_NAND_STATE_RESET)
  {
    /* Allocate lock resource and initialize it */
    hnand->Lock = HAL_UNLOCKED;

    /* Initialize the low level hardware (MSP) */
    HAL_NAND_MspInit(hnand);
  }

  /* Initialize NAND control Interface */
  FSMC_NAND_Init(hnand->Instance, &(hnand->Init));

  /* Initialize NAND common space timing Interface */
  FSMC_NAND_CommonSpace_Timing_Init(hnand->Instance, ComSpace_Timing, hnand->Init.NandBank);

  /* Initialize NAND attribute space timing Interface */
  FSMC_NAND_AttributeSpace_Timing_Init(hnand->Instance, AttSpace_Timing, hnand->Init.NandBank);

  /* Enable the NAND device */
  __FSMC_NAND_ENABLE(hnand->Instance, hnand->Init.NandBank);

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_READY;

  return HAL_OK;
}

/**
  * @brief  Perform NAND memory De-Initialization sequence
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_NAND_DeInit(NAND_HandleTypeDef *hnand)
{
  /* Initialize the low level hardware (MSP) */
  HAL_NAND_MspDeInit(hnand);

  /* Configure the NAND registers with their reset values */
  FSMC_NAND_DeInit(hnand->Instance, hnand->Init.NandBank);

  /* Reset the NAND controller state */
  hnand->State = HAL_NAND_STATE_RESET;

  /* Release Lock */
  __HAL_UNLOCK(hnand);

  return HAL_OK;
}

/**
  * @brief  NAND MSP Init
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @retval None
  */
__weak void HAL_NAND_MspInit(NAND_HandleTypeDef *hnand)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hnand);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_NAND_MspInit could be implemented in the user file
   */
}

/**
  * @brief  NAND MSP DeInit
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @retval None
  */
__weak void HAL_NAND_MspDeInit(NAND_HandleTypeDef *hnand)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hnand);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_NAND_MspDeInit could be implemented in the user file
   */
}

/**
  * @brief  This function handles NAND device interrupt request.
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @retval HAL status
*/
void HAL_NAND_IRQHandler(NAND_HandleTypeDef *hnand)
{
  /* Check NAND interrupt Rising edge flag */
  if(__FSMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FSMC_FLAG_RISING_EDGE))
  {
    /* NAND interrupt callback*/
    HAL_NAND_ITCallback(hnand);

    /* Clear NAND interrupt Rising edge pending bit */
    __FSMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FSMC_FLAG_RISING_EDGE);
  }

  /* Check NAND interrupt Level flag */
  if(__FSMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FSMC_FLAG_LEVEL))
  {
    /* NAND interrupt callback*/
    HAL_NAND_ITCallback(hnand);

    /* Clear NAND interrupt Level pending bit */
    __FSMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FSMC_FLAG_LEVEL);
  }

  /* Check NAND interrupt Falling edge flag */
  if(__FSMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FSMC_FLAG_FALLING_EDGE))
  {
    /* NAND interrupt callback*/
    HAL_NAND_ITCallback(hnand);

    /* Clear NAND interrupt Falling edge pending bit */
    __FSMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FSMC_FLAG_FALLING_EDGE);
  }

  /* Check NAND interrupt FIFO empty flag */
  if(__FSMC_NAND_GET_FLAG(hnand->Instance, hnand->Init.NandBank, FSMC_FLAG_FEMPT))
  {
    /* NAND interrupt callback*/
    HAL_NAND_ITCallback(hnand);

    /* Clear NAND interrupt FIFO empty pending bit */
    __FSMC_NAND_CLEAR_FLAG(hnand->Instance, hnand->Init.NandBank, FSMC_FLAG_FEMPT);
  }

}

/**
  * @brief  NAND interrupt feature callback
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @retval None
  */
__weak void HAL_NAND_ITCallback(NAND_HandleTypeDef *hnand)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(hnand);
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_NAND_ITCallback could be implemented in the user file
   */
}

/**
  * @}
  */

/** @defgroup NAND_Exported_Functions_Group2 Input and Output functions
  * @brief    Input Output and memory control functions
  *
  @verbatim
  ==============================================================================
                    ##### NAND Input and Output functions #####
  ==============================================================================
  [..]
    This section provides functions allowing to use and control the NAND
    memory

@endverbatim
  * @{
  */

/**
  * @brief  Read the NAND memory electronic signature
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @param  pNAND_ID: NAND ID structure
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_NAND_Read_ID(NAND_HandleTypeDef *hnand, NAND_IDTypeDef *pNAND_ID)
{
  __IO uint32_t data = 0;
  uint32_t deviceaddress = 0;

  /* Process Locked */
  __HAL_LOCK(hnand);

  /* Check the NAND controller state */
  if(hnand->State == HAL_NAND_STATE_BUSY)
  {
     return HAL_BUSY;
  }

  /* Identify the device address */
  if(hnand->Init.NandBank == FSMC_NAND_BANK2)
  {
    deviceaddress = NAND_DEVICE1;
  }
  else
  {
    deviceaddress = NAND_DEVICE2;
  }

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_BUSY;

  /* Send Read ID command sequence */
  *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA))  = NAND_CMD_READID;
  *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00;

  /* Read the electronic signature from NAND flash */
  data = *(__IO uint32_t *)deviceaddress;

  /* Return the data read */
  pNAND_ID->Maker_Id   = ADDR_1st_CYCLE(data);
  pNAND_ID->Device_Id  = ADDR_2nd_CYCLE(data);
  pNAND_ID->Third_Id   = ADDR_3rd_CYCLE(data);
  pNAND_ID->Fourth_Id  = ADDR_4th_CYCLE(data);

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_READY;

  /* Process unlocked */
  __HAL_UNLOCK(hnand);

  return HAL_OK;
}

/**
  * @brief  NAND memory reset
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_NAND_Reset(NAND_HandleTypeDef *hnand)
{
  uint32_t deviceaddress = 0;

  /* Process Locked */
  __HAL_LOCK(hnand);

  /* Check the NAND controller state */
  if(hnand->State == HAL_NAND_STATE_BUSY)
  {
     return HAL_BUSY;
  }

  /* Identify the device address */
  if(hnand->Init.NandBank == FSMC_NAND_BANK2)
  {
    deviceaddress = NAND_DEVICE1;
  }
  else
  {
    deviceaddress = NAND_DEVICE2;
  }

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_BUSY;

  /* Send NAND reset command */
  *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = 0xFF;

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_READY;

  /* Process unlocked */
  __HAL_UNLOCK(hnand);

  return HAL_OK;

}

/**
  * @brief  Read Page(s) from NAND memory block
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @param  pAddress : pointer to NAND address structure
  * @param  pBuffer : pointer to destination read buffer
  * @param  NumPageToRead : number of pages to read from block
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_NAND_Read_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToRead)
{
  __IO uint32_t index  = 0;
  uint32_t deviceaddress = 0, size = 0, numpagesread = 0, addressstatus = NAND_VALID_ADDRESS;
  NAND_AddressTypeDef nandaddress;
  uint32_t addressoffset = 0;

  /* Process Locked */
  __HAL_LOCK(hnand);

  /* Check the NAND controller state */
  if(hnand->State == HAL_NAND_STATE_BUSY)
  {
     return HAL_BUSY;
  }

  /* Identify the device address */
  if(hnand->Init.NandBank == FSMC_NAND_BANK2)
  {
    deviceaddress = NAND_DEVICE1;
  }
  else
  {
    deviceaddress = NAND_DEVICE2;
  }

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_BUSY;

  /* Save the content of pAddress as it will be modified */
  nandaddress.Block     = pAddress->Block;
  nandaddress.Page      = pAddress->Page;
  nandaddress.Zone      = pAddress->Zone;

  /* Page(s) read loop */
  while((NumPageToRead != 0) && (addressstatus == NAND_VALID_ADDRESS))
  {
    /* update the buffer size */
    size = hnand->Info.PageSize + ((hnand->Info.PageSize) * numpagesread);

    /* Get the address offset */
    addressoffset = ARRAY_ADDRESS(&nandaddress, hnand);

    /* Send read page command sequence */
    *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A;

    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00;
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1st_CYCLE(addressoffset);
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2nd_CYCLE(addressoffset);
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3rd_CYCLE(addressoffset);

    /* for 512 and 1 GB devices, 4th cycle is required */
    if(hnand->Info.BlockNbr >= 1024)
    {
      *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_4th_CYCLE(addressoffset);
    }

    *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA))  = NAND_CMD_AREA_TRUE1;

    /* Get Data into Buffer */
    for(; index < size; index++)
    {
      *(uint8_t *)pBuffer++ = *(uint8_t *)deviceaddress;
    }

    /* Increment read pages number */
    numpagesread++;

    /* Decrement pages to read */
    NumPageToRead--;

    /* Increment the NAND address */
    addressstatus = NAND_AddressIncrement(hnand, &nandaddress);
  }

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_READY;

  /* Process unlocked */
  __HAL_UNLOCK(hnand);

  return HAL_OK;

}

/**
  * @brief  Write Page(s) to NAND memory block
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @param  pAddress : pointer to NAND address structure
  * @param  pBuffer : pointer to source buffer to write
  * @param  NumPageToWrite  : number of pages to write to block
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_NAND_Write_Page(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumPageToWrite)
{
  __IO uint32_t index   = 0;
  uint32_t tickstart = 0;
  uint32_t deviceaddress = 0 , size = 0, numpageswritten = 0, addressstatus = NAND_VALID_ADDRESS;
  NAND_AddressTypeDef nandaddress;
  uint32_t addressoffset = 0;

  /* Process Locked */
  __HAL_LOCK(hnand);

  /* Check the NAND controller state */
  if(hnand->State == HAL_NAND_STATE_BUSY)
  {
     return HAL_BUSY;
  }

  /* Identify the device address */
  if(hnand->Init.NandBank == FSMC_NAND_BANK2)
  {
    deviceaddress = NAND_DEVICE1;
  }
  else
  {
    deviceaddress = NAND_DEVICE2;
  }

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_BUSY;

  /* Save the content of pAddress as it will be modified */
  nandaddress.Block     = pAddress->Block;
  nandaddress.Page      = pAddress->Page;
  nandaddress.Zone      = pAddress->Zone;

  /* Page(s) write loop */
  while((NumPageToWrite != 0) && (addressstatus == NAND_VALID_ADDRESS))
  {
    /* update the buffer size */
    size = hnand->Info.PageSize + ((hnand->Info.PageSize) * numpageswritten);

    /* Get the address offset */
    addressoffset = ARRAY_ADDRESS(&nandaddress, hnand);

    /* Send write page command sequence */
    *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_A;
    *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0;

    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00;
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1st_CYCLE(addressoffset);
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2nd_CYCLE(addressoffset);
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3rd_CYCLE(addressoffset);

    /* for 512 and 1 GB devices, 4th cycle is required */
    if(hnand->Info.BlockNbr >= 1024)
    {
      *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_4th_CYCLE(addressoffset);
    }

    /* Write data to memory */
    for(; index < size; index++)
    {
      *(__IO uint8_t *)deviceaddress = *(uint8_t *)pBuffer++;
    }

    *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1;

    /* Get tick */
    tickstart = HAL_GetTick();

    /* Read status until NAND is ready */
    while(HAL_NAND_Read_Status(hnand) != NAND_READY)
    {
      if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
      {
        return HAL_TIMEOUT;
      }
    }

    /* Increment written pages number */
    numpageswritten++;

    /* Decrement pages to write */
    NumPageToWrite--;

    /* Increment the NAND address */
    addressstatus = NAND_AddressIncrement(hnand, &nandaddress);
  }

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_READY;

  /* Process unlocked */
  __HAL_UNLOCK(hnand);

  return HAL_OK;
}

/**
  * @brief  Read Spare area(s) from NAND memory
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @param  pAddress : pointer to NAND address structure
  * @param  pBuffer: pointer to source buffer to write
  * @param  NumSpareAreaToRead: Number of spare area to read
  * @retval HAL status
*/
HAL_StatusTypeDef HAL_NAND_Read_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaToRead)
{
  __IO uint32_t index   = 0;
  uint32_t deviceaddress = 0, size = 0, num_spare_area_read = 0, addressstatus = NAND_VALID_ADDRESS;
  NAND_AddressTypeDef nandaddress;
  uint32_t addressoffset = 0;

  /* Process Locked */
  __HAL_LOCK(hnand);

  /* Check the NAND controller state */
  if(hnand->State == HAL_NAND_STATE_BUSY)
  {
     return HAL_BUSY;
  }

  /* Identify the device address */
  if(hnand->Init.NandBank == FSMC_NAND_BANK2)
  {
    deviceaddress = NAND_DEVICE1;
  }
  else
  {
    deviceaddress = NAND_DEVICE2;
  }

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_BUSY;

  /* Save the content of pAddress as it will be modified */
  nandaddress.Block     = pAddress->Block;
  nandaddress.Page      = pAddress->Page;
  nandaddress.Zone      = pAddress->Zone;

  /* Spare area(s) read loop */
  while((NumSpareAreaToRead != 0) && (addressstatus == NAND_VALID_ADDRESS))
  {
    /* update the buffer size */
    size = (hnand->Info.SpareAreaSize) + ((hnand->Info.SpareAreaSize) * num_spare_area_read);

    /* Get the address offset */
    addressoffset = ARRAY_ADDRESS(&nandaddress, hnand);

    /* Send read spare area command sequence */
    *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C;

    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00;
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1st_CYCLE(addressoffset);
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2nd_CYCLE(addressoffset);
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3rd_CYCLE(addressoffset);

    /* for 512 and 1 GB devices, 4th cycle is required */
    if(hnand->Info.BlockNbr >= 1024)
    {
      *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_4th_CYCLE(addressoffset);
    }

    *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_TRUE1;

    /* Get Data into Buffer */
    for ( ;index < size; index++)
    {
      *(uint8_t *)pBuffer++ = *(uint8_t *)deviceaddress;
    }

    /* Increment read spare areas number */
    num_spare_area_read++;

    /* Decrement spare areas to read */
    NumSpareAreaToRead--;

    /* Increment the NAND address */
    addressstatus = NAND_AddressIncrement(hnand, &nandaddress);
  }

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_READY;

  /* Process unlocked */
  __HAL_UNLOCK(hnand);

  return HAL_OK;
}

/**
  * @brief  Write Spare area(s) to NAND memory
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @param  pAddress : pointer to NAND address structure
  * @param  pBuffer : pointer to source buffer to write
  * @param  NumSpareAreaTowrite  : number of spare areas to write to block
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_NAND_Write_SpareArea(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress, uint8_t *pBuffer, uint32_t NumSpareAreaTowrite)
{
  __IO uint32_t index = 0;
  uint32_t tickstart = 0;
  uint32_t deviceaddress = 0, size = 0, num_spare_area_written = 0, addressstatus = NAND_VALID_ADDRESS;
  NAND_AddressTypeDef nandaddress;
  uint32_t addressoffset = 0;

  /* Process Locked */
  __HAL_LOCK(hnand);

  /* Check the NAND controller state */
  if(hnand->State == HAL_NAND_STATE_BUSY)
  {
     return HAL_BUSY;
  }

  /* Identify the device address */
  if(hnand->Init.NandBank == FSMC_NAND_BANK2)
  {
    deviceaddress = NAND_DEVICE1;
  }
  else
  {
    deviceaddress = NAND_DEVICE2;
  }

  /* Update the FSMC_NAND controller state */
  hnand->State = HAL_NAND_STATE_BUSY;

  /* Save the content of pAddress as it will be modified */
  nandaddress.Block     = pAddress->Block;
  nandaddress.Page      = pAddress->Page;
  nandaddress.Zone      = pAddress->Zone;

  /* Spare area(s) write loop */
  while((NumSpareAreaTowrite != 0) && (addressstatus == NAND_VALID_ADDRESS))
  {
    /* update the buffer size */
    size = (hnand->Info.SpareAreaSize) + ((hnand->Info.SpareAreaSize) * num_spare_area_written);

    /* Get the address offset */
    addressoffset = ARRAY_ADDRESS(&nandaddress, hnand);

    /* Send write Spare area command sequence */
    *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_AREA_C;
    *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE0;

    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = 0x00;
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1st_CYCLE(addressoffset);
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2nd_CYCLE(addressoffset);
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3rd_CYCLE(addressoffset);

    /* for 512 and 1 GB devices, 4th cycle is required */
    if(hnand->Info.BlockNbr >= 1024)
    {
      *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_4th_CYCLE(addressoffset);
    }

    /* Write data to memory */
    for(; index < size; index++)
    {
      *(__IO uint8_t *)deviceaddress = *(uint8_t *)pBuffer++;
    }

    *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_WRITE_TRUE1;

    /* Get tick */
    tickstart = HAL_GetTick();

    /* Read status until NAND is ready */
    while(HAL_NAND_Read_Status(hnand) != NAND_READY)
    {
      if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
      {
        return HAL_TIMEOUT;
      }
    }

    /* Increment written spare areas number */
    num_spare_area_written++;

    /* Decrement spare areas to write */
    NumSpareAreaTowrite--;

    /* Increment the NAND address */
    addressstatus = NAND_AddressIncrement(hnand, &nandaddress);
  }

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_READY;

  /* Process unlocked */
  __HAL_UNLOCK(hnand);

  return HAL_OK;
}

/**
  * @brief  NAND memory Block erase
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @param  pAddress : pointer to NAND address structure
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_NAND_Erase_Block(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress)
{
  uint32_t deviceaddress = 0;
  uint32_t tickstart = 0;

  /* Process Locked */
  __HAL_LOCK(hnand);

  /* Check the NAND controller state */
  if(hnand->State == HAL_NAND_STATE_BUSY)
  {
     return HAL_BUSY;
  }

  /* Identify the device address */
  if(hnand->Init.NandBank == FSMC_NAND_BANK2)
  {
    deviceaddress = NAND_DEVICE1;
  }
  else
  {
    deviceaddress = NAND_DEVICE2;
  }

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_BUSY;

  /* Send Erase block command sequence */
  *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE0;

  *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_1st_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
  *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_2nd_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
  *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_3rd_CYCLE(ARRAY_ADDRESS(pAddress, hnand));

  /* for 512 and 1 GB devices, 4th cycle is required */
  if(hnand->Info.BlockNbr >= 1024)
  {
    *(__IO uint8_t *)((uint32_t)(deviceaddress | ADDR_AREA)) = ADDR_4th_CYCLE(ARRAY_ADDRESS(pAddress, hnand));
  }

  *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_ERASE1;

  /* Update the NAND controller state */
  hnand->State = HAL_NAND_STATE_READY;

  /* Get tick */
  tickstart = HAL_GetTick();

  /* Read status until NAND is ready */
  while(HAL_NAND_Read_Status(hnand) != NAND_READY)
  {
    if((HAL_GetTick() - tickstart ) > NAND_WRITE_TIMEOUT)
    {
      /* Process unlocked */
      __HAL_UNLOCK(hnand);

      return HAL_TIMEOUT;
    }
  }

  /* Process unlocked */
  __HAL_UNLOCK(hnand);

  return HAL_OK;
}

/**
  * @brief  NAND memory read status
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @retval NAND status
  */
uint32_t HAL_NAND_Read_Status(NAND_HandleTypeDef *hnand)
{
  uint32_t data = 0;
  uint32_t deviceaddress = 0;

  /* Identify the device address */
  if(hnand->Init.NandBank == FSMC_NAND_BANK2)
  {
    deviceaddress = NAND_DEVICE1;
  }
  else
  {
    deviceaddress = NAND_DEVICE2;
  }

  /* Send Read status operation command */
  *(__IO uint8_t *)((uint32_t)(deviceaddress | CMD_AREA)) = NAND_CMD_STATUS;

  /* Read status register data */
  data = *(__IO uint8_t *)deviceaddress;

  /* Return the status */
  if((data & NAND_ERROR) == NAND_ERROR)
  {
    return NAND_ERROR;
  }
  else if((data & NAND_READY) == NAND_READY)
  {
    return NAND_READY;
  }

  return NAND_BUSY;
}

/**
  * @brief  Increment the NAND memory address
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @param pAddress: pointer to NAND address structure
  * @retval The new status of the increment address operation. It can be:
  *           - NAND_VALID_ADDRESS: When the new address is valid address
  *           - NAND_INVALID_ADDRESS: When the new address is invalid address
  */
uint32_t HAL_NAND_Address_Inc(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef *pAddress)
{
  uint32_t status = NAND_VALID_ADDRESS;

  /* Increment page address */
  pAddress->Page++;

  /* Check NAND address is valid */
  if(pAddress->Page == hnand->Info.BlockSize)
  {
    pAddress->Page = 0;
    pAddress->Block++;

    if(pAddress->Block == hnand->Info.ZoneSize)
    {
      pAddress->Block = 0;
      pAddress->Zone++;

      if(pAddress->Zone == (hnand->Info.ZoneSize/ hnand->Info.BlockNbr))
      {
        status = NAND_INVALID_ADDRESS;
      }
    }
  }

  return (status);
}
/**
  * @}
  */

/** @defgroup NAND_Exported_Functions_Group3 Peripheral Control functions
 *  @brief   management functions
 *
@verbatim
  ==============================================================================
                         ##### NAND Control functions #####
  ==============================================================================
  [..]
    This subsection provides a set of functions allowing to control dynamically
    the NAND interface.

@endverbatim
  * @{
  */

/**
  * @brief  Enables dynamically NAND ECC feature.
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_NAND_ECC_Enable(NAND_HandleTypeDef *hnand)
{
  /* Check the NAND controller state */
  if(hnand->State == HAL_NAND_STATE_BUSY)
  {
     return HAL_BUSY;
  }

  /* Update the NAND state */
  hnand->State = HAL_NAND_STATE_BUSY;

  /* Enable ECC feature */
  FSMC_NAND_ECC_Enable(hnand->Instance, hnand->Init.NandBank);

  /* Update the NAND state */
  hnand->State = HAL_NAND_STATE_READY;

  return HAL_OK;
}

/**
  * @brief  Disables dynamically FSMC_NAND ECC feature.
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_NAND_ECC_Disable(NAND_HandleTypeDef *hnand)
{
  /* Check the NAND controller state */
  if(hnand->State == HAL_NAND_STATE_BUSY)
  {
     return HAL_BUSY;
  }

  /* Update the NAND state */
  hnand->State = HAL_NAND_STATE_BUSY;

  /* Disable ECC feature */
  FSMC_NAND_ECC_Disable(hnand->Instance, hnand->Init.NandBank);

  /* Update the NAND state */
  hnand->State = HAL_NAND_STATE_READY;

  return HAL_OK;
}

/**
  * @brief  Disables dynamically NAND ECC feature.
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @param  ECCval: pointer to ECC value
  * @param  Timeout: maximum timeout to wait
  * @retval HAL status
  */
HAL_StatusTypeDef  HAL_NAND_GetECC(NAND_HandleTypeDef *hnand, uint32_t *ECCval, uint32_t Timeout)
{
  HAL_StatusTypeDef status = HAL_OK;

  /* Check the NAND controller state */
  if(hnand->State == HAL_NAND_STATE_BUSY)
  {
     return HAL_BUSY;
  }

  /* Update the NAND state */
  hnand->State = HAL_NAND_STATE_BUSY;

  /* Get NAND ECC value */
  status = FSMC_NAND_GetECC(hnand->Instance, ECCval, hnand->Init.NandBank, Timeout);

  /* Update the NAND state */
  hnand->State = HAL_NAND_STATE_READY;

  return status;
}

/**
  * @}
  */

/** @defgroup NAND_Exported_Functions_Group4 Peripheral State functions
 *  @brief   Peripheral State functions
 *
@verbatim
  ==============================================================================
                         ##### NAND State functions #####
  ==============================================================================
  [..]
    This subsection permits to get in run-time the status of the NAND controller
    and the data flow.

@endverbatim
  * @{
  */

/**
  * @brief  return the NAND state
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @retval HAL state
  */
HAL_NAND_StateTypeDef HAL_NAND_GetState(NAND_HandleTypeDef *hnand)
{
  return hnand->State;
}

/**
  * @}
  */

/**
  * @}
  */

/** @addtogroup NAND_Private_Functions
  * @{
  */

/**
  * @brief  Increment the NAND memory address.
  * @param  hnand: pointer to a NAND_HandleTypeDef structure that contains
  *                the configuration information for NAND module.
  * @param  Address: address to be incremented.
  * @retval The new status of the increment address operation. It can be:
  *              - NAND_VALID_ADDRESS: When the new address is valid address
  *              - NAND_INVALID_ADDRESS: When the new address is invalid address
  */
static uint32_t NAND_AddressIncrement(NAND_HandleTypeDef *hnand, NAND_AddressTypeDef* Address)
{
  uint32_t status = NAND_VALID_ADDRESS;

  Address->Page++;

  if(Address->Page == hnand->Info.BlockSize)
  {
    Address->Page = 0;
    Address->Block++;

    if(Address->Block == hnand->Info.ZoneSize)
    {
      Address->Block = 0;
      Address->Zone++;

      if(Address->Zone == hnand->Info.BlockNbr)
      {
        status = NAND_INVALID_ADDRESS;
      }
    }
  }

  return (status);
}

/**
  * @}
  */

/**
  * @}
  */

#endif /* STM32F101xE || STM32F103xE || STM32F101xG || STM32F103xG */
#endif /* HAL_NAND_MODULE_ENABLED  */

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
package com.github.ac31007_group_8.quiz.student.controllers;

import com.github.ac31007_group_8.quiz.common.ParameterManager;
import com.github.ac31007_group_8.quiz.util.Init;
import com.github.ac31007_group_8.quiz.Database;
import static com.github.ac31007_group_8.quiz.Database.getConnection;
import com.github.ac31007_group_8.quiz.staff.controllers.QuizManager;
import com.github.ac31007_group_8.quiz.staff.models.QuizModel;
import com.github.ac31007_group_8.quiz.staff.store.QuizInfo;
import com.github.ac31007_group_8.quiz.staff.store.QuizInfoStudent;
import com.github.ac31007_group_8.quiz.staff.store.User;
import com.github.ac31007_group_8.quiz.student.models.StudentQuizModel;
import com.google.gson.Gson;
import java.sql.Connection;
import java.sql.SQLException;
import spark.Request;
import spark.Response;
import spark.TemplateEngine;
import spark.template.mustache.MustacheTemplateEngine;

import java.util.ArrayList;
import java.util.HashMap;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.exception.DataAccessException;
import org.jooq.impl.DSL;

import org.slf4j.LoggerFactory;

import static spark.Spark.*;

/**
 * @Deprecated
 * @author Callum N
 *
 * @author Vlad
 */

public class StudentQuizList {

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(QuizManager.class);

    public StudentQuizList(){

    }

    @Init
    public static void init() {
        get("/student/relevantQuizzes", StudentQuizList::sendRelevantQuizzes);//relevant to student. displayed when page visited

        get("/student/quizList/filter", StudentQuizList::getFilteredQuizList);

    }

    //SEND RELEVANT QUIZZES

    public static Object sendRelevantQuizzes(Request req, Response res){

        HashMap<String, Object> map = ParameterManager.getAllParameters(req);
        TemplateEngine eng = new MustacheTemplateEngine();

        User currentUser = (User)map.get("user");
        if (currentUser==null){
            LOGGER.error("impossible happened");
            res.status(401);
            return null ;
        }

        int studentId = currentUser.getUserid();

        Connection conn = Database.getConnection();
        StudentQuizModel sqm = new StudentQuizModel();

        try{

            //module list wants dslcontext
            QuizModel quizModel = new QuizModel();
            ArrayList<String> moduleNames = quizModel.getModuleList(DSL.using(conn, SQLDialect.MYSQL));
            map.put("allModules", moduleNames);

            //old getRelevantQuizzes wants connection :)
            ArrayList<QuizInfoStudent> allQuizInfo = sqm.getRelevantQuizzes(studentId, conn);

            map.put("quizList", allQuizInfo);
            res.status(200);

            return eng.render(eng.modelAndView(map, "quizListStudent.mustache"));

        }
        catch(SQLException sqle){
            LOGGER.error("SQL exception happened !", sqle);
            res.status(500);
            return null;
        }

    }

    public static Object getFilteredQuizList(Request req, Response res){

        HashMap<String, Object> map = ParameterManager.getAllParameters(req);

        String relevant = req.queryParams("relevant");
        String taken = req.queryParams("taken");
        String moduleCode = req.queryParams("moduleCode");
        String sortBy = req.queryParams("sortBy");

        if (relevant==null || moduleCode==null || taken == null || sortBy==null){//no such parameter
            res.status(400);
            return "{\"message\":\"Bad input!\"}";
        }

        User currentUser = (User)map.get("user");
        if (currentUser==null){
            LOGGER.error("impossible happened");
            res.status(401);
            return null ;
        }

        int studentId = currentUser.getUserid();

        DSLContext dslCont = Database.getJooq();
        StudentQuizModel quizModel = new StudentQuizModel();

        try{

            ArrayList<QuizInfoStudent> quizTitles = quizModel.getFilteredQuizInfo(dslCont,moduleCode,sortBy, taken, relevant, studentId);
            String json = new Gson().toJson(quizTitles);
            System.out.println(json);
            res.status(200);
            return json;

        }
        catch (DataAccessException dae){
            LOGGER.error("SQL Exception occured!", dae);
            res.status(500);
            return "{\"message\":\"Exception occured\"}";
        }
        catch (Exception e){
            LOGGER.error("Exception :(", e);
            res.status(500);
            return "{\"message\":\"Exception occured\"}";
        }

    }

}


text:
class AddRssTokenToUsers < ActiveRecord::Migration[4.2]
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  disable_ddl_transaction!

  def up
    add_column :users, :rss_token, :string

    add_concurrent_index :users, :rss_token
  end

  def down
    remove_concurrent_index :users, :rss_token if index_exists? :users, :rss_token

    remove_column :users, :rss_token
  end
end


text:
<?php
/**
 * Manage media uploaded file.
 *
 * There are many filters in here for media. Plugins can extend functionality
 * by hooking into the filters.
 *
 * @package WordPress
 * @subpackage Administration
 */

if ( ! isset( $_GET['inline'] ) )
	define( 'IFRAME_REQUEST' , true );

/** Load WordPress Administration Bootstrap */
require_once('./admin.php');

if (!current_user_can('upload_files'))
	wp_die(__('You do not have permission to upload files.'));

wp_enqueue_script('plupload-handlers');
wp_enqueue_script('image-edit');
wp_enqueue_script('set-post-thumbnail' );
wp_enqueue_style('imgareaselect');
wp_enqueue_script( 'media-gallery' );

@header('Content-Type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));

// IDs should be integers
$ID = isset($ID) ? (int) $ID : 0;
$post_id = isset($post_id)? (int) $post_id : 0;

// Require an ID for the edit screen
if ( isset($action) && $action == 'edit' && !$ID )
	wp_die( __( 'Cheatin’ uh?' ) );

	if ( ! empty( $_REQUEST['post_id'] ) && ! current_user_can( 'edit_post' , $_REQUEST['post_id'] ) )
		wp_die( __( 'Cheatin’ uh?' ) );

	// upload type: image, video, file, ..?
	if ( isset($_GET['type']) )
		$type = strval($_GET['type']);
	else
		$type = apply_filters('media_upload_default_type', 'file');

	// tab: gallery, library, or type-specific
	if ( isset($_GET['tab']) )
		$tab = strval($_GET['tab']);
	else
		$tab = apply_filters('media_upload_default_tab', 'type');

	$body_id = 'media-upload';

	// let the action code decide how to handle the request
	if ( $tab == 'type' || $tab == 'type_url' || ! array_key_exists( $tab , media_upload_tabs() ) )
		do_action("media_upload_$type");
	else
		do_action("media_upload_$tab");


text:
package org.irmacard.cardemu.preferences;

import android.os.Bundle;
import android.preference.PreferenceFragment;

import org.irmacard.cardemu.R;

public class ScreenshotPreferenceFragment extends PreferenceFragment {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences_screenshots);
	}
}


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Rx';
import { JhiEventManager } from 'ng-jhipster';

import { TypeTest } from './type-test.model';
import { TypeTestService } from './type-test.service';

@Component({
    selector: 'jhi-type-test-detail',
    templateUrl: './type-test-detail.component.html'
})
export class TypeTestDetailComponent implements OnInit, OnDestroy {

    typeTest: TypeTest;
    private subscription: Subscription;
    private eventSubscriber: Subscription;

    constructor(
        private eventManager: JhiEventManager,
        private typeTestService: TypeTestService,
        private route: ActivatedRoute
    ) {
    }

    ngOnInit() {
        this.subscription = this.route.params.subscribe((params) => {
            this.load(params['id']);
        });
        this.registerChangeInTypeTests();
    }

    load(id) {
        this.typeTestService.find(id).subscribe((typeTest) => {
            this.typeTest = typeTest;
        });
    }
    previousState() {
        window.history.back();
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
        this.eventManager.destroy(this.eventSubscriber);
    }

    registerChangeInTypeTests() {
        this.eventSubscriber = this.eventManager.subscribe(
            'typeTestListModification',
            (response) => this.load(this.typeTest.id)
        );
    }
}


text:
@interface UIPageControl(BeeUILayout)
@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
package config

import (
	"testing"

	"github.com/frozzare/go-assert"
)

func TestCastList(t *testing.T) {
	tests := []struct {
		err      bool
		value    interface{}
		expected []string
	}{
		{false, "fredrik, elli", []string{"fredrik", "elli"}},
		{false, []string{"fredrik", "elli"}, []string{"fredrik", "elli"}},
		{false, nil, []string{}},
	}

	for _, test := range tests {
		v, err := castList(test.value)

		if test.err {
			assert.NotNil(t, err)
		} else {
			assert.Nil(t, err)
		}

		assert.Equal(t, test.expected, v)
	}
}


text:
/* The following code was generated by JFlex 1.3.5 on 9/24/02 12:52 PM */
package org.gridchem.client;

import java.io.*;

import org.gridchem.client.*;
import org.gridchem.client.common.Settings;
import org.gridchem.client.util.*;

import java_cup.runtime.*;

import java_cup.*;

/**
 * This class is a scanner generated by
 * JFlex 1.3.5
 * on 9/24/02 12:52 PM from the specification file
 * <tt>file:/home/dodi/new_qcrjm/optimization/opt/gamess.flex</tt>
 */
public class GamessLexer implements java_cup.runtime.Scanner {

  /** This character denotes the end of file */
  final public static int YYEOF = -1;

  /** initial size of the lookahead buffer */
  final private static int YY_BUFFERSIZE = 16384;

  /** lexical states */
  final public static int IGNOREALL = 2;
  final public static int YYINITIAL = 0;
  final public static int ITER = 1;

  /**
   * Translates characters to character classes
   */
  final private static char [] yycmap = {
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  2,  0,  0,
     0,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  5,  1,
     8,  1,  3,  1,  6,  4,  1,  1,  1,  7,  1,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
     0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0
  };

  /**
   * Translates a state to a row index in the transition table
   */
  final private static int yy_rowMap [] = {
        0,     9,    18,    27,    36,    45,    54,    63,    72,    81,
       90,    27
  };

  /**
   * The packed transition table of the DFA (part 0)
   */
  final private static String yy_packed0 =
    "\3\4\1\5\6\4\1\6\1\4\6\6\11\4\15\0"+
    "\1\7\5\0\1\6\1\0\6\6\5\0\1\10\11\0"+
    "\1\11\11\0\1\12\11\0\1\13\2\0\1\14\6\0";

  /**
   * The transition table of the DFA
   */
  final private static int yytrans [] = yy_unpack();

  /* error codes */
  final private static int YY_UNKNOWN_ERROR = 0;
  final private static int YY_ILLEGAL_STATE = 1;
  final private static int YY_NO_MATCH = 2;
  final private static int YY_PUSHBACK_2BIG = 3;

  /* error messages for the codes above */
  final private static String YY_ERROR_MSG[] = {
    "Unknown internal scanner error",
    "Internal error: unknown state",
    "Error: could not match input",
    "Error: pushback value was too large"
  };

  /**
   * YY_ATTRIBUTE[aState] contains the attributes of state aState
   */
  private final static byte YY_ATTRIBUTE[] = {
     0,  0,  0,  9,  1,  1,  0,  0,  0,  0,  0,  9
  };

  /** the input device */
  private java.io.Reader yy_reader;

  /** the current state of the DFA */
  private int yy_state;

  /** the current lexical state */
  private int yy_lexical_state = YYINITIAL;

  /** this buffer contains the current text to be matched and is
      the source of the yytext() string */
  private char yy_buffer[] = new char[YY_BUFFERSIZE];

  /** the textposition at the last accepting state */
  private int yy_markedPos;

  /** the textposition at the last state to be included in yytext */
  private int yy_pushbackPos;

  /** the current text position in the buffer */
  private int yy_currentPos;

  /** startRead marks the beginning of the yytext() string in the buffer */
  private int yy_startRead;

  /** endRead marks the last character in the buffer, that has been read
      from input */
  private int yy_endRead;

  /** number of newlines encountered up to the start of the matched text */
  private int yyline;

  /** the number of characters up to the start of the matched text */
  private int yychar;

  /**
   * the number of characters from the last newline up to the start of the
   * matched text
   */
  private int yycolumn;

  /**
   * yy_atBOL == true <=> the scanner is currently at the beginning of a line
   */
  private boolean yy_atBOL = true;

  /** yy_atEOF == true <=> the scanner is at the EOF */
  private boolean yy_atEOF;

  /** denotes if the user-EOF-code has already been executed */
  private boolean yy_eof_done;

  /* user code: */
  public static boolean DEBUG = false;

  /**
   * Creates a new scanner
   * There is also a java.io.InputStream version of this constructor.
   *
   * @param   in  the java.io.Reader to read input from.
   */
  public GamessLexer(java.io.Reader in) {
    this.yy_reader = in;
  }

  /**
   * Creates a new scanner.
   * There is also java.io.Reader version of this constructor.
   *
   * @param   in  the java.io.Inputstream to read input from.
   */
  public GamessLexer(java.io.InputStream in) {
    this(new java.io.InputStreamReader(in));
  }

  /**
   * Unpacks the split, compressed DFA transition table.
   *
   * @return the unpacked transition table
   */
  private static int [] yy_unpack() {
    int [] trans = new int[99];
    int offset = 0;
    offset = yy_unpack(yy_packed0, offset, trans);
    return trans;
  }

  /**
   * Unpacks the compressed DFA transition table.
   *
   * @param packed   the packed transition table
   * @return         the index of the last entry
   */
  private static int yy_unpack(String packed, int offset, int [] trans) {
    int i = 0;       /* index in packed string  */
    int j = offset;  /* index in unpacked array */
    int l = packed.length();
    while (i < l) {
      int count = packed.charAt(i++);
      int value = packed.charAt(i++);
      value--;
      do trans[j++] = value; while (--count > 0);
    }
    return j;
  }

  /**
   * Refills the input buffer.
   *
   * @return      false, iff there was new input.
   *
   * @exception   IOException  if any I/O-Error occurs
   */
  private boolean yy_refill() throws java.io.IOException {

    /* first: make room (if you can) */
    if (yy_startRead > 0) {
      System.arraycopy(yy_buffer, yy_startRead,
                       yy_buffer, 0,
                       yy_endRead-yy_startRead);

      /* translate stored positions */
      yy_endRead-= yy_startRead;
      yy_currentPos-= yy_startRead;
      yy_markedPos-= yy_startRead;
      yy_pushbackPos-= yy_startRead;
      yy_startRead = 0;
    }

    /* is the buffer big enough? */
    if (yy_currentPos >= yy_buffer.length) {
      /* if not: blow it up */
      char newBuffer[] = new char[yy_currentPos*2];
      System.arraycopy(yy_buffer, 0, newBuffer, 0, yy_buffer.length);
      yy_buffer = newBuffer;
    }

    /* finally: fill the buffer with new input */
    int numRead = yy_reader.read(yy_buffer, yy_endRead,
                                            yy_buffer.length-yy_endRead);

    if (numRead < 0) {
      return true;
    }
    else {
      yy_endRead+= numRead;
      return false;
    }
  }

  /**
   * Closes the input stream.
   */
  final public void yyclose() throws java.io.IOException {
    yy_atEOF = true;            /* indicate end of file */
    yy_endRead = yy_startRead;  /* invalidate buffer    */

    if (yy_reader != null)
      yy_reader.close();
  }

  /**
   * Closes the current stream, and resets the
   * scanner to read from a new input stream.
   *
   * All internal variables are reset, the old input stream
   * cannot be reused (internal buffer is discarded and lost).
   * Lexical state is set to <tt>YY_INITIAL</tt>.
   *
   * @param reader   the new input stream
   */
  final public void yyreset(java.io.Reader reader) throws java.io.IOException {
    yyclose();
    yy_reader = reader;
    yy_atBOL  = true;
    yy_atEOF  = false;
    yy_endRead = yy_startRead = 0;
    yy_currentPos = yy_markedPos = yy_pushbackPos = 0;
    yyline = yychar = yycolumn = 0;
    yy_lexical_state = YYINITIAL;
  }

  /**
   * Returns the current lexical state.
   */
  final public int yystate() {
    return yy_lexical_state;
  }

  /**
   * Enters a new lexical state
   *
   * @param newState the new lexical state
   */
  final public void yybegin(int newState) {
    yy_lexical_state = newState;
  }

  /**
   * Returns the text matched by the current regular expression.
   */
  final public String yytext() {
    return new String( yy_buffer, yy_startRead, yy_markedPos-yy_startRead );
  }

  /**
   * Returns the character at position <tt>pos</tt> from the
   * matched text.
   *
   * It is equivalent to yytext().charAt(pos), but faster
   *
   * @param pos the position of the character to fetch.
   *            A value from 0 to yylength()-1.
   *
   * @return the character at position pos
   */
  final public char yycharat(int pos) {
    return yy_buffer[yy_startRead+pos];
  }

  /**
   * Returns the length of the matched text region.
   */
  final public int yylength() {
    return yy_markedPos-yy_startRead;
  }

  /**
   * Reports an error that occured while scanning.
   *
   * In a wellformed scanner (no or only correct usage of
   * yypushback(int) and a match-all fallback rule) this method
   * will only be called with things that "Can't Possibly Happen".
   * If this method is called, something is seriously wrong
   * (e.g. a JFlex bug producing a faulty scanner etc.).
   *
   * Usual syntax/scanner level error handling should be done
   * in error fallback rules.
   *
   * @param   errorCode  the code of the errormessage to display
   */
  private void yy_ScanError(int errorCode) {
    String message;
    try {
      message = YY_ERROR_MSG[errorCode];
    }
    catch (ArrayIndexOutOfBoundsException e) {
      message = YY_ERROR_MSG[YY_UNKNOWN_ERROR];
    }

    throw new Error(message);
  }

  /**
   * Pushes the specified amount of characters back into the input stream.
   *
   * They will be read again by then next call of the scanning method
   *
   * @param number  the number of characters to be read again.
   *                This number must not be greater than yylength()!
   */
  private void yypushback(int number)  {
    if ( number > yylength() )
      yy_ScanError(YY_PUSHBACK_2BIG);

    yy_markedPos -= number;
  }

  /**
   * Contains user EOF-code, which will be executed exactly once,
   * when the end of file is reached
   */
  private void yy_do_eof() throws java.io.IOException {
    if (!yy_eof_done) {
      yy_eof_done = true;
      yyclose();
    }
  }

  /**
   * Resumes scanning until the next regular expression is matched,
   * the end of input is encountered or an I/O-Error occurs.
   *
   * @return      the next token
   * @exception   IOException  if any I/O-Error occurs
   */
  public java_cup.runtime.Symbol next_token() throws java.io.IOException {
    int yy_input;
    int yy_action;

    // cached fields:
    int yy_currentPos_l;
    int yy_startRead_l;
    int yy_markedPos_l;
    int yy_endRead_l = yy_endRead;
    char [] yy_buffer_l = yy_buffer;
    char [] yycmap_l = yycmap;

    int [] yytrans_l = yytrans;
    int [] yy_rowMap_l = yy_rowMap;
    byte [] yy_attr_l = YY_ATTRIBUTE;

    while (true) {
      yy_markedPos_l = yy_markedPos;

      yy_action = -1;

      yy_startRead_l = yy_currentPos_l = yy_currentPos =
                       yy_startRead = yy_markedPos_l;

      yy_state = yy_lexical_state;

      yy_forAction: {
        while (true) {

          if (yy_currentPos_l < yy_endRead_l)
            yy_input = yy_buffer_l[yy_currentPos_l++];
          else if (yy_atEOF) {
            yy_input = YYEOF;
            break yy_forAction;
          }
          else {
            // store back cached positions
            yy_currentPos  = yy_currentPos_l;
            yy_markedPos   = yy_markedPos_l;
            boolean eof = yy_refill();
            // get translated positions and possibly new buffer
            yy_currentPos_l  = yy_currentPos;
            yy_markedPos_l   = yy_markedPos;
            yy_buffer_l      = yy_buffer;
            yy_endRead_l     = yy_endRead;
            if (eof) {
              yy_input = YYEOF;
              break yy_forAction;
            }
            else {
              yy_input = yy_buffer_l[yy_currentPos_l++];
            }
          }
          int yy_next = yytrans_l[ yy_rowMap_l[yy_state] + yycmap_l[yy_input] ];
          if (yy_next == -1) break yy_forAction;
          yy_state = yy_next;

          int yy_attributes = yy_attr_l[yy_state];
          if ( (yy_attributes & 1) == 1 ) {
            yy_action = yy_state;
            yy_markedPos_l = yy_currentPos_l;
            if ( (yy_attributes & 8) == 8 ) break yy_forAction;
          }

        }
      }

      // store back cached position
      yy_markedPos = yy_markedPos_l;

      switch (yy_action) {

        case 11:
          {
    if (Settings.DEBUG) System.out.println("GamessFlex: Found RUNTYP");
	   yybegin(ITER);
	   return new Symbol(GamessSym.FOUNDITER);
   }
        case 13: break;
        case 5:
          {
  if  (Settings.DEBUG) System.out.println("GamessFlex: Found ");

   if (Settings.DEBUG) {
   try{
     //PrintStream temp = new PrintStream(new FileOutputStream(Settings.defaultDirStr +
    PrintStream temp = new PrintStream(new FileOutputStream(Env.getApplicationDataDir()  +
	       		Settings.fileSeparator + "runtype"));
     temp.print(yytext());
     System.out.println(yytext());}
   catch (IOException ie){ System.out.println("Error in GAMESS Lexer");}
    }

   yybegin(IGNOREALL);
   return new Symbol(GamessSym.RUNTYP);
    }
        case 14: break;
        case 3:
        case 4:
          {  }
        case 15: break;
        default:
          if (yy_input == YYEOF && yy_startRead == yy_currentPos) {
            yy_atEOF = true;
            yy_do_eof();
              { return new java_cup.runtime.Symbol(sym.EOF); }
          }
          else {
            yy_ScanError(YY_NO_MATCH);
          }
      }
    }
  }

  /**
   * Converts an int token code into the name of the
   * token by reflection on the cup symbol class/interface sym
   *
   * This code was contributed by Karl Meissner <meissnersd@yahoo.com>
   * meissner.v0.net/msd.htm
   */
  private String getTokenName(int token) {
    try {
      java.lang.reflect.Field [] class_fields = sym.class.getFields();
      for (int i = 0; i < class_fields.length; i++) {
        if (class_fields[i].getInt(null) == token) {
          return class_fields[i].getName();
        }
      }
    } catch (Exception e) {
      e.printStackTrace(System.err);
    }

    return "UNKNOWN TOKEN";
  }

  /**
   * Same as next_token but also prints the token to standard out
   * for debugging.
   *
   * This code was contributed by Karl Meissner <meissnersd@yahoo.com>
   * meissner.v0.net/msd.htm
   */
  public java_cup.runtime.Symbol debug_next_token() throws java.io.IOException {
    java_cup.runtime.Symbol s = next_token();
    System.out.println( " --"+ yytext() + "--" + getTokenName(s.sym) + "--");
    return s;
  }

  /**
   * Runs the scanner on input files.
   *
   * This is a standalone scanner, i.e. it will print any unmatched
   * text to System.out unchanged.
   *
   * @param argv   the command line, contains the filenames to run
   *               the scanner on.
   */
  public static void main(String argv[]) {
    if (argv.length == 0) {
      System.out.println("Usage : java GamessLexer <inputfile>");
    }
    else {
      for (int i = 0; i < argv.length; i++) {
        GamessLexer scanner = null;
        try {
          scanner = new GamessLexer( new java.io.FileReader(argv[i]) );
          while ( !scanner.yy_atEOF ) scanner.next_token();
        }
        catch (java.io.FileNotFoundException e) {
          System.out.println("File not found : \""+argv[i]+"\"");
        }
        catch (java.io.IOException e) {
          System.out.println("IO error scanning file \""+argv[i]+"\"");
          System.out.println(e);
        }
        catch (Exception e) {
          System.out.println("Unexpected exception:");
          e.printStackTrace();
        }
      }
    }
  }

}


text:
require File.expand_path('../../test_helper', __FILE__)

class CookbookRepositoryTest < ActiveSupport::TestCase
  def setup
    Rails.backtrace_cleaner.remove_silencers!
  end

  context "Initializing a cookbook repository" do
    should "clone the repository" do
      repo_location  = "git@github.com:giraffesoft/conductor-cookbooks.git"
      clone_location = "#{Rails.root}/cookbook-repo"
      CookbookRepository.any_instance.expects(:`).with("git clone #{repo_location} #{clone_location}")
      @repo = CookbookRepository.new("git@github.com:giraffesoft/conductor-cookbooks.git")
    end
  end

  context "When the repository already exists" do
    should "pull" do
      repo_location  = "git@github.com:giraffesoft/conductor-cookbooks.git"
      clone_location = "#{Rails.root}/cookbook-repo"
      File.stubs(:directory?).with(clone_location + "/.git").returns(true)
      CookbookRepository.any_instance.expects(:`).with("cd #{clone_location} && git pull")
      @repo = CookbookRepository.new("git@github.com:giraffesoft/conductor-cookbooks.git")
    end
  end

  context "Retrieving a file from the cookbook repository" do
    should "read the file from the repo location" do
      clone_location = "#{Rails.root}/cookbook-repo"
      File.stubs(:read).with(clone_location + "/attributes.rb").returns("value of attributes.rb")
      CookbookRepository.any_instance.stubs(:`)
      @repo = CookbookRepository.new("git@github.com:giraffesoft/conductor-cookbooks.git")
      assert_equal "value of attributes.rb", @repo.read("attributes.rb")
    end
  end
end


text:
package org.apache.flink.runtime.rest.handler.cluster;

import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.rest.handler.HandlerRequest;
import org.apache.flink.runtime.rest.messages.EmptyMessageParameters;
import org.apache.flink.runtime.rest.messages.EmptyRequestBody;
import org.apache.flink.runtime.rest.messages.UntypedResponseMessageHeaders;
import org.apache.flink.runtime.webmonitor.RestfulGateway;
import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever;

import javax.annotation.Nullable;

import java.io.File;
import java.util.Map;

/** Rest handler which serves the log files from JobManager. */
public class JobManagerLogFileHandler
        extends AbstractJobManagerFileHandler<EmptyMessageParameters> {

    private final File file;

    public JobManagerLogFileHandler(
            GatewayRetriever<? extends RestfulGateway> leaderRetriever,
            Time timeout,
            Map<String, String> responseHeaders,
            UntypedResponseMessageHeaders<EmptyRequestBody, EmptyMessageParameters> messageHeaders,
            @Nullable File file) {
        super(leaderRetriever, timeout, responseHeaders, messageHeaders);

        this.file = file;
    }

    @Override
    protected File getFile(
            HandlerRequest<EmptyRequestBody, EmptyMessageParameters> handlerRequest) {
        return file;
    }
}


text:
package org.wso2.carbon.apimgt.usage.publisher;

/**
 * analytics related publisher constants
 */
public class Constants {

    public static final String RESPONSE_METRIC_NAME = "apim:response";
    public static final String FAULTY_METRIC_NAME = "apim:faulty";

}


text:
/* This file was generated by syncqt. */
#ifndef QT_QTSCRIPTTOOLS_VERSION_H
#define QT_QTSCRIPTTOOLS_VERSION_H

#define QTSCRIPTTOOLS_VERSION_STR "5.3.1"

#define QTSCRIPTTOOLS_VERSION 0x050301

#endif // QT_QTSCRIPTTOOLS_VERSION_H


text:
#include <mpi.h>
#include "argo.hpp"

#if defined(ARGO_NO_RELEASE) && \
    (defined(ARGO_NODE_WIDE_ACQUIRE) || \
     defined(ARGO_SELECTIVE_ACQUIRE))
#error This coherence operations combination violates correctness.
#endif

#define SYS ARGO_Sys

struct ARGO_Sys : public Sys
{
    //-- c'tor
    ARGO_Sys(std::string name, std::string fname, std::string probename) : Sys(name, fname, probename) {}
    ARGO_Sys(std::string name, const SparseMatrixD &M, const SparseMatrixD &P) : Sys(name, M, P) {}
    ~ARGO_Sys();

    //-- virtual functions
    virtual void sample(Sys&);
    virtual void send_item(int);
    virtual void alloc_and_init();

    //-- process_queue queue with protecting mutex
    std::mutex m;
    std::list<int> queue;
    void commit_index(int);
    void process_queue();

    //-- release functions
    void release();
    void node_wide_release();
    void fine_grained_release();
    void coarse_grained_release();

    //-- acquire functions
    void acquire();
    void node_wide_acquire();
    void fine_grained_acquire();
    void coarse_grained_acquire();

    //-- helper functions
    void pop_front(int);
    static bool are_items_adjacent(int, int);
};

ARGO_Sys::~ARGO_Sys()
{
    argo::codelete_array(items_ptr);
}

void ARGO_Sys::alloc_and_init()
{
    items_ptr = argo::conew_array<double>(num_latent * num());

    init();
}

void ARGO_Sys::send_item(int i)
{
#ifdef ARGO_SELECTIVE_RELEASE
    commit_index(i);
    process_queue();
#endif
}

void ARGO_Sys::commit_index(int i)
{
    bool push = 0;
    for(int k = 0; k < nprocs; ++k)
        if (conn(i, k)) {
            push = 1;
            break;
        }
    // if no-one needs it, don't push
    if (!push) return;

    m.lock(); queue.push_back(i); m.unlock();
}

void ARGO_Sys::process_queue()
{
    int main_thread;
    MPI_Is_thread_main(&main_thread);
    if (!main_thread) return;

    // send items in buffer
    {
        BPMF_COUNTER("release");
        release();
    }
}

void ARGO_Sys::sample(Sys& in)
{
    // because of the order
    // movies.sample(users)
    // users.sample(movies)
#ifdef ARGO_VERIFICATION
    if(!name.compare("movs"))
        MPI_Barrier(MPI_COMM_WORLD);
#endif

    // compute my own chunk
    {
        BPMF_COUNTER("compute");
        Sys::sample(in);
    }

    // send remaining items
    process_queue();

    // w8 release to finish
    {
        BPMF_COUNTER("barrier");
        MPI_Barrier(MPI_COMM_WORLD);
    }

    // reduce small structs
    reduce_sum_cov_norm();

    // recv necessary items
    {
        BPMF_COUNTER("acquire");
        acquire();
    }
}

void ARGO_Sys::release()
{
#if   defined(ARGO_NODE_WIDE_RELEASE)
    node_wide_release();
#elif defined(ARGO_SELECTIVE_RELEASE)

#ifdef FINE_GRAINED_SELECTIVE_RELEASE
    fine_grained_release();
#else
    coarse_grained_release();
#endif

#endif
}

void ARGO_Sys::acquire()
{
#if   defined(ARGO_NODE_WIDE_ACQUIRE)
    node_wide_acquire();
#elif defined(ARGO_SELECTIVE_ACQUIRE)

#ifdef FINE_GRAINED_SELECTIVE_ACQUIRE
    fine_grained_acquire();
#else
    coarse_grained_acquire();
#endif

#else
    Sys::sync();
#endif
}

void ARGO_Sys::node_wide_release()
{
    argo::backend::release();
}

void ARGO_Sys::fine_grained_release()
{
    int q = queue.size();
    while (q--) {
        const auto i = queue.front();
        m.lock(); queue.pop_front(); m.unlock();

        const auto offset = i * num_latent;
        const auto size = num_latent;
        argo::backend::selective_release(
                items_ptr+offset, size*sizeof(double));
    }
}

void ARGO_Sys::coarse_grained_release()
{
    m.lock();
    int q = queue.size();
    queue.sort();
    m.unlock();

    while (q) {
        const auto i = queue.front();
              auto l = queue.begin();
              auto r = std::next(l);

        int c;
        for (c = 1; c < q; ++c, ++l, ++r)
            if (!are_items_adjacent(*l, *r))
                break;
        m.lock(); pop_front(c); m.unlock();

        const auto offset = i * num_latent;
        const auto size = c * num_latent;
        argo::backend::selective_release(
                items_ptr+offset, size*sizeof(double));

        q -= c;
    }
}

void ARGO_Sys::node_wide_acquire()
{
    argo::backend::acquire();
}

void ARGO_Sys::fine_grained_acquire()
{
    const int lo = from(0);
    const int hi =   to(nprocs-1);
    const int my_lo = from(procid);
    const int my_hi =   to(procid);

    for(int i = lo; i < hi; ++i) {
        // if currently in my region
        if (i >= my_lo && i < my_hi) {
            // jump to next region
            i += my_hi - my_lo - 1;
            continue;
        }

        if (conn(i, procid)) {
            const auto offset = i * num_latent;
            const auto size = num_latent;
            argo::backend::selective_acquire(
                    items_ptr+offset, size*sizeof(double));
        }
    }
}

void ARGO_Sys::coarse_grained_acquire()
{
    const int lo = from(0);
    const int hi =   to(nprocs-1);
    const int my_lo = from(procid);
    const int my_hi =   to(procid);

    auto ssi = [&](
            const auto idx, const auto num) {
        const auto offset = idx * num_latent;
        const auto size = num * num_latent;
        argo::backend::selective_acquire(
                items_ptr+offset, size*sizeof(double));
    };

    int s{-1}, c{0};
    for(int i = lo; i < hi; ++i) {
        // if currently in my region
        if (i >= my_lo && i < my_hi) {
            // ssi leftover items
            if (c)
                ssi(s, c);
            // reset vars
            s = -1;
            c =  0;
            // jump to next region
            i += my_hi - my_lo - 1;
            continue;
        }

        // if conn between item-node
        if (conn(i, procid)) {
            // set stamp
            if (s == -1)
                s = i;
            // inc count
            ++c;
            // corner case
            if (i == hi-1)
                ssi(s, c);
        } else {
            // streak broke
            if (c > 0)
                ssi(s, c);
            // reset vars
            s = -1;
            c =  0;
        }
    }
}

bool ARGO_Sys::are_items_adjacent(int l, int r)
{
    return (l == r-1);
}

void ARGO_Sys::pop_front(int elems)
{
    const auto beg = queue.begin();
    const auto end = std::next(beg, elems);
    queue.erase(beg, end);
}

void Sys::Init()
{
    // global address space size - 50GiB
    argo::init(50*1024*1024*1024UL);

    Sys::procid = argo::node_id();
    Sys::nprocs = argo::number_of_nodes();
}

void Sys::Finalize()
{
    argo::finalize();
}

void Sys::sync()
{
    argo::barrier();
}

void Sys::Abort(int err)
{
    MPI_Abort(MPI_COMM_WORLD, err);
}

void Sys::reduce_sum_cov_norm()
{
    BPMF_COUNTER("reduce_sum_cov_norm");
    MPI_Allreduce(MPI_IN_PLACE, sum.data(), num_latent, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
    MPI_Allreduce(MPI_IN_PLACE, cov.data(), num_latent * num_latent, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
    MPI_Allreduce(MPI_IN_PLACE, &norm, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
}


text:
<?php

while ($userdata = $entry->fetch_object()) {//Profilbild könnte später noch implementiert werden
  echo '
';
  echo '
Profilbild:
';
  echo "profilepic}\" alt=\"Kein Profilbild vorhanden.\" height=\"75\" width=\"75\" name=\"{$userdata->profilepic}\">";
  echo '
Username:
';
  echo "
{$userdata->username}
";
  echo '
E-Mail Adresse:
';
  echo "
{$userdata->email}
";
  echo "id}\"><input type=\"button\" value=\"Passwort ändern\">";
  echo '
';
  echo "
";
  echo "
";
}

 ?>


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

#ifndef CHROME_BROWSER_UI_SYNC_ONE_CLICK_SIGNIN_DIALOG_H_
#define CHROME_BROWSER_UI_SYNC_ONE_CLICK_SIGNIN_DIALOG_H_
#pragma once

#include "base/callback_forward.h"
#include "ui/gfx/native_widget_types.h"

typedef base::Callback<void(bool /* use_default_settings */)>
    OneClickAcceptCallback;

// Shows a dialog with more information about one click signin and
// waits for confirmation from the user.  |parent_window| is the
// window from which the dialog was invoked.  If the user confirms,
// |accept_callback| is called.  The implementation of this function
// is platform specific.
void ShowOneClickSigninDialog(
    gfx::NativeWindow parent_window,
    const OneClickAcceptCallback& accept_callback);

#endif  // CHROME_BROWSER_UI_SYNC_ONE_CLICK_SIGNIN_DIALOG_H_


text:
use crate::{
    domains::Transition,
    fa::StateActionUpdate,
    policies::Policy,
    Function,
    Handler,
    Parameterised,
};
use rand::thread_rng;

#[derive(Clone, Debug)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
pub struct Response<R> {
    td_error: f64,
    qfunc_response: R,
}

/// On-policy variant of Watkins' Q-learning (aka "modified Q-learning").
///
/// # References
/// - Rummery, G. A. (1995). Problem Solving with Reinforcement Learning. Ph.D
/// thesis, Cambridge University.
/// - Singh, S. P., Sutton, R. S. (1996). Reinforcement learning with replacing
/// eligibility traces. Machine Learning 22:123–158.
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
pub struct SARSA<Q, P> {
    #[weights]
    pub q_func: Q,
    pub policy: P,

    pub gamma: f64,
}

impl<'m, S, Q, P> Handler<&'m Transition<S, P::Action>> for SARSA<Q, P>
where
    Q: Function<(&'m S, P::Action), Output = f64>
        + for<'a> Function<(&'m S, &'a P::Action), Output = f64>
        + Handler<StateActionUpdate<&'m S, &'m P::Action>>,
    P: Policy<&'m S>,
{
    type Response = Response<Q::Response>;
    type Error = Q::Error;

    fn handle(&mut self, t: &'m Transition<S, P::Action>) -> Result<Self::Response, Self::Error> {
        let s = t.from.state();
        let qsa = self.q_func.evaluate((s, &t.action));

        let residual = if t.terminated() {
            t.reward - qsa
        } else {
            let ns = t.to.state();
            let na = self.policy.sample(&mut thread_rng(), ns);
            let nqsna = self.q_func.evaluate((ns, na));

            t.reward + self.gamma * nqsna - qsa
        };

        self.q_func.handle(StateActionUpdate {
            state: s,
            action: &t.action,
            error: residual,
        }).map(|r| Response {
            td_error: residual,
            qfunc_response: r,
        })
    }
}


text:
<?php

namespace Esendex;

class SentMessagesService
{
    const SENT_MESSAGES_SERVICE = 'messageheaders';
    const SENT_MESSAGES_SERVICE_VERSION = 'v1.0';

    private $authentication;
    private $httpClient;
    private $parser;

    /**
     * @param Authentication\IAuthentication $authentication
     * @param Http\IHttp $httpClient
     * @param Parser\SentMessagesXmlParser $parser
     */
    public function __construct(
        Authentication\IAuthentication $authentication,
        Http\IHttp $httpClient = null,
        Parser\SentMessagesXmlParser $parser = null
    ) {
        $this->authentication = $authentication;
        $this->httpClient = (isset($httpClient))
            ? $httpClient
            : new Http\HttpClient(true);
        $this->parser = (isset($parser))
            ? $parser
            : new Parser\SentMessagesXmlParser(new Parser\MessageHeaderXmlParser());
    }

    /**
     * @param int $startIndex
     * @param int $count
     * @return Model\SentMessagesPage
     */
    public function latest($startIndex = null, $count = null)
    {
        $query = array();
        if ($startIndex != null && is_int($startIndex)) {
            $query["startIndex"] = $startIndex;
        }
        if ($count != null && is_int($count)) {
            $query["count"] = $count;
        }

        return $this->loadMessages($query);
    }

    /**
     * @param array $options
     * @return Model\SentMessagesPage
     */
    public function loadMessages(array $options)
    {
        $uri = Http\UriBuilder::serviceUri(
            self::SENT_MESSAGES_SERVICE_VERSION,
            self::SENT_MESSAGES_SERVICE,
            null,
            $this->httpClient->isSecure()
        );

        $options['accountreference'] = $this->authentication->accountReference();
        $uri .= "?" . Http\UriBuilder::buildQuery($options);

        $data = $this->httpClient->get(
            $uri,
            $this->authentication
        );

        return $this->parser->parse($data);
    }
}