text:
{% extends theme('layouts/_onecol.html') %}

{% import 'macros/helpers.html' as helpers %}

{% block header %}
    {% set header_as_h1 = true %}
    {% include 'partials/header.html' %}
{% endblock %}

{% block subheader %}
    {{super()}}
{% endblock subheader %}

{% set form = content.form %}

{% block page_title %}{{survey_title}}{% endblock %}

{% block main %}

    {% block business_details %}

                    {% if metadata.trad_as %}
                        {{ _("You are completing this for %(ru_name)s (%(trading_as_name)s)",
                        ru_name = metadata.ru_name,
                        trading_as_name = metadata.trad_as) }}
                    {% else %}
                        {{ _("You are completing this for %(ru_name)s", ru_name = metadata.ru_name) }}
                    {% endif %}

{{ _("If the company details or structure have changed contact us on 0300 303 5948 or email surveys@ons.gov.uk") }}

    {% endblock business_details %}

    {% block intro_content %}

            {% if content.block.primary_content %}
                {% for intro in content.block.primary_content %}
                    {% include 'partials/introduction/basic.html' %}
                {% endfor %}
            {% endif %}

            {%- if legal_basis -%}

{{ _("Your response is legally required") }}

{{ legal_basis }}

            {%- endif -%}

            {% if survey_guidance_url %}

{{ _("Guidance to help complete this survey") }}

{{_("There is %(opening_tag)s further guidance available%(closing_tag)s with information of what is required for this survey, and help to complete it",opening_tag="",closing_tag="")}}

            {% endif %}

            {% block start_survey %}
                {% include 'partials/introduction/start-survey.html' %}
            {% endblock start_survey %}

            {% if content.block.preview_content %}
                {% set intro = content.block.preview_content %}
                {% include 'partials/introduction/preview.html' %}
            {% endif %}

            {% if content.block.secondary_content %}
                {% for intro in content.block.secondary_content %}
                    {% include 'partials/introduction/basic.html' %}
                {% endfor %}
            {% endif %}

{{ _("For survey information during the coronavirus (COVID-19) outbreak go to  www.ons.gov.uk or follow us on Twitter @ONSfocus") }}

    {% endblock intro_content %}

{% endblock %}
{% block footer %}

        {% include theme('partials/feedback/expandable_inline.html') %}

{{super()}}
{% endblock %}


text:
using Microsoft.Scripting.Utils;
using Microsoft.Scripting.Runtime;
using IronRuby.Runtime;
using IronRuby.Builtins;
using System;
using System.Runtime.InteropServices;
using Microsoft.Phone.Tasks;
using rho.common;

namespace rho.rubyext
{
    [RubyModule("Camera")]
    public static class RhoCamera
    {
        private static RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
            new RhoLogger("RhoCamera");
        private static CRhoRuby RhoRuby { get { return CRhoRuby.Instance; } }
        private static CRhodesApp RHODESAPP() { return CRhodesApp.Instance; }
        private static String m_callback;

        #region Private Implementation Details

        #endregion

        #region Private Instance & Singleton Methods

        [RubyMethodAttribute("take_picture", RubyMethodAttributes.PublicSingleton)]
        public static void takePicture(RubyModule/*!*/ self, [NotNull]String/*!*/ callback)
        {
            try
            {
                m_callback = callback;
                CameraCaptureTask cameraCaptureTask;
                cameraCaptureTask = new CameraCaptureTask();
                cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraTask_Completed);
                cameraCaptureTask.Show();
            }
            catch (Exception ex)
            {
                Exception rubyEx = self.Context.CurrentException;
                if (rubyEx == null)
                {
                    rubyEx = RubyExceptionData.InitializeException(new RuntimeError(ex.Message.ToString()), ex.Message);
                }
                LOG.ERROR("take_picture", ex);
                throw rubyEx;
            }
        }

        [RubyMethodAttribute("choose_picture", RubyMethodAttributes.PublicSingleton)]
        public static void choosePicture(RubyModule/*!*/ self, [NotNull]String/*!*/ callback)
        {
            try
            {
                m_callback = callback;
                PhotoChooserTask photoChooserTask;
                photoChooserTask = new PhotoChooserTask();
                photoChooserTask.Completed += new EventHandler<PhotoResult>(cameraTask_Completed);
                photoChooserTask.Show();
            }
            catch (Exception ex)
            {
                Exception rubyEx = self.Context.CurrentException;
                if (rubyEx == null)
                {
                    rubyEx = RubyExceptionData.InitializeException(new RuntimeError(ex.Message.ToString()), ex.Message);
                }
                LOG.ERROR("take_picture", ex);
                throw rubyEx;
            }
        }

        #endregion

        #region Helpers

        private static void cameraTask_Completed(object sender, PhotoResult e)
        {
            switch (e.TaskResult)
            {
                case TaskResult.OK:
                    RhoClassFactory.createNetRequest().pushData(m_callback, "status=ok&image_uri=" + e.OriginalFileName + "&rho_callback=1", null);
                    break;
                case TaskResult.None:
                    RhoClassFactory.createNetRequest().pushData(m_callback, "status=error&message=Error&rho_callback=1", null);
                    break;
                case TaskResult.Cancel:
                    RhoClassFactory.createNetRequest().pushData(m_callback, "status=cancel&message=User cancelled operation&rho_callback=1", null);
                    break;
                default:
                    break;
            }

            //Code to display the photo on the page in an image control named myImage.
            //System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
            //bmp.SetSource(e.ChosenPhoto);
            //myImage.Source = bmp;
        }

        #endregion

    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef NCSUTIL_H
#define NCSUTIL_H

// FIXME					/**[02]**/
#ifdef __PALM__				/**[02]**/
#ifndef EMULATION_LEVEL		/**[02]**/
#define EMULATION_LEVEL 0	/**[02]**/
#endif						/**[02]**/
#endif						/**[02]**/

#ifndef __PALM__			/**[02]**/
#include <math.h>
#endif /**[02]**/

#ifndef NCSDEFS_H
#include "NCSDefs.h"
#endif
#ifndef NCSTYPES_H
#include "NCSTypes.h"
#endif
#ifndef NCSDYNAMICLIB_H
#include "NCSDynamicLib.h"
#endif
#ifndef NCSERRORS_H
#include "NCSErrors.h"
#endif
#ifndef NCSMALLOC_H
#include "NCSMalloc.h"
#endif
#ifndef NCSARRAY_H
#include "NCSArray.h"
#endif
#ifndef NCSTIMESTAMP_H
#include "NCSTimeStamp.h"
#endif
#ifndef NCSMUTEX_H
#include "NCSMutex.h"
#endif
#ifndef NCSMEMPOOL_H
#include "NCSMemPool.h"
#endif
#ifndef NCSUTIL_H
#include "NCSUtil.h"
#endif
#ifndef NCSTHREAD_H
#include "NCSThread.h"
#endif
#ifndef NCSQUEUE_H
#include "NCSQueue.h"
#endif
#ifndef NCSPACKETS_H
#include "NCSPackets.h"
#endif
#ifndef NCSTIMER_H
#include "NCSTimer.h"
#endif
#ifndef NCSPREFS_H
#include "NCSPrefs.h"
#endif
#ifndef NCSFILEIO_H
#include "NCSFileIO.h"
#endif
#ifndef NCSMISC_H
#include "NCSMisc.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

INT32 NCSUtilInitialised();
void NCSUtilInit(void);
void NCSUtilFini(void);
void NCSErrorFiniThread(void); /**[08]**/
void NCSSleep(NCSTimeStampMs tsSleepTime);
char *NCSStrDup(char *pString);
NCSTChar *NCSStrDupT(NCSTChar *pString);
NCSError NCSFormatCoordStringsEN(double dEasting, double dNorthing, char **ppEastString, char **ppNorthString);
NCSError NCSFormatCoordStringsLL(double dEasting, double dNorthing, char **ppEastString, char **ppNorthString);
UINT32   NCSGetNumCPUs(void);
UINT32 NCSGetNumPhysicalCPUs(void);
#ifdef WIN32
BOOLEAN NCSGetUserAndDomainName(char *UserName, LPDWORD cchUserName, char* DomainName, LPDWORD cchDomainName);
UINT32 NCSGetWebServerID(const char *szPath, DWORD nPathLen);
#endif
BOOLEAN NCSIsNaN(IEEE8 dDoubleValue);
BOOLEAN NCSIsService(void);		/**[04]**/

BOOLEAN NCSIsIWS(void);
void NCSSetIsIWS( BOOLEAN bValue );

double NCSNanVal(void);	/**[06]**/
BOOLEAN NCSDoubleIsNan(double v);

#ifdef WIN32
#ifdef _WIN32_WCE

#if (_WIN32_WCE <= 211)
#define strnicmp(a, b, c)	_memicmp(a, b, c)
#define stricmp(a, b)		_memicmp(a, b, MIN(strlen(a), strlen(b)))
#else
#define strnicmp(a, b, c)	_strnicmp(a, b, c)
#define stricmp(a, b)		_stricmp(a, b)
#endif

#endif /* _WIN32_CE */

#define vsnprintf			_vsnprintf
#define snprintf			_snprintf

#define NCSMessageBox(Window, Text, Caption, Type) ::MessageBox(Window, Text, Caption, Type)
#define NCSMessageBoxA(Window, Text, Caption, Type) ::MessageBoxA(Window, Text, Caption, Type)

#elif defined __PALM__

#define stricmp(a, b)		StrCaselessCompare(a, b)
#define strnicmp(a, b, c)	StrNCaselessCompare(a, b, c)
#define strcmp(a, b)		StrCompare(a, b)
#define strncmp(a, b)		StrNCompare(a, b)
#define strcpy(a, b) 		StrCopy(a, (const char*)b)
#define strncpy(a, b, c)	StrNCopy(a, (const char*)b, c)
#define strlen(a)			StrLen(a)
#define calloc(a, b) 		NCSMalloc(a * b, TRUE)
#define malloc(a)			NCSMalloc(a, FALSE)
#define realloc(a, b)		NCSRealloc((void*)a, b, TRUE)
#define free(a)				NCSFree(a)
#define memcpy(a, b, c)		MemMove(a, b, c)
#define memset(a, b, c)		MemSet(a, c, b)
#define isupper(a)			((((a) >= 'A') && ((a) <= 'Z')) ? TRUE : FALSE)
#define tolower(a)			((a) -= ('A' - 'a'))
int sscanf(const char *string, const char *format, ...);
__inline double atof(char *s)
{
	double d;
	sscanf(s, "%f", &d);
	return(d);
}

#elif defined MACINTOSH

#if TARGET_API_MAC_CARBON
#	define _stricmp stricmp
#	define _strnicmp strnicmp
#	define _itoa itoa
#else
#	define strncascmp 		_stricmp
#	define NCSstrcasecmp 	_stricmp
#	define strnicmp		_strnicmp
#	define stricmp			_stricmp
#endif //TARGET_API_MAC_CARBON

#elif defined POSIX

#include <string.h>
#define stricmp(a, b) 		strcasecmp(a, b)
#define _stricmp(a, b)		strcasecmp(a, b)
#define strnicmp(a, b, c)	strncasecmp(a, b, c)
#define _snprintf snprintf
#define _vsnprintf vsnprintf

#else /* __PALM__ */

#define stricmp(a, b) 		strcasecmp(a, b)
#define strnicmp(a, b, c)	strncasecmp(a, b, c)

#endif /* WIN32 */

#ifdef __cplusplus
}
#endif

#endif /* NCSUTIL_H */


text:
#include <aws/alexaforbusiness/model/UpdateDeviceResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>

#include <utility>

using namespace Aws::AlexaForBusiness::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;

UpdateDeviceResult::UpdateDeviceResult()
{
}

UpdateDeviceResult::UpdateDeviceResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  *this = result;
}

UpdateDeviceResult& UpdateDeviceResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
  AWS_UNREFERENCED_PARAM(result);

  return *this;
}


text:
package org.traccar.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.traccar.Context;
import org.traccar.database.ConnectionManager;
import org.traccar.model.Device;
import org.traccar.model.Event;
import org.traccar.model.Position;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class AsyncSocket extends WebSocketAdapter implements ConnectionManager.UpdateListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(AsyncSocket.class);

    private static final String KEY_DEVICES = "devices";
    private static final String KEY_POSITIONS = "positions";
    private static final String KEY_EVENTS = "events";

    private final long userId;

    public AsyncSocket(long userId) {
        this.userId = userId;
    }

    @Override
    public void onWebSocketConnect(Session session) {
        super.onWebSocketConnect(session);

        Map<String, Collection<?>> data = new HashMap<>();
        data.put(KEY_POSITIONS, Context.getDeviceManager().getInitialState(userId));
        sendData(data);

        Context.getConnectionManager().addListener(userId, this);
    }

    @Override
    public void onWebSocketClose(int statusCode, String reason) {
        super.onWebSocketClose(statusCode, reason);

        Context.getConnectionManager().removeListener(userId, this);
    }

    @Override
    public void onUpdateDevice(Device device) {
        Map<String, Collection<?>> data = new HashMap<>();
        data.put(KEY_DEVICES, Collections.singletonList(device));
        sendData(data);
    }

    @Override
    public void onUpdatePosition(Position position) {
        Map<String, Collection<?>> data = new HashMap<>();
        data.put(KEY_POSITIONS, Collections.singletonList(position));
        sendData(data);
    }

    @Override
    public void onUpdateEvent(Event event) {
        Map<String, Collection<?>> data = new HashMap<>();
        data.put(KEY_EVENTS, Collections.singletonList(event));
        sendData(data);
    }

    private void sendData(Map<String, Collection<?>> data) {
        if (!data.isEmpty() && isConnected()) {
            try {
                getRemote().sendString(Context.getObjectMapper().writeValueAsString(data), null);
            } catch (JsonProcessingException e) {
                LOGGER.warn("Socket JSON formatting error", e);
            }
        }
    }
}


text:
<?php

class SPODNOTIFICATION_BOL_Notification extends OW_Entity
{
    /**
     * @var string
     */
    public $notification;
    /**
     * @var integer
     */
    public $timestamp;
}


text:
@class NSArray;
@class NSError;

CLOUDKIT_EXPORT_CLASS
@interface CKDiscoverAllContactsOperation : CKOperation

@property (copy, nonatomic, nullable) void (^discoverAllContactsCompletionBlock)(NSArray*, NSError*) STUB_PROPERTY;
@end


text:
/*
 * This file is available under and governed by the GNU General Public
 * License version 2 only, as published by the Free Software Foundation.
 * However, the following notice accompanied the original version of this
 * file, and Oracle licenses the original version of this file under the BSD
 * license:
 */
/*
   Copyright 2009-2013 Attila Szegedi

   Licensed under both the Apache License, Version 2.0 (the "Apache License")
   and the BSD License (the "BSD License"), with licensee being free to
   choose either of the two at their discretion.

   You may not use this file except in compliance with either the Apache
   License or the BSD License.

   If you choose to use this file in compliance with the Apache License, the
   following notice applies to you:

       You may obtain a copy of the Apache License at

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

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

   If you choose to use this file in compliance with the BSD License, the
   following notice applies to you:

       Redistribution and use in source and binary forms, with or without
       modification, are permitted provided that the following conditions are
       met:
       * Redistributions of source code must retain the above copyright
         notice, this list of conditions and the following disclaimer.
       * Redistributions in binary form must reproduce the above copyright
         notice, this list of conditions and the following disclaimer in the
         documentation and/or other materials provided with the distribution.
       * Neither the name of the copyright holder nor the names of
         contributors may be used to endorse or promote products derived from
         this software without specific prior written permission.

       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
       IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
       TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
       PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDER
       BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
       CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
       SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
       BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
       WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
       OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
       ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package jdk.internal.dynalink.beans;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import jdk.internal.dynalink.CallSiteDescriptor;
import jdk.internal.dynalink.linker.GuardedInvocation;
import jdk.internal.dynalink.linker.LinkRequest;
import jdk.internal.dynalink.linker.LinkerServices;
import jdk.internal.dynalink.linker.TypeBasedGuardingDynamicLinker;
import jdk.internal.dynalink.support.CallSiteDescriptorFactory;
import jdk.internal.dynalink.support.Guards;

/**
 * Simple linker that implements the "dyn:call" operation for {@link DynamicMethod} objects - the objects returned by
 * "dyn:getMethod" from {@link AbstractJavaLinker}.
 */
class DynamicMethodLinker implements TypeBasedGuardingDynamicLinker {
    @Override
    public boolean canLinkType(Class<?> type) {
        return DynamicMethod.class.isAssignableFrom(type);
    }

    @Override
    public GuardedInvocation getGuardedInvocation(LinkRequest linkRequest, LinkerServices linkerServices) {
        final Object receiver = linkRequest.getReceiver();
        if(!(receiver instanceof DynamicMethod)) {
            return null;
        }
        final CallSiteDescriptor desc = linkRequest.getCallSiteDescriptor();
        if(desc.getNameTokenCount() != 2 && desc.getNameToken(CallSiteDescriptor.SCHEME) != "dyn") {
            return null;
        }
        final String operator = desc.getNameToken(CallSiteDescriptor.OPERATOR);
        if(operator == "call") {
            final MethodHandle invocation = ((DynamicMethod)receiver).getInvocation(
                    CallSiteDescriptorFactory.dropParameterTypes(desc, 0, 1), linkerServices);
            if(invocation == null) {
                return null;
            }
            return new GuardedInvocation(MethodHandles.dropArguments(invocation, 0,
                    desc.getMethodType().parameterType(0)), Guards.getIdentityGuard(receiver));
        }
        return null;
    }
}


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32746g_discovery_camera.h"
#include "stm32746g_discovery.h"

/** @addtogroup BSP
  * @{
  */

/** @addtogroup STM32746G_DISCOVERY
  * @{
  */

/** @addtogroup STM32746G_DISCOVERY_CAMERA
  * @{
  */

/** @defgroup STM32746G_DISCOVERY_CAMERA_Private_TypesDefinitions STM32746G_DISCOVERY_CAMERA Private Types Definitions
  * @{
  */
/**
  * @}
  */

/** @defgroup STM32746G_DISCOVERY_CAMERA_Private_Defines STM32746G_DISCOVERY_CAMERA Private Defines
  * @{
  */
#define CAMERA_VGA_RES_X          640
#define CAMERA_VGA_RES_Y          480
#define CAMERA_480x272_RES_X      480
#define CAMERA_480x272_RES_Y      272
#define CAMERA_QVGA_RES_X         320
#define CAMERA_QVGA_RES_Y         240
#define CAMERA_QQVGA_RES_X        160
#define CAMERA_QQVGA_RES_Y        120
/**
  * @}
  */

/** @defgroup STM32746G_DISCOVERY_CAMERA_Private_Macros STM32746G_DISCOVERY_CAMERA Private Macros
  * @{
  */
/**
  * @}
  */

/** @defgroup STM32746G_DISCOVERY_CAMERA_Private_Variables STM32746G_DISCOVERY_CAMERA Private Variables
  * @{
  */
static DCMI_HandleTypeDef  hDcmiHandler;
       CAMERA_DrvTypeDef   *camera_drv;
/* Camera current resolution naming (QQVGA, VGA, ...) */
static uint32_t CameraCurrentResolution;

/* Camera module I2C HW address */
static uint32_t CameraHwAddress;
/**
  * @}
  */

/** @defgroup STM32746G_DISCOVERY_CAMERA_Private_FunctionPrototypes STM32746G_DISCOVERY_CAMERA Private Function Prototypes
  * @{
  */
static uint32_t GetSize(uint32_t resolution);
/**
  * @}
  */

/** @defgroup STM32746G_DISCOVERY_CAMERA_Exported_Functions STM32746G_DISCOVERY_CAMERA Exported Functions
  * @{
  */

/**
  * @brief  Initializes the camera.
  * @param  Resolution : camera sensor requested resolution (x, y) : standard resolution
  *         naming QQVGA, QVGA, VGA ...
  * @retval Camera status
  */
uint8_t BSP_CAMERA_Init(uint32_t Resolution)
{
  DCMI_HandleTypeDef *phdcmi;
  uint8_t status = CAMERA_ERROR;

  /* Get the DCMI handle structure */
  phdcmi = &hDcmiHandler;

  /*** Configures the DCMI to interface with the camera module ***/
  /* DCMI configuration */
  phdcmi->Init.CaptureRate      = DCMI_CR_ALL_FRAME;
  phdcmi->Init.HSPolarity       = DCMI_HSPOLARITY_LOW;
  phdcmi->Init.SynchroMode      = DCMI_SYNCHRO_HARDWARE;
  phdcmi->Init.VSPolarity       = DCMI_VSPOLARITY_HIGH;
  phdcmi->Init.ExtendedDataMode = DCMI_EXTEND_DATA_8B;
  phdcmi->Init.PCKPolarity      = DCMI_PCKPOLARITY_RISING;
  phdcmi->Instance              = DCMI;

  /* Power up camera */
  BSP_CAMERA_PwrUp();

  /* Read ID of Camera module via I2C */
  if(ov9655_ReadID(CAMERA_I2C_ADDRESS) == OV9655_ID)
  {
    /* Initialize the camera driver structure */
    camera_drv = &ov9655_drv;
    CameraHwAddress = CAMERA_I2C_ADDRESS;

    /* DCMI Initialization */
    BSP_CAMERA_MspInit(&hDcmiHandler, NULL);
    HAL_DCMI_Init(phdcmi);

    /* Camera Module Initialization via I2C to the wanted 'Resolution' */
    if (Resolution == CAMERA_R480x272)
    {     /* For 480x272 resolution, the OV9655 sensor is set to VGA resolution
           * as OV9655 doesn't supports 480x272 resolution,
           * then DCMI is configured to output a 480x272 cropped window */
      camera_drv->Init(CameraHwAddress, CAMERA_R640x480);
      HAL_DCMI_ConfigCROP(phdcmi,           /* Crop in the middle of the VGA picture */
                         (CAMERA_VGA_RES_X - CAMERA_480x272_RES_X)/2,
                         (CAMERA_VGA_RES_Y - CAMERA_480x272_RES_Y)/2,
                         (CAMERA_480x272_RES_X * 2) - 1,
                          CAMERA_480x272_RES_Y - 1);
      HAL_DCMI_EnableCROP(phdcmi);
    }
    else
    {
      camera_drv->Init(CameraHwAddress, Resolution);
      HAL_DCMI_DisableCROP(phdcmi);
    }

    CameraCurrentResolution = Resolution;

    /* Return CAMERA_OK status */
    status = CAMERA_OK;
  }
  else
  {
    /* Return CAMERA_NOT_SUPPORTED status */
    status = CAMERA_NOT_SUPPORTED;
  }

  return status;
}

/**
  * @brief  DeInitializes the camera.
  * @retval Camera status
  */
uint8_t BSP_CAMERA_DeInit(void)
{
  hDcmiHandler.Instance              = DCMI;

  HAL_DCMI_DeInit(&hDcmiHandler);
  BSP_CAMERA_MspDeInit(&hDcmiHandler, NULL);
  return CAMERA_OK;
}

/**
  * @brief  Starts the camera capture in continuous mode.
  * @param  buff: pointer to the camera output buffer
  * @retval None
  */
void BSP_CAMERA_ContinuousStart(uint8_t *buff)
{
  /* Start the camera capture */
  HAL_DCMI_Start_DMA(&hDcmiHandler, DCMI_MODE_CONTINUOUS, (uint32_t)buff, GetSize(CameraCurrentResolution));
}

/**
  * @brief  Starts the camera capture in snapshot mode.
  * @param  buff: pointer to the camera output buffer
  * @retval None
  */
void BSP_CAMERA_SnapshotStart(uint8_t *buff)
{
  /* Start the camera capture */
  HAL_DCMI_Start_DMA(&hDcmiHandler, DCMI_MODE_SNAPSHOT, (uint32_t)buff, GetSize(CameraCurrentResolution));
}

/**
  * @brief Suspend the CAMERA capture
  * @retval None
  */
void BSP_CAMERA_Suspend(void)
{
  /* Disable the DMA */
  __HAL_DMA_DISABLE(hDcmiHandler.DMA_Handle);
  /* Disable the DCMI */
  __HAL_DCMI_DISABLE(&hDcmiHandler);

}

/**
  * @brief Resume the CAMERA capture
  * @retval None
  */
void BSP_CAMERA_Resume(void)
{
  /* Enable the DCMI */
  __HAL_DCMI_ENABLE(&hDcmiHandler);
  /* Enable the DMA */
  __HAL_DMA_ENABLE(hDcmiHandler.DMA_Handle);
}

/**
  * @brief  Stop the CAMERA capture
  * @retval Camera status
  */
uint8_t BSP_CAMERA_Stop(void)
{
  uint8_t status = CAMERA_ERROR;

  if(HAL_DCMI_Stop(&hDcmiHandler) == HAL_OK)
  {
     status = CAMERA_OK;
  }

  /* Set Camera in Power Down */
  BSP_CAMERA_PwrDown();

  return status;
}

/**
  * @brief  CANERA power up
  * @retval None
  */
void BSP_CAMERA_PwrUp(void)
{
  GPIO_InitTypeDef gpio_init_structure;

  /* Enable GPIO clock */
  __HAL_RCC_GPIOH_CLK_ENABLE();

  /*** Configure the GPIO ***/
  /* Configure DCMI GPIO as alternate function */
  gpio_init_structure.Pin       = GPIO_PIN_13;
  gpio_init_structure.Mode      = GPIO_MODE_OUTPUT_PP;
  gpio_init_structure.Pull      = GPIO_NOPULL;
  gpio_init_structure.Speed     = GPIO_SPEED_HIGH;
  HAL_GPIO_Init(GPIOH, &gpio_init_structure);

  /* De-assert the camera POWER_DOWN pin (active high) */
  HAL_GPIO_WritePin(GPIOH, GPIO_PIN_13, GPIO_PIN_RESET);

  HAL_Delay(3);     /* POWER_DOWN de-asserted during 3ms */
}

/**
  * @brief  CAMERA power down
  * @retval None
  */
void BSP_CAMERA_PwrDown(void)
{
  GPIO_InitTypeDef gpio_init_structure;

  /* Enable GPIO clock */
  __HAL_RCC_GPIOH_CLK_ENABLE();

  /*** Configure the GPIO ***/
  /* Configure DCMI GPIO as alternate function */
  gpio_init_structure.Pin       = GPIO_PIN_13;
  gpio_init_structure.Mode      = GPIO_MODE_OUTPUT_PP;
  gpio_init_structure.Pull      = GPIO_NOPULL;
  gpio_init_structure.Speed     = GPIO_SPEED_HIGH;
  HAL_GPIO_Init(GPIOH, &gpio_init_structure);

  /* Assert the camera POWER_DOWN pin (active high) */
  HAL_GPIO_WritePin(GPIOH, GPIO_PIN_13, GPIO_PIN_SET);
}

/**
  * @brief  Configures the camera contrast and brightness.
  * @param  contrast_level: Contrast level
  *          This parameter can be one of the following values:
  *            @arg  CAMERA_CONTRAST_LEVEL4: for contrast +2
  *            @arg  CAMERA_CONTRAST_LEVEL3: for contrast +1
  *            @arg  CAMERA_CONTRAST_LEVEL2: for contrast  0
  *            @arg  CAMERA_CONTRAST_LEVEL1: for contrast -1
  *            @arg  CAMERA_CONTRAST_LEVEL0: for contrast -2
  * @param  brightness_level: Contrast level
  *          This parameter can be one of the following values:
  *            @arg  CAMERA_BRIGHTNESS_LEVEL4: for brightness +2
  *            @arg  CAMERA_BRIGHTNESS_LEVEL3: for brightness +1
  *            @arg  CAMERA_BRIGHTNESS_LEVEL2: for brightness  0
  *            @arg  CAMERA_BRIGHTNESS_LEVEL1: for brightness -1
  *            @arg  CAMERA_BRIGHTNESS_LEVEL0: for brightness -2
  * @retval None
  */
void BSP_CAMERA_ContrastBrightnessConfig(uint32_t contrast_level, uint32_t brightness_level)
{
  if(camera_drv->Config != NULL)
  {
    camera_drv->Config(CameraHwAddress, CAMERA_CONTRAST_BRIGHTNESS, contrast_level, brightness_level);
  }
}

/**
  * @brief  Configures the camera white balance.
  * @param  Mode: black_white mode
  *          This parameter can be one of the following values:
  *            @arg  CAMERA_BLACK_WHITE_BW
  *            @arg  CAMERA_BLACK_WHITE_NEGATIVE
  *            @arg  CAMERA_BLACK_WHITE_BW_NEGATIVE
  *            @arg  CAMERA_BLACK_WHITE_NORMAL
  * @retval None
  */
void BSP_CAMERA_BlackWhiteConfig(uint32_t Mode)
{
  if(camera_drv->Config != NULL)
  {
    camera_drv->Config(CameraHwAddress, CAMERA_BLACK_WHITE, Mode, 0);
  }
}

/**
  * @brief  Configures the camera color effect.
  * @param  Effect: Color effect
  *          This parameter can be one of the following values:
  *            @arg  CAMERA_COLOR_EFFECT_ANTIQUE
  *            @arg  CAMERA_COLOR_EFFECT_BLUE
  *            @arg  CAMERA_COLOR_EFFECT_GREEN
  *            @arg  CAMERA_COLOR_EFFECT_RED
  * @retval None
  */
void BSP_CAMERA_ColorEffectConfig(uint32_t Effect)
{
  if(camera_drv->Config != NULL)
  {
    camera_drv->Config(CameraHwAddress, CAMERA_COLOR_EFFECT, Effect, 0);
  }
}

/**
  * @brief  Handles DCMI interrupt request.
  * @retval None
  */
void BSP_CAMERA_IRQHandler(void)
{
  HAL_DCMI_IRQHandler(&hDcmiHandler);
}

/**
  * @brief  Handles DMA interrupt request.
  * @retval None
  */
void BSP_CAMERA_DMA_IRQHandler(void)
{
  HAL_DMA_IRQHandler(hDcmiHandler.DMA_Handle);
}

/**
  * @brief  Get the capture size in pixels unit.
  * @param  resolution: the current resolution.
  * @retval capture size in pixels unit.
  */
static uint32_t GetSize(uint32_t resolution)
{
  uint32_t size = 0;

  /* Get capture size */
  switch (resolution)
  {
  case CAMERA_R160x120:
    {
      size =  0x2580;
    }
    break;
  case CAMERA_R320x240:
    {
      size =  0x9600;
    }
    break;
  case CAMERA_R480x272:
    {
      size =  0xFF00;
    }
    break;
  case CAMERA_R640x480:
    {
      size =  0x25800;
    }
    break;
  default:
    {
      break;
    }
  }

  return size;
}

/**
  * @brief  Initializes the DCMI MSP.
  * @param  hdcmi: HDMI handle
  * @param  Params
  * @retval None
  */
__weak void BSP_CAMERA_MspInit(DCMI_HandleTypeDef *hdcmi, void *Params)
{
  static DMA_HandleTypeDef hdma_handler;
  GPIO_InitTypeDef gpio_init_structure;

  /*** Enable peripherals and GPIO clocks ***/
  /* Enable DCMI clock */
  __HAL_RCC_DCMI_CLK_ENABLE();

  /* Enable DMA2 clock */
  __HAL_RCC_DMA2_CLK_ENABLE();

  /* Enable GPIO clocks */
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOE_CLK_ENABLE();
  __HAL_RCC_GPIOG_CLK_ENABLE();
  __HAL_RCC_GPIOH_CLK_ENABLE();

  /*** Configure the GPIO ***/
  /* Configure DCMI GPIO as alternate function */
  gpio_init_structure.Pin       = GPIO_PIN_4 | GPIO_PIN_6;
  gpio_init_structure.Mode      = GPIO_MODE_AF_PP;
  gpio_init_structure.Pull      = GPIO_PULLUP;
  gpio_init_structure.Speed     = GPIO_SPEED_HIGH;
  gpio_init_structure.Alternate = GPIO_AF13_DCMI;
  HAL_GPIO_Init(GPIOA, &gpio_init_structure);

  gpio_init_structure.Pin       = GPIO_PIN_3;
  gpio_init_structure.Mode      = GPIO_MODE_AF_PP;
  gpio_init_structure.Pull      = GPIO_PULLUP;
  gpio_init_structure.Speed     = GPIO_SPEED_HIGH;
  gpio_init_structure.Alternate = GPIO_AF13_DCMI;
  HAL_GPIO_Init(GPIOD, &gpio_init_structure);

  gpio_init_structure.Pin       = GPIO_PIN_5 | GPIO_PIN_6;
  gpio_init_structure.Mode      = GPIO_MODE_AF_PP;
  gpio_init_structure.Pull      = GPIO_PULLUP;
  gpio_init_structure.Speed     = GPIO_SPEED_HIGH;
  gpio_init_structure.Alternate = GPIO_AF13_DCMI;
  HAL_GPIO_Init(GPIOE, &gpio_init_structure);

  gpio_init_structure.Pin       = GPIO_PIN_9;
  gpio_init_structure.Mode      = GPIO_MODE_AF_PP;
  gpio_init_structure.Pull      = GPIO_PULLUP;
  gpio_init_structure.Speed     = GPIO_SPEED_HIGH;
  gpio_init_structure.Alternate = GPIO_AF13_DCMI;
  HAL_GPIO_Init(GPIOG, &gpio_init_structure);

  gpio_init_structure.Pin       = GPIO_PIN_9 | GPIO_PIN_10  | GPIO_PIN_11  |\
                                  GPIO_PIN_12 | GPIO_PIN_14;
  gpio_init_structure.Mode      = GPIO_MODE_AF_PP;
  gpio_init_structure.Pull      = GPIO_PULLUP;
  gpio_init_structure.Speed     = GPIO_SPEED_HIGH;
  gpio_init_structure.Alternate = GPIO_AF13_DCMI;
  HAL_GPIO_Init(GPIOH, &gpio_init_structure);

  /*** Configure the DMA ***/
  /* Set the parameters to be configured */
  hdma_handler.Init.Channel             = DMA_CHANNEL_1;
  hdma_handler.Init.Direction           = DMA_PERIPH_TO_MEMORY;
  hdma_handler.Init.PeriphInc           = DMA_PINC_DISABLE;
  hdma_handler.Init.MemInc              = DMA_MINC_ENABLE;
  hdma_handler.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
  hdma_handler.Init.MemDataAlignment    = DMA_MDATAALIGN_WORD;
  hdma_handler.Init.Mode                = DMA_CIRCULAR;
  hdma_handler.Init.Priority            = DMA_PRIORITY_HIGH;
  hdma_handler.Init.FIFOMode            = DMA_FIFOMODE_DISABLE;
  hdma_handler.Init.FIFOThreshold       = DMA_FIFO_THRESHOLD_FULL;
  hdma_handler.Init.MemBurst            = DMA_MBURST_SINGLE;
  hdma_handler.Init.PeriphBurst         = DMA_PBURST_SINGLE;

  hdma_handler.Instance = DMA2_Stream1;

  /* Associate the initialized DMA handle to the DCMI handle */
  __HAL_LINKDMA(hdcmi, DMA_Handle, hdma_handler);

  /*** Configure the NVIC for DCMI and DMA ***/
  /* NVIC configuration for DCMI transfer complete interrupt */
  HAL_NVIC_SetPriority(DCMI_IRQn, 5, 0);
  HAL_NVIC_EnableIRQ(DCMI_IRQn);

  /* NVIC configuration for DMA2D transfer complete interrupt */
  HAL_NVIC_SetPriority(DMA2_Stream1_IRQn, 5, 0);
  HAL_NVIC_EnableIRQ(DMA2_Stream1_IRQn);

  /* Configure the DMA stream */
  HAL_DMA_Init(hdcmi->DMA_Handle);
}

/**
  * @brief  DeInitializes the DCMI MSP.
  * @param  hdcmi: HDMI handle
  * @param  Params
  * @retval None
  */
__weak void BSP_CAMERA_MspDeInit(DCMI_HandleTypeDef *hdcmi, void *Params)
{
  /* Disable NVIC  for DCMI transfer complete interrupt */
  HAL_NVIC_DisableIRQ(DCMI_IRQn);

  /* Disable NVIC for DMA2 transfer complete interrupt */
  HAL_NVIC_DisableIRQ(DMA2_Stream1_IRQn);

  /* Configure the DMA stream */
  HAL_DMA_DeInit(hdcmi->DMA_Handle);

  /* Disable DCMI clock */
  __HAL_RCC_DCMI_CLK_DISABLE();

  /* GPIO pins clock and DMA clock can be shut down in the application
     by surcharging this __weak function */
}

/**
  * @brief  Line event callback
  * @param  hdcmi: pointer to the DCMI handle
  * @retval None
  */
void HAL_DCMI_LineEventCallback(DCMI_HandleTypeDef *hdcmi)
{
  BSP_CAMERA_LineEventCallback();
}

/**
  * @brief  Line Event callback.
  * @retval None
  */
__weak void BSP_CAMERA_LineEventCallback(void)
{
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_DCMI_LineEventCallback could be implemented in the user file
   */
}

/**
  * @brief  VSYNC event callback
  * @param  hdcmi: pointer to the DCMI handle
  * @retval None
  */
void HAL_DCMI_VsyncEventCallback(DCMI_HandleTypeDef *hdcmi)
{
  BSP_CAMERA_VsyncEventCallback();
}

/**
  * @brief  VSYNC Event callback.
  * @retval None
  */
__weak void BSP_CAMERA_VsyncEventCallback(void)
{
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_DCMI_VsyncEventCallback could be implemented in the user file
   */
}

/**
  * @brief  Frame event callback
  * @param  hdcmi: pointer to the DCMI handle
  * @retval None
  */
void HAL_DCMI_FrameEventCallback(DCMI_HandleTypeDef *hdcmi)
{
  BSP_CAMERA_FrameEventCallback();
}

/**
  * @brief  Frame Event callback.
  * @retval None
  */
__weak void BSP_CAMERA_FrameEventCallback(void)
{
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_DCMI_FrameEventCallback could be implemented in the user file
   */
}

/**
  * @brief  Error callback
  * @param  hdcmi: pointer to the DCMI handle
  * @retval None
  */
void HAL_DCMI_ErrorCallback(DCMI_HandleTypeDef *hdcmi)
{
  BSP_CAMERA_ErrorCallback();
}

/**
  * @brief  Error callback.
  * @retval None
  */
__weak void BSP_CAMERA_ErrorCallback(void)
{
  /* NOTE : This function Should not be modified, when the callback is needed,
            the HAL_DCMI_ErrorCallback could be implemented in the user file
   */
}

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */

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


text:
from django.core.management.base import BaseCommand
from django.db import connection

from .createopenslidesuser import Command as CreateOpenslidesUser

class Command(BaseCommand):
    """
    Command to create an OpenSlides user.
    """

    help = "Creates an OpenSlides user with id=2 if no other user than the administrator were created before."

    def add_arguments(self, parser):
        parser.add_argument("first_name", help="The first name of the new user.")
        parser.add_argument("last_name", help="The last name of the new user.")
        parser.add_argument("username", help="The username of the new user.")
        parser.add_argument("password", help="The password of the new user.")
        parser.add_argument("groups_id", help="The group id of the new user.")
        parser.add_argument("--email", help="The email address of the new user.")

    def handle(self, *args, **options):
        options["userid"] = 2

        with connection.cursor() as cursor:
            cursor.execute("SELECT last_value FROM users_user_id_seq;")
            last_id = cursor.fetchone()[0]
            if last_id > 1:
                self.stdout.write(
                    self.style.NOTICE(
                        "There have users been created before. Do nothing."
                    )
                )
                return

        CreateOpenslidesUser().handle(**options)


text:
package net.ensode.javaee8book.jsfjpa;

import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

import net.ensode.javaee8book.Customer;
import net.ensode.javaee8book.CustomerDaoBean;

@Named
@RequestScoped
public class CustomerController implements Serializable {

    @EJB
    private CustomerDaoBean customerDaoBean;

    private Customer customer;

    private String firstName;
    private String lastName;
    private String email;

    public CustomerController() {
        customer = new Customer();
    }

    public String saveCustomer() {
        String returnValue = "customer_saved";

        try {
            populateCustomer();
            customerDaoBean.saveCustomer(customer);
        } catch (Exception e) {
            e.printStackTrace();
            returnValue = "error_saving_customer";
        }

        return returnValue;
    }

    private void populateCustomer() {
        if (customer == null) {
            customer = new Customer();
        }
        customer.setFirstName(getFirstName());
        customer.setLastName(getLastName());
        customer.setEmail(getEmail());
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}


text:
"""
LoL server
"""

import xmlrpclib
import res.canvas

ROOMS = {}

class BaseUnit(object):
    def __init__(self):
        self.style = None
        self.pos = None
        self.name = None

class NPCUnit(BaseUnit):
    def __init__(self):
        super(NPCUnit).__init__(self)
    pass

class HeroUnit(BaseUnit):
    pass

ERR_MAPNOTFOUND = RuntimeError('map not found')
ERR_ROOMEXISTS = RuntimeError('room already exists')
ERR_ROOMNOTFOUND = RuntimeError('room not found')

def _new_room(name, map_name):
    '''
    @return: error (like golang)
    '''
    if ROOMS.has_key(name):
        return ERR_ROOMEXISTS
    map_info = res.canvas.get(map_name)
    if not map_info:
        return ERR_MAPNOTFOUND
    ROOMS[name] = dict(map_name=map_name, map_info=map_info, persons=set())
    return

def _join_room(name, client_ip):
    room = ROOMS.get(name)
    if not room:
        return '', ERR_ROOMNOTFOUND
    room['persons'].add(client_ip)
    return room, None

def main():
    err = _new_room('hello', 'yy')
    assert err == ERR_MAPNOTFOUND

    err = _new_room('hello', 'plain')
    assert err == None

    err = _new_room('hello', 'plain')
    assert err == ERR_ROOMEXISTS

if __name__ == '__main__':
    main()


text:
package models

import (
	"time"
)

//store movieInfo
type MovieInfo struct {
	MovieId    uint64    `sql:"type:bigint(2)" gorm:"primary_key;column:movieId"`
	MovieName  string    `sql:"type:varchar(120);not null" gorm:"column:movieName"`
	TagName    string    `sql:"type:varchar(10);not null" gorm:"column:tagName"`
	MovieUrl   string    `sql:"type:varchar(70);not null" gorm:"column:movieUrl"`
	ReleasedAt string    `sql:"type:varchar(10)" gorm:"column:releasedAt"`
	UpdatedAt  time.Time `sql:"type:datetime(0);not null" gorm:"column:updatedAt"`
}

func (mi MovieInfo) TableName() string {
	return "movieInfo"
}

type MovieRatingInfo struct {
	MovieId        uint64    `sql:"type:bigint(2)" gorm:"primary_key;column:movieId"`
	MovieRating    float64   `sql:"type:float(3)" gorm:"column:movieRating"`
	UsersNumRating uint64    `sql:"type:bigint(1)" gorm:"column:usersNumRating"`
	TagName        string    `sql:"type:varchar(10);not null" gorm:"column:tagName"`
	UpdatedAt      time.Time `sql:"type:datetime(0);not null" gorm:"column:updatedAt"`
}

func (mri MovieRatingInfo) TableName() string {
	return "movieRatingInfo"
}


text:
RTTI_DEF1(ossimQuickbirdMetaData, "ossimQuickbirdMetaData", ossimObject);

// Define Trace flags for use within this file:
static ossimTrace traceExec  ("ossimQuickbirdMetaData:exec");
static ossimTrace traceDebug ("ossimQuickbirdMetaData:debug");

class QbMetadataParser
{
 public:
   bool openConnection(const ossimString &connectionString)
   {
      m_inputStream = ossim::StreamFactoryRegistry::instance()->createIstream(connectionString);
      return m_inputStream != nullptr;
   }
   bool nextLine(ossimString &line)
   {
      std::ostringstream out;
      line = "";
      if (m_inputStream->good())
      {
         char c = static_cast<char>(m_inputStream->get());
         while (!m_inputStream->eof() && m_inputStream->good() && c != '\n')
         {
            out.write(&c, 1);
            c = static_cast<char>(m_inputStream->get());
         }
         line = out.str();
      }

      return !line.empty();
   }
   bool parseConnection(const ossimString &connectionString)
   {
      bool result = false;

      if (openConnection(connectionString))
      {
         return parse();
      }

      return result;
   }
   bool parse();
   void splitKeyValue(const ossimString &input, ossimString &key, ossimString &value) const
   {
      key = input.before("=");
      value = input.after("=");
      key = key.trim();
      value = value.trim();
   }
   const std::shared_ptr<ossimKeywordlist> &getKwl() const
   {
      return m_kwl;
   }

   std::shared_ptr<ossim::istream> m_inputStream;
   std::shared_ptr<ossimKeywordlist> m_kwl;
   ossimString m_currentPrefix;
};

bool QbMetadataParser::parse() //std::istream& in, ossimKeywordlist& kwl, const ossimString& prefix)
{
   bool result = true;
   std::stack<ossimString> prefixStack;
   std::stack<ossim_int32> currentIdxStack;
   ossimString line;
   ossimString kwlString;
   ossim_int32 bandIdx = -1;
   ossim_int32 imageIdx = -1;
   ossimString fullKeyValue;
   ossimString key;
   ossimString value;
   prefixStack.push("");
   ossimString bandNames;
   m_kwl = std::make_shared<ossimKeywordlist>();
   while (result && !prefixStack.empty() && nextLine(line))
   {
      ossimString tempLine = line;
      tempLine = tempLine.trim();
      if (tempLine.startsWith("BEGIN_GROUP"))
      {
         ossimString currentPrefix = prefixStack.top();
         splitKeyValue(tempLine, key, value);
         ossimString test = value;
         test = test.downcase();
         if (test.startsWith("band"))
         {
            ossimString bandNameValue = value.after("_").downcase();
            if (bandNames.empty())
            {
               bandNames = bandNameValue;
            }
            else
            {
               bandNames += " " + bandNameValue;
            }
         }
         prefixStack.push(currentPrefix + value.downcase().trim() + ".");
      }
      else if (tempLine.startsWith("END_GROUP"))
      {
         prefixStack.pop();
         if (prefixStack.empty())
         {
            result = false;
         }
      }
      else if (tempLine.endsWith(";"))
      {
         if (!tempLine.startsWith("END"))
         {
            fullKeyValue += line;
            fullKeyValue = fullKeyValue.trim();
            splitKeyValue(fullKeyValue, key, value);
            value = value.trim().trim(";").trim("\"");
            key = prefixStack.top() + key.trim();
            m_kwl->add(key, value);
         }
         fullKeyValue = "";
      }
      else
      {
         fullKeyValue += line;
      }
   }
   if (!bandNames.empty())
   {
      m_kwl->add("band_name_list", bandNames);
   }
   return result;
}

ossimQuickbirdMetaData::ossimQuickbirdMetaData()
    : theGenerationDate("Unknown"),
      theBandId("Unknown"),
      theBitsPerPixel(0),
      theSatID("Unknown"),
      theTLCDate("Unknown"),
      theSunAzimuth(0.0),
      theSunElevation(0.0),
      theSatAzimuth(0.0),
      theSatElevation(0.0),
      theTDILevel(0),
      theAbsCalFactors(),
      theBandNameList("Unknown"),
      theImageSize(),
      thePNiirs(-1),
      theCloudCoverage(0.0)
{
   theImageSize.makeNan();
   theAbsCalFactors.clear();
}

ossimQuickbirdMetaData::~ossimQuickbirdMetaData()
{
}

bool ossimQuickbirdMetaData::open(const ossimFilename& imageFile,
                                  ossim_int32 qbParseTypes)
{
   static const char MODULE[] = "ossimQuickbirdMetaData::open";

   clearFields();

   //retrieve information from the metadata file
   //if the Quickbird tif is 02APR01105228-M1BS-000000128955_01_P001.TIF
   //the metadata file will be 02APR01105228-M1BS-000000128955_01_P001.IMD

   ossimFilename file = imageFile;

   if(qbParseTypes & QB_PARSE_TYPE_IMD)
   {
      file.setExtension(ossimString("IMD"));
      if (parseMetaData(file) == false)
      {
         if (traceDebug())
         {
            ossimNotify(ossimNotifyLevel_WARN)
                << MODULE << " errors parsing metadata" << std::endl;
         }
         return false;
      }
   }
   if (qbParseTypes & QB_PARSE_TYPE_ATT)
   {
      file.setExtension(ossimString("ATT"));
      if(!parse(m_attKwl, file))
      {
         if (traceDebug())
         {
            ossimNotify(ossimNotifyLevel_WARN)
                << MODULE << " errors parsing att" << std::endl;
         }
         return false;
      }
   }
   if (qbParseTypes & QB_PARSE_TYPE_EPH)
   {
      file.setExtension(ossimString("EPH"));
      if (!parse(m_ephKwl, file))
      {
         if (traceDebug())
         {
            ossimNotify(ossimNotifyLevel_WARN)
                << MODULE << " errors parsing eph" << std::endl;
         }
         return false;
      }
   }
   if (qbParseTypes & QB_PARSE_TYPE_GEO)
   {
      file.setExtension(ossimString("GEO"));
      if (!parse(m_geoKwl, file))
      {
         if (traceDebug())
         {
            ossimNotify(ossimNotifyLevel_WARN)
                << MODULE << " errors parsing geo" << std::endl;
         }
         return false;
      }
   }
   if (qbParseTypes & QB_PARSE_TYPE_RPB)
   {
      file.setExtension(ossimString("RPB"));
      if (!parse(m_rpbKwl, file))
      {
         if (traceDebug())
         {
            ossimNotify(ossimNotifyLevel_WARN)
                << MODULE << " errors parsing rpb" << std::endl;
         }
         return false;
      }
   }
   if (qbParseTypes & QB_PARSE_TYPE_TIL)
   {
      file.setExtension(ossimString("TIL"));
      if (!parse(m_tilKwl, file))
      {
         if (traceDebug())
         {
            ossimNotify(ossimNotifyLevel_WARN)
                << MODULE << " errors parsing til" << std::endl;
         }
         return false;
      }
   }

   return true;
}

void ossimQuickbirdMetaData::clearFields()
{
   theGenerationDate = "Unknown";
   theBitsPerPixel = 0;
   theBandId = "Unknown";
   theSatID = "Unknown";
   theTLCDate = "Unknown";
   theSunAzimuth = 0.0;
   theSunElevation = 0.0;
   theSatAzimuth = 0.0;
   theSatElevation = 0.0;
   theTDILevel = 0;
   theAbsCalFactors.clear();
   theBandNameList = "Unknown";
   theImageSize.makeNan();
   m_attKwl = nullptr;
   m_imdKwl = nullptr;
   m_ephKwl = nullptr;
   m_rpbKwl = nullptr;
   m_geoKwl = nullptr;
   m_tilKwl = nullptr;
   m_steKwl = nullptr;
}

std::ostream& ossimQuickbirdMetaData::print(std::ostream& out) const
{

   out << "\n----------------- Info on Quickbird Image -------------------"
       << "\n  "
       << "\n  Generation date:    " << theGenerationDate
       << "\n  Band Id:            " << theBandId
       << "\n  Bits per pixel:     " << theBitsPerPixel
       << "\n  Sat Id:             " << theSatID
       << "\n  TLC date:           " << theTLCDate
       << "\n  Sun Azimuth:        " << theSunAzimuth
       << "\n  Sun Elevation:      " << theSunElevation
       << "\n  Sat Azimuth:        " << theSatAzimuth
       << "\n  Sat Elevation:      " << theSatElevation
       << "\n  Band name list:     " << theBandNameList
       << "\n  TDI Level:          " << theTDILevel
       << "\n  abs Calibration Factors:   "
       << std::endl;
   for(unsigned int i=0; i<theAbsCalFactors.size(); i++)
   {
      out<<theAbsCalFactors[i] << "   ";
   }
   out << "\n  Image Size:         " << theImageSize
       << "\n"
       << "\n---------------------------------------------------------"
       << "\n  " << std::endl;
   return out;
}

bool ossimQuickbirdMetaData::saveState(ossimKeywordlist& kwl,
				       const char* prefix)const
{
   if(m_imdKwl)
   {
      kwl.add(prefix,
              ossimKeywordNames::TYPE_KW,
              "ossimQuickbirdMetaData",
              true);

      kwl.add(prefix,
              "generation_date",
              theGenerationDate,
              true);

      // will use generation date as the acquisition
      kwl.add(prefix,
              "acquisition_date",
              theGenerationDate,
              true);

      kwl.add(prefix,
              "bits_per_pixel",
              theBitsPerPixel,
              true);

      kwl.add(prefix,
              "band_id",
              theBandId,
              true);

      kwl.add(prefix,
              "sat_id",
              theSatID,
              true);

      kwl.add(prefix,
              "sensor_id",
              theSatID,
              true);

      kwl.add(prefix,
              "mission_id",
              theSatID,
              true);

      kwl.add(prefix,
              "tlc_date",
              theTLCDate,
              true);

      kwl.add(prefix,
              "sun_azimuth",
              theSunAzimuth,
              true);
      kwl.add(prefix,
              "sun_elevation",
              theSunElevation,
              true);

      kwl.add(prefix,
              ossimKeywordNames::AZIMUTH_ANGLE_KW,
              theSunAzimuth,
              true);

      kwl.add(prefix,
              ossimKeywordNames::ELEVATION_ANGLE_KW,
              theSunElevation,
              true);

      kwl.add(prefix,
              "sat_azimuth_angle",
              theSatAzimuth,
              true);

      kwl.add(prefix,
              "sat_elevation_angle",
              theSatElevation,
              true);

      kwl.add(prefix,
              "TDI_level",
              theTDILevel,
              true);
      kwl.add(prefix,
              "band_name_list",
              theBandNameList,
              true);

      if (thePNiirs > -1)
      {
         kwl.add(prefix,
                 "niirs",
                 thePNiirs,
                 true);
      }

      kwl.add(prefix,
              "cloud_cover",
              theCloudCoverage,
              true);

      if (theBandId == "Multi")
      {
         std::vector<ossimString> bandNameList = theBandNameList.split(" ");
         for (unsigned int i = 0; i < bandNameList.size(); ++i)
         {
            kwl.add(prefix,
                    bandNameList[i] + "_band_absCalFactor",
                    theAbsCalFactors[i],
                    true);
         }
      }
      else if (!theAbsCalFactors.empty())
      {
         kwl.add(prefix,
                 "absCalFactor",
                 theAbsCalFactors[0],
                 true);
      }
      ossimString testBandId = theBandId;
      testBandId = testBandId.upcase();
      if (testBandId == "MULTI")
      {
         kwl.add(prefix, "irep", "MULTI");
         kwl.add(prefix, "icat", "MS");
      }
      else if (testBandId == "P")
      {
         kwl.add(prefix, "irep", "MONO");
         kwl.add(prefix, "icat", "VIS");
      }
      else if( !testBandId.empty())
      {
         kwl.add(prefix, "irep", testBandId);
      }
      kwl.add(ossimString(prefix) + "imd.", *m_imdKwl);
   }
   if (m_attKwl)
   {
      kwl.add(ossimString(prefix) + "att.", *m_attKwl);
   }
   if (m_ephKwl)
   {
      kwl.add(ossimString(prefix) + "eph.", *m_ephKwl);
   }
   if (m_geoKwl)
   {
      kwl.add(ossimString(prefix) + "geo.", *m_geoKwl);
   }
   if (m_rpbKwl)
   {
      kwl.add(ossimString(prefix) + "rpb.", *m_rpbKwl);
   }
   if (m_steKwl)
   {
      kwl.add(ossimString(prefix) + "ste.", *m_rpbKwl);
   }
   if (m_tilKwl)
   {
      kwl.add(ossimString(prefix) + "til.", *m_tilKwl);
   }
   kwl.add(prefix,
           "organization",
           "DigitalGlobe",
           true);

   return true;
}

bool ossimQuickbirdMetaData::loadState(const ossimKeywordlist& kwl,
				       const char* prefix)
{
   clearFields();

   const char* lookup = 0;
   ossimString s;

   lookup = kwl.find(prefix, ossimKeywordNames::TYPE_KW);
   if (lookup)
   {
      s = lookup;
      if(s != "ossimQuickbirdMetaData")
      {
         return false;
      }
   }

   lookup = kwl.find(prefix, "generation_date");
   if (lookup)
   {
      theGenerationDate = lookup;
   }

   lookup = kwl.find(prefix, "band_id");
   if (lookup)
   {
      theBandId = lookup;
   }

   lookup = kwl.find(prefix, "bits_per_pixel");
   if (lookup)
   {
      s = lookup;
      theBitsPerPixel = s.toInt();;
   }

   lookup = kwl.find(prefix, "sat_id");
   if (lookup)
   {
      theSatID = lookup;
   }

   lookup = kwl.find(prefix, "tlc_date");
   if (lookup)
   {
      theTLCDate= lookup;
   }

   lookup = kwl.find(prefix, "TDI_level");
   if (lookup)
   {
      s = lookup;
      theTDILevel = s.toInt();
   }

   lookup = kwl.find(prefix, ossimKeywordNames::AZIMUTH_ANGLE_KW);
   if (lookup)
   {
      s = lookup;
      theSunAzimuth = s.toFloat64();
   }

   lookup = kwl.find(prefix, ossimKeywordNames::ELEVATION_ANGLE_KW);
   if (lookup)
   {
      s = lookup;
      theSunElevation = s.toFloat64();
   }

   lookup = kwl.find(prefix, "sat_azimuth_angle");
   if (lookup)
   {
      s = lookup;
      theSatAzimuth = s.toFloat64();
   }

   lookup = kwl.find(prefix, "sat_elevation_angle");
   if (lookup)
   {
      s = lookup;
      theSatElevation = s.toFloat64();
   }

   lookup = kwl.find(prefix, "sun_azimuth");
   if (lookup)
   {
      s = lookup;
      theSunAzimuth = s.toFloat64();
   }

   lookup = kwl.find(prefix, "sun_elevation");
   if (lookup)
   {
      s = lookup;
      theSunElevation = s.toFloat64();
   }

   lookup = kwl.find(prefix, "band_name_list");
   if (lookup)
   {
      theBandNameList= lookup;
   }
   lookup = kwl.find(prefix, "niirs");
   if (lookup)
   {
      thePNiirs = ossimString(lookup).toFloat64();
   }

   lookup = kwl.find(prefix, "cloud_cover");
   if(lookup)
   {
      theCloudCoverage = ossimString(lookup).toFloat64();
   }

   if(theBandId=="Multi")
   {
      std::vector<ossimString> bandNameList = theBandNameList.split(" ");
      theAbsCalFactors = std::vector<double>(bandNameList.size(), 1.);
      for(unsigned int i = 0 ; i < bandNameList.size() ; ++i)
      {
         lookup = kwl.find(prefix, bandNameList[i] + "_band_absCalFactor");
         if (lookup)
         {
            s = lookup;
            theAbsCalFactors[i] = s.toDouble();
         }
      }
   }
   else if (theBandId=="P")
   {
      theAbsCalFactors = std::vector<double>(1, 1.);
      lookup = kwl.find(prefix, "absCalFactor");
      if (lookup)
      {
         s = lookup;
         theAbsCalFactors[0] = s.toDouble();
      }
   }

   if (kwl.getNumberOfKeysThatMatch("^" + ossimString(prefix) + "imd."))
   {
      m_imdKwl = std::make_shared<ossimKeywordlist>();
      m_imdKwl->add(kwl , ossimString(prefix) + "imd.");
   }

   if (kwl.getNumberOfKeysThatMatch("^" + ossimString(prefix) + "att."))
   {
      m_attKwl = std::make_shared<ossimKeywordlist>();
      m_attKwl->add(kwl, ossimString(prefix) + "att.");
   }

   if (kwl.getNumberOfKeysThatMatch("^" + ossimString(prefix) + "geo."))
   {
      m_geoKwl = std::make_shared<ossimKeywordlist>();
      m_geoKwl->add(kwl, ossimString(prefix) + "geo.");
   }
   if (kwl.getNumberOfKeysThatMatch("^" + ossimString(prefix) + "rpb."))
   {
      m_rpbKwl = std::make_shared<ossimKeywordlist>();
      m_rpbKwl->add(kwl, ossimString(prefix) + "rpb.");
   }
   if (kwl.getNumberOfKeysThatMatch("^" + ossimString(prefix) + "ste."))
   {
      m_steKwl = std::make_shared<ossimKeywordlist>();
      m_steKwl->add(kwl, ossimString(prefix) + "ste.");
   }

   return true;
}

//*****************************************************************************
// PROTECTED METHOD: ossimQuickbirdMetaData::parseMetaData()
//
//  Parses the Quickbird IMD file.
//
//*****************************************************************************
bool ossimQuickbirdMetaData::parseMetaData(const ossimFilename& data_file)
{
   bool result = false;
   if (traceExec()) ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimQuickbirdMetaData::parseMetaData(data_file): entering..." << std::endl;

   if( !data_file.exists() )
   {
      if (traceExec()) ossimNotify(ossimNotifyLevel_WARN) << "ossimQuickbirdMetaData::parseMetaData(data_file) WARN:" << "\nmetadate data file <" << data_file << ">. " << "doesn't exist..." << std::endl;
      return result;
   }
   m_imdKwl = nullptr;

   //     std::shared_ptr<QbMetadataParser>
   //         qbMetadataParser = std::make_shared<QbMetadataParser>();
   // if (qbMetadataParser->parseConnection(data_file))
   if(parse(m_imdKwl, data_file))
   {
      // m_imdKwl = std::make_shared<ossimKeywordlist>(*qbMetadataParser->getKwl());
      ossimString value = m_imdKwl->find("generationTime");
      if(!value.empty())
      {
         theGenerationDate = value;
      }
      theBandId = m_imdKwl->find("bandId");

      value = m_imdKwl->find("numRows");
      if(!value.empty())
      {
         theImageSize.y = value.toInt64();
      }
      value = m_imdKwl->find("numColumns");
      if (!value.empty())
      {
         theImageSize.x = value.toInt64();
      }
      theBandId = m_imdKwl->find("bandId");

      value = m_imdKwl->find("nbitsPerPixel");
      if(!value.empty())
      {
         theBitsPerPixel = value.toInt32();
      }
      theBandNameList = m_imdKwl->find("band_name_list");
      std::vector<ossimString> bandList;
      theBandNameList.split(bandList, " ");
      if(bandList.size()>0)
      {
         ossim_uint32 idx = 0;
         theAbsCalFactors = std::vector<double>(bandList.size(), 1.0);
         for(auto band:bandList)
         {
            value = m_imdKwl->find("band_"+band+".absCalFactor");
            if(!value.empty())
            {
               theAbsCalFactors[idx] = value.toFloat64();
            }
            ++idx;
         }
      }
      theSatID = m_imdKwl->find("image_1.satId");
      theTLCDate = m_imdKwl->find("image_1.TLCTime");
      if(theTLCDate.empty())
      {
         theTLCDate = m_imdKwl->find("image_1.firstLineTime");
      }
      value = m_imdKwl->find("sunAz");
      if (!value.empty())
      {
         theSunAzimuth = value.toFloat64();
      }
      else
      {
         value = m_imdKwl->find("image_1.meanSunAz");
         if (!value.empty())
         {
            theSunAzimuth = value.toFloat64();
         }
      }
      value = m_imdKwl->find("sunEl");
      if (!value.empty())
      {
         theSunElevation = value.toFloat64();
      }
      else
      {
         value = m_imdKwl->find("image_1.meanSunEl");
         if (!value.empty())
         {
            theSunElevation = value.toFloat64();
         }
      }
      value = m_imdKwl->find("image_1.satAz");
      if (!value.empty())
      {
         theSatAzimuth = value.toFloat64();
      }
      else
      {
         value = m_imdKwl->find("image_1.meanSatAz");
         if (!value.empty())
         {
            theSatAzimuth = value.toFloat64();
         }
      }
      value = m_imdKwl->find("image_1.cloudCover");
      if (!value.empty())
      {
         theCloudCoverage = value.toFloat64();
      }
      value = m_imdKwl->find("image_1.PNIIRS");
      if (!value.empty())
      {
         thePNiirs = value.toFloat64();
      }

      result = true;
   }

   return result;
}

bool ossimQuickbirdMetaData::parse(std::shared_ptr<ossimKeywordlist> &kwl,
                                   const ossimFilename &file)
{
   bool result = false;
   if (!file.exists())
   {
      if (traceExec())
         ossimNotify(ossimNotifyLevel_WARN) << "ossimQuickbirdMetaData::parse(file) WARN:"
                                            << "\ndata file <" << file << ">. "
                                            << "doesn't exist..." << std::endl;
      return result;
   }
   std::shared_ptr<QbMetadataParser> qbMetadataParser = std::make_shared<QbMetadataParser>();
   if (qbMetadataParser->parseConnection(file))
   {
      kwl = std::make_shared<ossimKeywordlist>(*qbMetadataParser->getKwl());
      result = kwl->getSize() > 0;
   }
   return result;
}

ossimString ossimQuickbirdMetaData::getSatID() const
{
   return theSatID;
}

bool ossimQuickbirdMetaData::getMapProjectionKwl( const ossimFilename& imd_file,
                                                  ossimKeywordlist& kwl )
{
   static const char MODULE[] = "ossimQuickbirdMetaData::getMapProjectionKwl";
   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " entered...\n";
   }

   bool result = false;

   if( imd_file.exists() )
   {
      FILE* fptr = fopen (imd_file.c_str(), "r");
      if (fptr)
      {

         char* strptr(NULL);

         //---
         // Read the file into a buffer:
         //---
         ossim_int32 fileSize = static_cast<ossim_int32>(imd_file.fileSize());
         char* filebuf = new char[fileSize];
         fread(filebuf, 1, fileSize, fptr);
         strptr = filebuf;
         fclose(fptr);
         ossimString imd_key;
         ossimString tempStr;
         std::string key;
         std::string value;

         // Loop until we find all our keys or bust out with error.
         while ( 1 )
         {
            // Verify map projected.
            imd_key = "BEGIN_GROUP = MAP_PROJECTED_PRODUCT";
            if ( strstr( filebuf, imd_key.c_str() ) == NULL )
            {
               break; // Not a map projected product.
            }

            // Get datum:
            if( getEndOfLine( strptr, ossimString("\n\tdatumName = "), "%13c %s", tempStr) )
            {
               if ( tempStr.contains("WE") )
               {
                  key = "dataum";
                  value   = "WGE";
                  kwl.addPair(key, value);
               }
               else
               {
                  if(traceDebug())
                  {
                     ossimNotify(ossimNotifyLevel_WARN)
                        << "Unhandled datum: " << tempStr << "\n";
                  }
               }
            }

            // Get projection:
            if( getEndOfLine( strptr, ossimString("\n\tmapProjName = "), "%15c %s", tempStr) )
            {
               if ( tempStr.contains("UTM") )
               {
                  key = "type";
                  value   = "ossimUtmProjection";
                  kwl.addPair(key, value);
               }
               else
               {
                  if(traceDebug())
                  {
                     ossimNotify(ossimNotifyLevel_WARN)
                        << "Unhandled projection name: " << tempStr << "\n";
                  }
               }
            }

             // Get projection:
            if( getEndOfLine( strptr, ossimString("\n\tmapProjName = "), "%15c %s", tempStr) )
            {
               if ( tempStr.contains("UTM") )
               {
                  key = "type";
                  value   = "ossimUtmProjection";
                  kwl.addPair(key, value);

                  // Get UTM zone:
                  if( getEndOfLine( strptr, ossimString("\n\tmapZone = "), "%11c %s", tempStr) )
                  {
                     key = "zone";
                     value = tempStr.trim(";").string();
                     kwl.addPair(key, value);
                  }
                  else
                  {
                     break;
                  }

                  // Get UTM hemisphere:
                  if( getEndOfLine( strptr, ossimString("\n\tmapHemi = "), "%11c %s", tempStr) )
                  {
                     key = "hemisphere";
                     tempStr = tempStr.trim(";");
                     tempStr = tempStr.trim("\"");
                     value = tempStr.string();
                     kwl.addPair(key, value);
                  }
                  else
                  {
                     break;
                  }

               } // End UTM:
            }

            // Get projection units:
            std::string units;
            if( getEndOfLine( strptr, ossimString("\n\tproductUnits = "), "%16c %s", tempStr) )
            {
               if ( tempStr == "\"M\";" )
               {
                  key = "units";
                  units = "meters";
                  kwl.addPair(key, units);
               }
               else
               {
                  if(traceDebug())
                  {
                     ossimNotify(ossimNotifyLevel_WARN)
                        << "Unhandled units: " << tempStr << "\n";
                  }
               }
            }

            // Get projection tie point:
            ossimDpt dpt;
            dpt.makeNan();
            if( getEndOfLine( strptr, ossimString("\n\toriginX = "), "%11c %s", tempStr) )
            {
               tempStr = tempStr.trim(";");
               dpt.x = tempStr.toFloat64();
            }
            else
            {
               break;
            }
            if( getEndOfLine( strptr, ossimString("\n\toriginY = "), "%11c %s", tempStr) )
            {
               tempStr = tempStr.trim(";");
               dpt.y = tempStr.toFloat64();
            }
            else
            {
               break;
            }
            if ( dpt.hasNans() == false )
            {
               key = "tie_point_units";
               kwl.addPair(key, units);

               key = "tie_point_xy";
               value = dpt.toString().string();
               kwl.addPair( key, value );
            }
            else
            {
               if(traceDebug())
               {
                  ossimNotify(ossimNotifyLevel_WARN)
                     << "tie point has nans!";
               }
               break;
            }

            // Get projection scale:
            dpt.makeNan();
            if( getEndOfLine( strptr, ossimString("\n\tcolSpacing = "), "%14c %s", tempStr) )
            {
               tempStr = tempStr.trim(";");
               dpt.x = tempStr.toFloat64();
            }
            else
            {
               break;
            }
            if( getEndOfLine( strptr, ossimString("\n\trowSpacing = "), "%14c %s", tempStr) )
            {
               tempStr = tempStr.trim(";");
               dpt.y = tempStr.toFloat64();
            }
            else
            {
               break;
            }

            if ( dpt.hasNans() == false )
            {
               key = "pixel_scale_units";
               kwl.addPair(key, units);

               key = "pixel_scale_xy";
               value = dpt.toString().string();
               kwl.addPair( key, value );
            }
            else
            {
               if(traceDebug())
               {
                  ossimNotify(ossimNotifyLevel_WARN)
                     << "scale has nans!";
               }
               break;
            }

            //---
            // End of key look up. If we get here set the status to true and
            // bust out of loop.
            //---
            result = true;
            break;
         }

         if ( result == false )
         {
            if(traceDebug())
            {
               ossimNotify(ossimNotifyLevel_DEBUG)
                  << "ERROR: Missing or unhandled key in metadat: " << imd_key << "\n";
            }
         }

         delete [] filebuf;
         filebuf = 0;
      }
      else
      {
         if (traceDebug())
         {
            ossimNotify(ossimNotifyLevel_DEBUG)
               << "ossimQuickbirdRpcModel::parseMetaData(imd_file) DEBUG:"
               << "\nCould not open Meta data file:  " << imd_file
	    << "\nreturning with error...\n";
         }
      }
   }

   if(traceDebug())
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << " exit status = " << (result?"true":"false") << "\n";
   }

   return result;
}
const std::shared_ptr<ossimKeywordlist> ossimQuickbirdMetaData::getImdKwl() const
{
   return m_imdKwl;
}

const std::shared_ptr<ossimKeywordlist> ossimQuickbirdMetaData::getAttKwl() const
{
   return m_attKwl;
}

const std::shared_ptr<ossimKeywordlist> ossimQuickbirdMetaData::getGeoKwl() const
{
   return m_geoKwl;
}

const std::shared_ptr<ossimKeywordlist> ossimQuickbirdMetaData::getEphKwl() const
{
   return m_ephKwl;
}

const std::shared_ptr<ossimKeywordlist> ossimQuickbirdMetaData::getRpbKwl() const
{
   return m_rpbKwl;
}
//*****************************************************************************
// PROTECTED METHOD: ossimQuickbirdMetaData::getEndOfLine
//
// //  Parse a char * to find another char *. Change the pointer only if the second char * is found.
//
//*****************************************************************************
bool ossimQuickbirdMetaData::getEndOfLine( char * fileBuf,
                                           ossimString lineBeginning,
                                           const char * format,
                                           ossimString & name)
{
   //char * res = strstr(fileBuf, lineBeginning.c_str());
   //if (!res)
   //{
   //  return false;
   // }
   //// if the lineBeginning is found, update the start pointer adress
   //fileBuf = res;

   //char dummy[80], nameChar[80];
   //sscanf(res, format, dummy, nameChar);
   //name = ossimString(nameChar);

   char * res = strstr(fileBuf, lineBeginning.c_str());
   if(!res)
   {
      return false;
   }
   fileBuf = strstr(fileBuf, lineBeginning.c_str());
   char dummy[80], nameChar[80];
   sscanf(fileBuf, format, dummy, nameChar);
   name = ossimString(nameChar);

   return true;
}

const ossimIpt& ossimQuickbirdMetaData::getImageSize() const
{
   return theImageSize;
}


text:
package io.github.forec.videoplayer.main;

import io.github.forec.videoplayer.views.MainWindow;

import java.awt.EventQueue;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.SwingWorker;

import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;

import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;

public class PlayerMain {

	static MainWindow frame;
	public static void main(String[] args) {
		if (RuntimeUtil.isWindows()){
			NativeLibrary.addSearchPath(
				RuntimeUtil.getLibVlcLibraryName(),
				"E:\\Program Files\\VLC");
		}
		Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);

		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frame = new MainWindow();
					frame.setTitle("常常播放器");
					frame.setVisible(true);
					frame.getMediaPlayer().prepareMedia(frame.getLocate());
					new SwingWorker<String, Integer>() {

						@Override
						protected String doInBackground() throws Exception {
							while(true){
								long total = frame.getMediaPlayer().getLength();
								long curr = frame.getMediaPlayer().getTime();
								float percent = (float)curr/total;
								publish((int)(percent*100));
						//		System.out.println((int)percent*100);
								Thread.sleep(100);
							}
						}
						protected void process(java.util.List<Integer> chunks) {
							for (int v:chunks){
								frame.getProgressBar().setValue(v);
							}
						};
					}.execute();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	public static void play(){
		frame.getMediaPlayer().play();
	}
	public static void pause(){
		frame.getMediaPlayer().pause();
	}
	public static void stop(){
		frame.getMediaPlayer().stop();
	}
	public static void jump(float to){
		frame.getMediaPlayer().setTime((long)(to*frame.getMediaPlayer().getLength()));
	}
	public static void openVideo(){
		JFileChooser chose = new JFileChooser();
		int value = chose.showOpenDialog(frame);
		if (value == JFileChooser.APPROVE_OPTION){
			File file = chose.getSelectedFile();
			frame.setLocate(file.getAbsolutePath());
			frame.getMediaPlayer().prepareMedia(file.getAbsolutePath());
		}
	}
	public static void openSubtitle(){
		JFileChooser chose = new JFileChooser();
		int value = chose.showOpenDialog(frame);
		if (value == JFileChooser.APPROVE_OPTION){
			File file = chose.getSelectedFile();
			frame.getMediaPlayer().setSubTitleFile(file);
		}
	}
	public static void exit(){
		frame.getMediaPlayer().release();
		System.exit(0);
	}
	public static void setVol(int v){
		frame.getMediaPlayer().setVolume(v);
	}
}


text:
callable = lambda x: hasattr(x, "__call__")
anything = lambda x: True
nothing = lambda x: x is None
iterable = lambda x: hasattr(x, "__iter__")

class TypeCheckError(Exception): pass

class TypeCheckSpecificationError(Exception): pass

class InputParameterError(TypeCheckError): pass

class ReturnValueError(TypeCheckError): pass

# Type checking
def isObjOfType(obj, _type):
    return type(obj) in ([_type] + _type.__subclasses__())

class Checker(object):
    def __call__(self, value):
        return self.check(value)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<title>Plugin: domiterator</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<link rel="stylesheet" type="text/css" href="../../test.css" />

caption

			head1

cell1

		cell2

<textarea id="iterResult2">

caption

head1

cell1

cell2

</textarea>

item1

item2

item3

item5

item5

<textarea id="iterResult3">

item1

item2

item3

item5

item5

</textarea>

paragraph
text

<textarea id="iterResult4">

paragraph

text

</textarea>

paragraph

<textarea id="iterResult7">
paragraph
</textarea>

paragraph

<textarea id="iterResult8">
paragraph
</textarea>

<form id="iterContainer9">non-paragraph</form>
<textarea id="iterResult9">
non-paragraph
</textarea>

para1

para2


text:
package sagex.phoenix.vfs.sources;

import java.util.Set;

import sagex.phoenix.factory.ConfigurableOption;
import sagex.phoenix.factory.ConfigurableOption.DataType;
import sagex.phoenix.factory.ConfigurableOption.ListSelection;
import sagex.phoenix.factory.Factory;
import sagex.phoenix.vfs.CombinedMediaFolder;
import sagex.phoenix.vfs.IMediaFolder;
import sagex.phoenix.vfs.sage.SageSourcesMediaFolder;

/**
 * Simple factory for creating a structured source from a sage media mask. ie,
 * this factory will create a hierarch structure of sage media files.
 *
 * @author seans
 */
public class SageSourcesFactory extends Factory<IMediaFolder> {
    public SageSourcesFactory() {
        super();

        // defined options
        addOption(new ConfigurableOption("mediamask", "Sage Media Mask", null, DataType.string, true, ListSelection.multi,
                "T:TV,D:DVD,B:BluRay,V:Video,M:Music,P:Pictures"));
        addOption(new ConfigurableOption("combine", "Combine Folders", null, DataType.bool));
    }

    public IMediaFolder create(Set<ConfigurableOption> altOptions) {
        boolean combine = getOption("combine", altOptions).getBoolean(false);
        String mediamask = getOption("mediamask", altOptions).getString(null);
        if (combine) {
            return new CombinedMediaFolder(new SageSourcesMediaFolder(mediamask, getLabel()), combine);
        } else {
            return new SageSourcesMediaFolder(mediamask, getLabel());
        }
    }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title>My Choice</title>
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
	<link href="https://fonts.googleapis.com/css?family=Abril+Fatface" rel="stylesheet">


text:
let overrides = {
  compiler_enable_hmr: true,
  compiler_public_path: '/'
};

export default overrides;


text:
package net.cortexmodders.lyoko.blocks;

import net.cortexmodders.lyoko.CodeLyoko;
import net.cortexmodders.lyoko.tileentity.TileEntityCable;
import net.cortexmodders.lyoko.tileentity.TileEntityHolomap;
import net.cortexmodders.lyoko.tileentity.TileEntityScanner;
import net.cortexmodders.lyoko.tileentity.TileEntitySuperCalc;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;

public class BlockCable extends BlockContainer
{
    public BlockCable()
    {
        super(Material.cloth);
        this.setCreativeTab(CodeLyoko.LyokoTabs);
        this.opaque = false;
    }

    @Override
    public void onNeighborBlockChange(World world, int x, int y, int z, Block neighborBlock)
    {
        if (world.getTileEntity(x, y, z) instanceof TileEntityCable) {
            TileEntityCable tile = (TileEntityCable) world.getTileEntity(x, y, z);
            if (neighborBlock instanceof BlockCable && tile != null) {
                String test1 = tile.getSector();
                this.syncBlock(world, x + 1, y, z, tile);
                this.syncBlock(world, x - 1, y, z, tile);
                this.syncBlock(world, x, y + 1, z, tile);
                this.syncBlock(world, x, y - 1, z, tile);
                this.syncBlock(world, x, y, z + 1, tile);
                this.syncBlock(world, x, y, z - 1, tile);
                String test2 = tile.getSector();

                if (!test1.equals(test2))
                    world.notifyBlocksOfNeighborChange(x, y, z, this);
                this.syncBlock2(world, x + 1, y, z, tile);
                this.syncBlock2(world, x - 1, y, z, tile);
                this.syncBlock2(world, x, y + 1, z, tile);
                this.syncBlock2(world, x, y - 1, z, tile);
                this.syncBlock2(world, x, y, z + 1, tile);
                this.syncBlock2(world, x, y, z - 1, tile);
                this.syncBlock3(world, x + 1, y, z, tile);
                this.syncBlock3(world, x - 1, y, z, tile);
                this.syncBlock3(world, x, y + 1, z, tile);
                this.syncBlock3(world, x, y - 1, z, tile);
                this.syncBlock3(world, x, y, z + 1, tile);
                this.syncBlock3(world, x, y, z - 1, tile);
                this.syncBlock4(world, x + 1, y, z, tile);
                this.syncBlock4(world, x - 1, y, z, tile);
                this.syncBlock4(world, x, y + 1, z, tile);
                this.syncBlock4(world, x, y - 1, z, tile);
                this.syncBlock4(world, x, y, z + 1, tile);
                this.syncBlock4(world, x, y, z - 1, tile);
            }
        }
    }

    public void syncBlock(World world, int x, int y, int z, TileEntityCable localCable)
    {
        if (world.getBlock(x, y, z) instanceof BlockCable && world.getTileEntity(x, y, z) instanceof TileEntityCable) {
            TileEntityCable tile = (TileEntityCable) world.getTileEntity(x, y, z);
            if (tile != null && localCable.getCoolDown() == 0 && !tile.getSector().equals("") && localCable.getSector().equals("")) {
                localCable.resetCoolDown();
                localCable.setSector(tile.getSector());
            }
        }
    }

    public void syncBlock2(World world, int x, int y, int z, TileEntityCable localCable)
    {
        if (world.getBlock(x, y, z) instanceof BlockScanner && world.getTileEntity(x, y, z) instanceof TileEntityScanner) {
            TileEntityScanner tile = (TileEntityScanner) world.getTileEntity(x, y, z);
            if (tile != null && !localCable.getSector().equals("") && tile.sector == -1) {
                tile.sector = this.convertSectorToInt(localCable.getSector());
                world.markBlockForUpdate(x, y, z);
            }
        }
    }

    public void syncBlock3(World world, int x, int y, int z, TileEntityCable localCable)
    {
        if (world.getBlock(x, y, z) instanceof BlockSuperCalc && world.getTileEntity(x, y, z) instanceof TileEntitySuperCalc) {
            TileEntitySuperCalc tile = (TileEntitySuperCalc) world.getTileEntity(x, y, z);
            if (tile != null && !localCable.getSector().equals("") && tile.sector.equals("")) {
                tile.sector = localCable.getSector();
                world.markBlockForUpdate(x, y, z);
            }
        }
    }

    public void syncBlock4(World world, int x, int y, int z, TileEntityCable localCable)
    {
        if (world.getBlock(x, y, z) instanceof BlockHolomap && world.getTileEntity(x, y, z) instanceof TileEntityHolomap) {
            TileEntityHolomap tile = (TileEntityHolomap) world.getTileEntity(x, y, z);
            if (tile != null && !localCable.getSector().equals("")) {
                tile.sector = (byte) (this.convertSectorToInt(localCable.getSector()) + 1);
                world.markBlockForUpdate(x, y, z);
            }
        }
    }

    public int convertSectorToInt(String sector)
    {
        if (sector.toLowerCase().equals("polar") || sector.toLowerCase().equals("ice"))
            return 0;
        else if (sector.toLowerCase().equals("desert"))
            return 1;
        else if (sector.toLowerCase().equals("forest"))
            return 2;
        else if (sector.toLowerCase().equals("mountain"))
            return 3;
        else if (sector.toLowerCase().equals("carthage"))
            return 4;
        return -1;
    }

    @Override
    public int getRenderBlockPass()
    {
        return 1;
    }

    @Override
    public int getRenderType()
    {
        return -1;
    }

    @Override
    public void registerBlockIcons(IIconRegister par1IconRegister)
    {
        this.blockIcon = par1IconRegister.registerIcon("lyoko:cable");
    }

    @Override
    public boolean isOpaqueCube()
    {
        return false;
    }

    private boolean validBlock(Block block, int side)
    {
        if (block instanceof BlockCable || block instanceof BlockSuperCalcConsole)
            return true;
        else if (block instanceof BlockSuperCalc && (side == 1 || side == 0))
            return true;
        else if (block instanceof BlockHolomap && side != 0)
            return true;
        else if (block instanceof BlockScanner && (side == 0 || side == 1))
            return true;
        return false;
    }

    @Override
    public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z)
    {
        this.setBlockBounds(0.3125F, 0.3125F, 0.3125F, 0.6875F, 0.6875F, 0.6875F);

        float minx = (float) this.minX;
        float maxx = (float) this.maxX;
        float miny = (float) this.minY;
        float maxy = (float) this.maxY;
        float minz = (float) this.minZ;
        float maxz = (float) this.maxZ;

        if (this.validBlock(world.getBlock(x - 1, y, z), 2))
            minx = 0;

        if (this.validBlock(world.getBlock(x + 1, y, z), 3))
            maxx = 1;

        if (this.validBlock(world.getBlock(x, y - 1, z), 0))
            miny = 0;

        if (this.validBlock(world.getBlock(x, y + 1, z), 1))
            maxy = 1;

        if (this.validBlock(world.getBlock(x, y, z - 1), 4))
            minz = 0;

        if (this.validBlock(world.getBlock(x, y, z + 1), 5))
            maxz = 1;

        this.setBlockBounds(minx, miny, minz, maxx, maxy, maxz);
    }

    @Override
    public TileEntity createNewTileEntity(World world, int metadata)
    {
        return new TileEntityCable();
    }
}


text:
Agregar Abono a proveedores

                <?php echo form_open('Abonoproveedores/addAbonoproveedores');?>
                <?php foreach($deudaspagar as $dp){ ?>

                        Fecha:
                        <input class="form-control" type="date" name="fecha" required>

                        Abono:
                        <input class="form-control" type="number" name="abono" placeholder="Introduce cantidad del abono" required>

                    <input type="hidden" name="iddeudas" value="<?php echo $dp->iddeudaspagar?>">

                    <button type="submit" class="btn btn-primary">Enviar</button>

                  <?php }?>
                </form>


text:
<?php
/**
 * IndexController
 *
 * @uses      Zend_Controller_Action
 * @package   Spindle
 * @license   New BSD {@link http://framework.zend.com/license/new-bsd}
 * @version   $Id: $
 */
class IndexController extends Zend_Controller_Action
{
    /**
     * Home page; redirect to pastebin landing page
     *
     * @return void
     */
    public function indexAction()
    {
        $this->_helper->redirector('index', 'paste', 'spindle');
    }
}


text:
using System;
using System.Collections.ObjectModel;
using System.Data;
using System.Management.Automation;
using Cognifide.PowerShell.Core.Utility;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Data.Managers;
using Version = Sitecore.Data.Version;

namespace Cognifide.PowerShell.Core.Provider
{
    public partial class PsSitecoreItemProvider : IDynamicParameters
    {
        [Flags]
        public enum TransferOptions
        {
            ChangeID = 1,
            AllowDefaultValues = 2,
            AllowStandardValues = 4
        }

        private const string FailSilentlyParam = "FailSilently";
        private const string QueryParam = "Query";
        private const string LanguageParam = "Language";
        private const string VersionParam = "Version";
        private const string StartWorkflowParam = "StartWorkflow";
        private const string PermanentlyParam = "Permanently";
        private const string ItemParam = "Item";
        private const string DestinationItemParam = "DestinationItem";
        private const string IdParam = "ID";
        private const string DatabaseParam = "Database";
        private const string UriParam = "Uri";
        private const string ParentParam = "Parent";
        private const string AmbiguousPathsParam = "AmbiguousPaths";
        private const string TransferOptionsParam = "TransferOptions";

        public object GetDynamicParameters()
        {
            return null;
        }

        public object GetPropertyDynamicParameters(string path, Collection<string> providerSpecificPickList)
        {
            return null;
        }

        public object ClearPropertyDynamicParameters(string path, Collection<string> propertyToClear)
        {
            return null;
        }

        public object SetPropertyDynamicParameters(string path, PSObject propertyValue)
        {
            return null;
        }

        protected static bool AddDynamicParameter(Type type, string name, ref RuntimeDefinedParameterDictionary dic)
        {
            return AddDynamicParameter(type, name, ref dic, false, false, string.Empty);
        }

        protected static bool AddDynamicParameter(Type type, string name, ref RuntimeDefinedParameterDictionary dic,
            bool valueFromPipeline)
        {
            return AddDynamicParameter(type, name, ref dic, valueFromPipeline, false, string.Empty);
        }

        protected static bool AddDynamicParameter(Type type, string name, ref RuntimeDefinedParameterDictionary dic,
            bool valueFromPipeline, bool valueFromPipelineByPropertyName)
        {
            return AddDynamicParameter(type, name, ref dic, valueFromPipeline, valueFromPipelineByPropertyName,
                string.Empty);
        }

        protected static bool AddDynamicParameter(Type type, string name, ref RuntimeDefinedParameterDictionary dic,
            bool valueFromPipeline, bool valueFromPipelineByPropertyName, string paramSetName, bool mandatory = false)
        {
            var paramAdded = false;

            if (dic == null || !dic.ContainsKey(name))
            {
                var attrib = new ParameterAttribute
                {
                    Mandatory = mandatory,
                    ValueFromPipeline = valueFromPipeline,
                    ValueFromPipelineByPropertyName = valueFromPipelineByPropertyName
                };
                if (!string.IsNullOrEmpty(paramSetName))
                {
                    attrib.ParameterSetName = paramSetName;
                }

                var param = new RuntimeDefinedParameter
                {
                    IsSet = false,
                    Name = name,
                    ParameterType = type
                };
                param.Attributes.Add(attrib);

                if (dic == null)
                {
                    dic = new RuntimeDefinedParameterDictionary();
                }
                dic.Add(name, param);
                paramAdded = true;
            }

            return paramAdded;
        }

        protected override object CopyItemDynamicParameters(string path, string destination, bool recurse)
        {
            LogInfo("Executing CopyItemDynamicParameters(string path='{0}', destination='{1}', string recurse='{2}')",
                path, destination, recurse);
            var dic = DynamicParameters as RuntimeDefinedParameterDictionary;
            var paramAdded = FailSilentlyDynamicParameters(ref dic);
            var sourceDrive = PathUtilities.GetDrive(path, SessionState.Drive.Current.Name);
            var destinationDrive = PathUtilities.GetDrive(destination, SessionState.Drive.Current.Name);
            if (!string.Equals(sourceDrive, destination, StringComparison.OrdinalIgnoreCase) &&
                Factory.GetDatabase(sourceDrive) != null && Factory.GetDatabase(destinationDrive) != null)
            {
                paramAdded |= AddDynamicParameter(typeof (TransferOptions), TransferOptionsParam, ref dic);
            }
            paramAdded |= AddDynamicParameter(typeof(Item), ItemParam, ref dic, true);
            paramAdded |= AddDynamicParameter(typeof(Item), DestinationItemParam, ref dic, false);
            return paramAdded ? dic : null;
        }

        protected override object MoveItemDynamicParameters(string path, string destination)
        {
            LogInfo("Executing MoveItemDynamicParameters(string path='{0}', destination='{1}')",
                path, destination);
            var dic = DynamicParameters as RuntimeDefinedParameterDictionary;
            var paramAdded = FailSilentlyDynamicParameters(ref dic);
            var sourceDrive = PathUtilities.GetDrive(path, SessionState.Drive.Current.Name);
            var destinationDrive = PathUtilities.GetDrive(destination, SessionState.Drive.Current.Name);
            if (!string.Equals(sourceDrive, destination, StringComparison.OrdinalIgnoreCase) &&
                Factory.GetDatabase(sourceDrive) != null && Factory.GetDatabase(destinationDrive) != null)
            {
                paramAdded |= AddDynamicParameter(typeof (TransferOptions), TransferOptionsParam, ref dic);
            }
            paramAdded |= AddDynamicParameter(typeof(Item), ItemParam, ref dic, true);
            paramAdded |= AddDynamicParameter(typeof(Item), DestinationItemParam, ref dic, false);
            return paramAdded ? dic : null;
        }

        protected override object RemoveItemDynamicParameters(string path, bool recurse)
        {
            LogInfo("Executing RemoveItemDynamicParameters(string path='{0}', string recurse='{1}')", path, recurse);
            var dic = DynamicParameters as RuntimeDefinedParameterDictionary;
            var paramAdded = FailSilentlyDynamicParameters(ref dic);
            paramAdded |= AddDynamicParameter(typeof (SwitchParameter), PermanentlyParam, ref dic);
            paramAdded |= AddDynamicParameter(typeof(Item), ItemParam, ref dic, true);
            return paramAdded ? dic : null;
        }

        protected bool IsDynamicParamSet(string paramName)
        {
            var dic = DynamicParameters as RuntimeDefinedParameterDictionary;
            return dic != null && dic[paramName].IsSet;
        }

        protected static bool FailSilentlyDynamicParameters(ref RuntimeDefinedParameterDictionary dic)
        {
            var paramAdded = false;
            paramAdded |= AddDynamicParameter(typeof (SwitchParameter), FailSilentlyParam, ref dic);
            return paramAdded;
        }

        private bool TryGetDynamicParam<T>(string paramName, out T result)
        {
            // language selection
            var dic = DynamicParameters as RuntimeDefinedParameterDictionary;
            bool defined = (dic != null && dic[paramName].IsSet);
            result = defined ? (T)dic[paramName].Value : default(T);
            return defined;
        }

        private void GetVersionAndLanguageParams(out int version, out string language)
        {
            // language selection
            var dic = DynamicParameters as RuntimeDefinedParameterDictionary;
            language = null;
            if (dic != null && dic[LanguageParam].IsSet)
            {
                var forcedLanguage = dic[LanguageParam].Value.ToString();
                language = forcedLanguage.Contains("*")
                    ? forcedLanguage
                    : LanguageManager.GetLanguage(forcedLanguage).Name;
            }

            version = Version.Latest.Number;
            if (dic != null && dic[VersionParam].IsSet)
            {
                int forcedVersion;
                var versionParam = dic[VersionParam].Value.ToString();
                if (versionParam == "*")
                {
                    version = Int32.MaxValue;
                }
                else if (Int32.TryParse(dic[VersionParam].Value.ToString(), out forcedVersion))
                {
                    version = forcedVersion;
                }
            }
        }

        protected override object GetChildItemsDynamicParameters(string path, bool recurse)
        {
            LogInfo("Executing GetChildItemsDynamicParameters(string path='{0}', string recurse='{1}')", path, recurse);
            var dic = DynamicParameters as RuntimeDefinedParameterDictionary;

            var paramAdded = AddDynamicParameter(typeof (string), LanguageParam, ref dic);
            paramAdded |= AddDynamicParameter(typeof (string), VersionParam, ref dic);
            paramAdded |= AddDynamicParameter(typeof (SwitchParameter), AmbiguousPathsParam, ref dic);
            paramAdded |= AddDynamicParameter(typeof(Item), ItemParam, ref dic, true);
            paramAdded |= AddDynamicParameter(typeof(string), IdParam, ref dic, false, false);

            return paramAdded ? dic : null;
        }

        protected override object GetChildNamesDynamicParameters(string path)
        {
            /* for now we'll just use the same parameters as gci */
            return GetChildItemsDynamicParameters(path, false);
        }

        protected override object GetItemDynamicParameters(string path)
        {
            LogInfo("Executing GetItemDynamicParameters(string path='{0}')", path);
            var dic = DynamicParameters as RuntimeDefinedParameterDictionary;

            var paramAdded = AddDynamicParameter(typeof (string), LanguageParam, ref dic);
            paramAdded |= AddDynamicParameter(typeof (string), VersionParam, ref dic);
            paramAdded |= AddDynamicParameter(typeof (string), QueryParam, ref dic, false, false);
            paramAdded |= AddDynamicParameter(typeof (string), IdParam, ref dic, false, false);
            paramAdded |= AddDynamicParameter(typeof (Database), DatabaseParam, ref dic, false, false);
            paramAdded |= AddDynamicParameter(typeof (string), UriParam, ref dic, false, true);
            paramAdded |= AddDynamicParameter(typeof (SwitchParameter), AmbiguousPathsParam, ref dic);

            return paramAdded ? dic : null;
        }

        private void CheckOperationAllowed(string operation, bool isOperationAllowed, string path)
        {
            if (!isOperationAllowed && !IsDynamicParamSet(FailSilentlyParam))
            {
                throw new UnauthorizedAccessException(
                    string.Format("Cannot {0} item {1} - Access to the path is denied.", operation, path));
            }
        }

        protected override object NewItemDynamicParameters(string path, string itemTypeName, object newItemValue)
        {
            LogInfo(
                "Executing NewItemDynamicParameters(string path='{0}', string itemTypeName='{1}', newItemValue='{2}')",
                path, itemTypeName, newItemValue);

            var dic = DynamicParameters as RuntimeDefinedParameterDictionary;
            var paramAdded = AddDynamicParameter(typeof (SwitchParameter), StartWorkflowParam, ref dic);
            paramAdded |= AddDynamicParameter(typeof (string), LanguageParam, ref dic);
            paramAdded |= AddDynamicParameter(typeof (Item), ParentParam, ref dic, true);
            return paramAdded ? dic : null;
        }
    }
}