text:
/*
 * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 * See https://github.com/openiddict/openiddict-core for more information concerning
 * the license and the contributors participating to this project.
 */

using System;
using System.ComponentModel;
using System.Security.Claims;
using JetBrains.Annotations;
using Microsoft.Extensions.Logging;
using OpenIddict.Abstractions;

namespace OpenIddict.Validation
{
    public static partial class OpenIddictValidationEvents
    {
        /// <summary>
        /// Represents an abstract base class used for certain event contexts.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public abstract class BaseContext
        {
            /// <summary>
            /// Creates a new instance of the <see cref="BaseContext"/> class.
            /// </summary>
            protected BaseContext([NotNull] OpenIddictValidationTransaction transaction)
                => Transaction = transaction ?? throw new ArgumentNullException(nameof(transaction));

            /// <summary>
            /// Gets the environment associated with the current request being processed.
            /// </summary>
            public OpenIddictValidationTransaction Transaction { get; }

            /// <summary>
            /// Gets or sets the endpoint type that handled the request, if applicable.
            /// </summary>
            public OpenIddictValidationEndpointType EndpointType
            {
                get => Transaction.EndpointType;
                set => Transaction.EndpointType = value;
            }

            /// <summary>
            /// Gets or sets the issuer address associated with the current transaction, if available.
            /// </summary>
            public Uri Issuer
            {
                get => Transaction.Issuer;
                set => Transaction.Issuer = value;
            }

            /// <summary>
            /// Gets the logger responsible of logging processed operations.
            /// </summary>
            public ILogger Logger => Transaction.Logger;

            /// <summary>
            /// Gets the OpenIddict validation options.
            /// </summary>
            public OpenIddictValidationOptions Options => Transaction.Options;

            /// <summary>
            /// Gets or sets the OpenIddict request or <c>null</c> if it couldn't be extracted.
            /// </summary>
            public OpenIddictRequest Request
            {
                get => Transaction.Request;
                set => Transaction.Request = value;
            }

            /// <summary>
            /// Gets or sets the OpenIddict response, if applicable.
            /// </summary>
            public OpenIddictResponse Response
            {
                get => Transaction.Response;
                set => Transaction.Response = value;
            }
        }

        /// <summary>
        /// Represents an abstract base class used for certain event contexts.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public abstract class BaseRequestContext : BaseContext
        {
            /// <summary>
            /// Creates a new instance of the <see cref="BaseRequestContext"/> class.
            /// </summary>
            protected BaseRequestContext([NotNull] OpenIddictValidationTransaction transaction)
                : base(transaction)
            {
            }

            /// <summary>
            /// Gets a boolean indicating whether the request was fully handled.
            /// </summary>
            public bool IsRequestHandled { get; private set; }

            /// <summary>
            /// Gets a boolean indicating whether the request processing was skipped.
            /// </summary>
            public bool IsRequestSkipped { get; private set; }

            /// <summary>
            /// Marks the request as fully handled. Once declared handled,
            /// a request shouldn't be processed further by the underlying host.
            /// </summary>
            public void HandleRequest() => IsRequestHandled = true;

            /// <summary>
            /// Marks the request as skipped. Once declared skipped, a request
            /// shouldn't be processed further by OpenIddict but should be allowed
            /// to go through the next components in the processing pipeline
            /// (if this pattern is supported by the underlying host).
            /// </summary>
            public void SkipRequest() => IsRequestSkipped = true;
        }

        /// <summary>
        /// Represents an abstract base class used for certain event contexts.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public abstract class BaseExternalContext : BaseValidatingContext
        {
            /// <summary>
            /// Creates a new instance of the <see cref="BaseRequestContext"/> class.
            /// </summary>
            protected BaseExternalContext([NotNull] OpenIddictValidationTransaction transaction)
                : base(transaction)
            {
            }

            /// <summary>
            /// Gets or sets the address of the external endpoint to communicate with.
            /// </summary>
            public Uri Address { get; set; }
        }

        /// <summary>
        /// Represents an abstract base class used for certain event contexts.
        /// </summary>
        [EditorBrowsable(EditorBrowsableState.Never)]
        public abstract class BaseValidatingContext : BaseRequestContext
        {
            /// <summary>
            /// Creates a new instance of the <see cref="BaseValidatingContext"/> class.
            /// </summary>
            protected BaseValidatingContext([NotNull] OpenIddictValidationTransaction transaction)
                : base(transaction)
            {
            }

            /// <summary>
            /// Gets a boolean indicating whether the request will be rejected.
            /// </summary>
            public bool IsRejected { get; protected set; }

            /// <summary>
            /// Gets or sets the "error" parameter returned to the client application.
            /// </summary>
            public string Error { get; private set; }

            /// <summary>
            /// Gets or sets the "error_description" parameter returned to the client application.
            /// </summary>
            public string ErrorDescription { get; private set; }

            /// <summary>
            /// Gets or sets the "error_uri" parameter returned to the client application.
            /// </summary>
            public string ErrorUri { get; private set; }

            /// <summary>
            /// Rejects the request.
            /// </summary>
            public virtual void Reject() => IsRejected = true;

            /// <summary>
            /// Rejects the request.
            /// </summary>
            /// <param name="error">The "error" parameter returned to the client application.</param>
            public virtual void Reject(string error)
            {
                Error = error;

                Reject();
            }

            /// <summary>
            /// Rejects the request.
            /// </summary>
            /// <param name="error">The "error" parameter returned to the client application.</param>
            /// <param name="description">The "error_description" parameter returned to the client application.</param>
            public virtual void Reject(string error, string description)
            {
                Error = error;
                ErrorDescription = description;

                Reject();
            }

            /// <summary>
            /// Rejects the request.
            /// </summary>
            /// <param name="error">The "error" parameter returned to the client application.</param>
            /// <param name="description">The "error_description" parameter returned to the client application.</param>
            /// <param name="uri">The "error_uri" parameter returned to the client application.</param>
            public virtual void Reject(string error, string description, string uri)
            {
                Error = error;
                ErrorDescription = description;
                ErrorUri = uri;

                Reject();
            }
        }

        /// <summary>
        /// Represents an event called when processing an incoming request.
        /// </summary>
        public class ProcessRequestContext : BaseValidatingContext
        {
            /// <summary>
            /// Creates a new instance of the <see cref="ProcessRequestContext"/> class.
            /// </summary>
            public ProcessRequestContext([NotNull] OpenIddictValidationTransaction transaction)
                : base(transaction)
            {
            }
        }

        /// <summary>
        /// Represents an event called when processing an errored response.
        /// </summary>
        public class ProcessErrorContext : BaseRequestContext
        {
            /// <summary>
            /// Creates a new instance of the <see cref="ProcessErrorContext"/> class.
            /// </summary>
            public ProcessErrorContext([NotNull] OpenIddictValidationTransaction transaction)
                : base(transaction)
            {
            }
        }

        /// <summary>
        /// Represents an event called when processing an authentication operation.
        /// </summary>
        public class ProcessAuthenticationContext : BaseValidatingContext
        {
            /// <summary>
            /// Creates a new instance of the <see cref="ProcessAuthenticationContext"/> class.
            /// </summary>
            public ProcessAuthenticationContext([NotNull] OpenIddictValidationTransaction transaction)
                : base(transaction)
            {
            }

            /// <summary>
            /// Gets or sets the security principal.
            /// </summary>
            public ClaimsPrincipal Principal { get; set; }

            /// <summary>
            /// Gets or sets the token to validate.
            /// </summary>
            public string Token { get; set; }

            /// <summary>
            /// Gets or sets the expected type of the token.
            /// </summary>
            public string TokenType { get; set; }
        }

        /// <summary>
        /// Represents an event called when processing a challenge response.
        /// </summary>
        public class ProcessChallengeContext : BaseValidatingContext
        {
            /// <summary>
            /// Creates a new instance of the <see cref="ProcessChallengeContext"/> class.
            /// </summary>
            public ProcessChallengeContext([NotNull] OpenIddictValidationTransaction transaction)
                : base(transaction)
            {
            }
        }
    }
}


text:
"""
Support for ADS light sources.

For more details about this platform, please refer to the documentation.
https://home-assistant.io/components/light.ads/

"""
import logging
import voluptuous as vol
from homeassistant.components.light import Light, ATTR_BRIGHTNESS, \
    SUPPORT_BRIGHTNESS, PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME
from homeassistant.components.ads import DATA_ADS, CONF_ADS_VAR, \
    CONF_ADS_VAR_BRIGHTNESS
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['ads']
DEFAULT_NAME = 'ADS Light'
CONF_ADSVAR_BRIGHTNESS = 'adsvar_brightness'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_ADS_VAR): cv.string,
    vol.Optional(CONF_ADS_VAR_BRIGHTNESS): cv.string,
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string
})

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the light platform for ADS."""
    ads_hub = hass.data.get(DATA_ADS)

    ads_var_enable = config.get(CONF_ADS_VAR)
    ads_var_brightness = config.get(CONF_ADS_VAR_BRIGHTNESS)
    name = config.get(CONF_NAME)

    add_entities([AdsLight(ads_hub, ads_var_enable, ads_var_brightness,
                           name)], True)

class AdsLight(Light):
    """Representation of ADS light."""

    def __init__(self, ads_hub, ads_var_enable, ads_var_brightness, name):
        """Initialize AdsLight entity."""
        self._ads_hub = ads_hub
        self._on_state = False
        self._brightness = None
        self._name = name
        self.ads_var_enable = ads_var_enable
        self.ads_var_brightness = ads_var_brightness

    async def async_added_to_hass(self):
        """Register device notification."""
        def update_on_state(name, value):
            """Handle device notifications for state."""
            _LOGGER.debug('Variable %s changed its value to %d', name, value)
            self._on_state = value
            self.schedule_update_ha_state()

        def update_brightness(name, value):
            """Handle device notification for brightness."""
            _LOGGER.debug('Variable %s changed its value to %d', name, value)
            self._brightness = value
            self.schedule_update_ha_state()

        self.hass.async_add_executor_job(
            self._ads_hub.add_device_notification,
            self.ads_var_enable, self._ads_hub.PLCTYPE_BOOL, update_on_state
        )
        if self.ads_var_brightness is not None:
            self.hass.async_add_executor_job(
                self._ads_hub.add_device_notification,
                self.ads_var_brightness, self._ads_hub.PLCTYPE_INT,
                update_brightness
            )

    @property
    def name(self):
        """Return the name of the device if any."""
        return self._name

    @property
    def brightness(self):
        """Return the brightness of the light (0..255)."""
        return self._brightness

    @property
    def is_on(self):
        """Return if light is on."""
        return self._on_state

    @property
    def should_poll(self):
        """Return False because entity pushes its state to HA."""
        return False

    @property
    def supported_features(self):
        """Flag supported features."""
        support = 0
        if self.ads_var_brightness is not None:
            support = SUPPORT_BRIGHTNESS
        return support

    def turn_on(self, **kwargs):
        """Turn the light on or set a specific dimmer value."""
        brightness = kwargs.get(ATTR_BRIGHTNESS)
        self._ads_hub.write_by_name(self.ads_var_enable, True,
                                    self._ads_hub.PLCTYPE_BOOL)

        if self.ads_var_brightness is not None and brightness is not None:
            self._ads_hub.write_by_name(self.ads_var_brightness, brightness,
                                        self._ads_hub.PLCTYPE_UINT)

    def turn_off(self, **kwargs):
        """Turn the light off."""
        self._ads_hub.write_by_name(self.ads_var_enable, False,
                                    self._ads_hub.PLCTYPE_BOOL)

redpajama_set_name: RedPajamaGithub


text:
package com.example.therevengeofbuil.coolwheterapplication;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * To work on unit tests, switch the Test Artifact in the Build Variants view.
 */
public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.HybridData.Models
{
    public partial class HybridDataManagerPatch : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Sku))
            {
                writer.WritePropertyName("sku");
                writer.WriteObjectValue(Sku);
            }
            if (Optional.IsCollectionDefined(Tags))
            {
                writer.WritePropertyName("tags");
                writer.WriteStartObject();
                foreach (var item in Tags)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteStringValue(item.Value);
                }
                writer.WriteEndObject();
            }
            writer.WriteEndObject();
        }
    }
}


text:
All notable changes (since version 3.4.0) to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

## [3.4.0] - 2020-03-10
### Added
- Laravel 7 support

[Unreleased]: https://github.com/felixkiss/uniquewith-validator/compare/v3.4.0...HEAD
[3.4.0]: https://github.com/felixkiss/uniquewith-validator/compare/v3.3.1...v3.4.0


text:
package com.lizy.myglide.request.target;

import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;

import com.lizy.myglide.manager.LifecycleListener;
import com.lizy.myglide.request.Request;
import com.lizy.myglide.request.transtion.Transition;

/**
 * Created by lizy on 16-5-3.
 */
public interface Target<R> extends LifecycleListener {

    int SIZE_ORIGINAL = Integer.MIN_VALUE;

    void onLoadStarted(@Nullable Drawable placeHolder);

    void onLoadFailed(@Nullable Drawable errorHolder);

    void onLoadCleared(@Nullable Drawable placeHolder);

    void onResourceReady(R source, Transition<? super R> transition);

    void getSize(SizeReadyCallback callback);

    void setRequest(@Nullable Request request);

    @Nullable
    Request getRequest();
}


text:
<?php namespace Cmgmyr\Messenger;

use Illuminate\Support\ServiceProvider;

class MessengerServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->package('cmgmyr/messenger');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['messenger'];
    }
}


text:
set(HAL_DRIVERS_F0
    adc can cec comp cortex crc dac dma exti flash gpio i2c i2s irda iwdg pcd
    pwr rcc rtc smartcard smbus spi tim tsc uart usart wwdg
)
set(HAL_EX_DRIVERS_F0
    adc crc dac flash i2c pcd pwr rcc rtc smartcard spi tim uart usart
)
set(HAL_LL_DRIVERS_F0
    adc comp crc crs dac dma exti gpio i2c pwr rcc rtc spi tim usart usb utils
)

set(HAL_DRIVERS_F1
    adc can cec cortex crc dac dma eth exti flash gpio hcd i2c i2s irda iwdg
    mmc nand nor pccard pcd pwr rcc rtc sd smartcard spi sram tim uart usart
    wwdg
)
set(HAL_EX_DRIVERS_F1
    adc dac flash gpio pcd rcc rtc tim
)
set(HAL_LL_DRIVERS_F1
    adc crc dac dma exti fsmc gpio i2c pwr rcc rtc sdmmc spi tim usart usb utils
)

set(HAL_DRIVERS_F2
    adc can cortex crc cryp dac dcmi dma eth exti flash gpio hash hcd i2c i2s
    irda iwdg mmc nand nor pccard pcd pwr rcc rng rtc sd smartcard spi sram tim
    uart usart wwdg
)
set(HAL_EX_DRIVERS_F2
    adc dac dcmi dma flash pcd pwr rcc rtc tim
)
set(HAL_LL_DRIVERS_F2
    adc crc dac dma exti fsmc gpio i2c pwr rcc rng rtc sdmmc spi tim usart usb
    utils
)

set(HAL_DRIVERS_F3
    adc can cec comp cortex crc dac dma exti flash gpio hrtim i2c i2s irda iwdg
    nand nor opamp pccard pcd pwr rcc rtc sdadc smartcard smbus spi sram tim tsc
    uart usart wwdg
)
set(HAL_EX_DRIVERS_F3
    adc crc dac flash i2c i2s opamp pcd pwr rcc rtc smartcard spi tim uart usart
)
set(HAL_LL_DRIVERS_F3
    adc comp crc dac dma exti fmc gpio hrtim i2c opamp pwr rcc rtc spi tim usart
    usb utils
)

set(HAL_DRIVERS_F4
    adc can cec cortex crc cryp dac dcmi dfsdm dma dma2d dsi eth exti flash
    flash_ramfunc fmpi2c gpio hash hcd i2c i2s irda iwdg lptim ltdc mmc nand nor
    pccard pcd pwr qspi rcc rng rtc sai sd sdram smartcard smbus spdifrx spi
    sram tim uart usart wwdg
)
set(HAL_EX_DRIVERS_F4
    adc cryp dac dcmi dma flash fmpi2c hash i2c i2s ltdc pcd pwr rcc rtc sai tim
)
set(HAL_LL_DRIVERS_F4
    adc crc dac dma dma2d exti fmc fsmc gpio i2c lptim pwr rcc rng rtc sdmmc spi
    tim usart usb utils
)

set(HAL_DRIVERS_F7
    adc can cec cortex crc cryp dac dcmi dfsdm dma dma2d dsi eth exti flash
    gpio hash hcd i2c i2s irda iwdg jpeg lptim ltdc mdios mmc nand nor pcd pwr
    qspi rcc rng rtc sai sd sdram smartcard smbus spdifrx spi sram tim uart
    usart wwdg
)
set(HAL_EX_DRIVERS_F7
    adc crc cryp dac dcmi dma flash hash i2c ltdc pcd pwr rcc rtc sai smartcard
    spi tim uart
)
set(HAL_LL_DRIVERS_F7
    adc crc dac dma dma2d exti fmc gpio i2c lptim pwr rcc rng rtc sdmmc spi tim
    usart usb utils
)

set(HAL_DRIVERS_G0
    adc cec comp cortex crc cryp dac dma exti flash gpio i2c i2s irda iwdg lptim
    pwr rcc rng rtc smartcard smbus spi tim uart usart wwdg
)
set(HAL_EX_DRIVERS_G0
    adc crc cryp dac dma flash i2c pwr rcc rtc smartcard spi tim uart usart
)
set(HAL_LL_DRIVERS_G0
    adc comp crc dac dma exti gpio i2c lptim lpuart pwr rcc rng rtc spi tim ucpd
    usart utils
)

set(HAL_DRIVERS_G4
    adc comp cordic cortex crc cryp dac dma exti fdcan flash flash_ramfunc fmac
    gpio hrtim i2c i2s irda iwdg lptim nand nor opamp pcd pwr qspi rcc rng rtc
    sai smartcard smbus spi sram tim uart usart wwdg
)
set(HAL_EX_DRIVERS_G4
    adc crc cryp dac dma flash i2c opamp pcd pwr rcc rtc sai smartcard spi tim
    uart usart
)
set(HAL_LL_DRIVERS_G4
    adc comp cordic crc crs dac dma exti fmac fmc gpio hrtim i2c lptim lpuart
    opamp pwr rcc rng rtc spi tim ucpd usart usb utils
)

set(HAL_DRIVERS_H7
    adc cec comp cordic cortex crc cryp dac dcmi dfsdm dma dma2d dsi dts eth exti fdcan
    flash fmac gfxmmu gpio hash hcd hrtim hsem i2c i2s irda iwdg jpeg lptim ltdc mdios
    mdma mmc nand nor opamp ospi otfdec pcd pssi pwr qspi ramecc rcc rng rtc sai
    sd sdram smartcard smbus spdifrx spi sram swpmi tim uart usart wwdg
)
set(HAL_EX_DRIVERS_H7
    adc crc cryp dac dfsdm dma eth flash hash i2c i2s ltdc mmc opamp pcd pwr rcc
    rng rtc sai sd smartcard spi tim uart usart
)
set(HAL_LL_DRIVERS_H7
    adc bdma comp cordic crc crs dac delayblock dma dma2d exti fmac fmc gpio hrtim i2c lptim
    lpuart mdma opamp pwr rcc rng rtc sdmmc spi swpmi tim usart usb utils
)

set(HAL_DRIVERS_L0
    adc comp cortex crc cryp dac dma firewall flash flash_ramfunc gpio i2c i2s
    irda iwdg lcd lptim pcd pwr rcc rng rtc smartcard smbus spi tim tsc uart
    usart wwdg
)
set(HAL_EX_DRIVERS_L0
    adc comp crc cryp dac flash i2c pcd pwr rcc rtc smartcard tim uart
)
set(HAL_LL_DRIVERS_L0
    adc comp crc crs dac dma exti gpio i2c lptim lpuart pwr rcc rng rtc spi tim
    usart usb utils
)

set(HAL_DRIVERS_L1
    adc comp cortex crc cryp dac dma flash flash_ramfunc gpio i2c i2s irda iwdg
    lcd nor opamp pcd pwr rcc rtc sd smartcard spi sram tim uart usart wwdg
)
set(HAL_EX_DRIVERS_L1
    adc cryp dac flash opamp pcd pcd pwr rcc rtc tim
)
set(HAL_LL_DRIVERS_L1
    adc comp crc dac dma exti fsmc gpio i2c opamp pwr rcc rtc sdmmc spi tim
    usart usb utils
)

set(HAL_DRIVERS_L4
    adc can comp cortex crc cryp dac dcmi dfsdm dma dma2d dsi exti firewall
    flash flash_ramfunc gfxmmu gpio hash hcd i2c irda iwdg lcd lptim ltdc mmc
    nand nor opamp ospi pcd pka pssi pwr qspi rcc rng rtc sai sd smartcard smbus
    spi sram swpmi tim tsc uart usart wwdg
)
set(HAL_EX_DRIVERS_L4
    adc crc cryp dac dfsdm dma flash hash i2c ltdc mmc opamp pcd pwr rcc rng rtc
    sai sd smartcard spi tim uart usart
)
set(HAL_LL_DRIVERS_L4
    adc comp crc crs dac dma dma2d exti fmc gpio i2c lptim lpuart opamp pka pwr
    rcc rng rtc sdmmc spi swpmi tim usart usb utils
)

set(HAL_DRIVERS_L5
    adc comp cortex crc cryp dac dfsdm dma exti fdcan flash flash_ramfunc gpio
    gtzc hash i2c icache irda iwdg lptim mmc nand nor opamp ospi pcd pka pwr rcc
    rng rtc sai sd smartcard smbus spi sram tim tsc uart usart wwdg
)
set(HAL_EX_DRIVERS_L5
    adc crc cryp dac dfsdm dma flash hash i2c mmc opamp pcd pwr rcc
    rng rtc sai sd smartcard spi tim uart usart
)
set(HAL_LL_DRIVERS_L5
    adc comp crc crs dac dma exti fmc gpio i2c lptim lpuart opamp pka pwr rcc
    rng rtc sdmmc spi tim ucpd usart usb utils
)

set(HAL_DRIVERS_MP1
    adc cec cortex crc cryp dac dcmi dfsdm dma exti fdcan gpio hash hsem i2c
    ipcc lptim mdios mdma pwr qspi rcc rng rtc sai sd smartcard smbus spdifrx
    spi sram tim uart usart wwdg
)
set(HAL_EX_DRIVERS_MP1
    adc crc cryp dac dfsdm dma hash i2c pwr rcc rtc sai sd smartcard spi tim
    uart usart
)
set(HAL_LL_DRIVERS_MP1
    adc delayblock dma exti fmc gpio i2c lptim pwr rcc rtc sdmmc spi tim usart
    utils
)

set(HAL_DRIVERS_U5
    adc comp cordic cortex crc cryp dac dcache dcmi dma dma2d exti fdcan flash fmac gpio
    gtzc hash hcd i2c icache irda iwdg lptim mdf mmc nand nor opamp ospi otfdec pcd pka pssi pwr ramcfg rcc
    rng rtc sai sd smartcard smbus spi sram tim tsc uart usart wwdg
)
set(HAL_EX_DRIVERS_U5
    adc crc cryp dac dma flash hash i2c mmc opamp pcd pwr rcc
    rng rtc sai sd smartcard smbus spi tim uart usart
)
set(HAL_LL_DRIVERS_U5
    adc comp cordic crc crs dac dlyb dma dma2d exti fmac fmc gpio i2c icache lpgpio lptim lpuart opamp pka pwr rcc
    rng rtc sdmmc spi tim ucpd usart usb utils
)

set(HAL_DRIVERS_WB
    adc comp cortex crc cryp dma exti flash gpio hsem
    i2c ipcc irda iwdg lcd lptim pcd pka pwr qspi rcc
    rng rtc sai smartcard smbus spi tim tsc uart usart wwdg
)
set(HAL_EX_DRIVERS_WB
    adc crc cryp dma flash i2c pcd pwr rcc
    rtc sai smartcard spi tim uart usart
)
set(HAL_LL_DRIVERS_WB
    adc comp crc crs dma exti gpio i2c lptim lpuart pka pwr rcc
    rng rtc spi tim usart usb utils
)

set(HAL_DRIVERS_WL
    adc comp cortex crc cryp dac dma exti flash gpio gtzc hsem
    i2c i2s ipcc irda iwdg lptim pka pwr rcc
    rng rtc smartcard smbus spi subghz tim uart usart wwdg
)
set(HAL_EX_DRIVERS_WL
    adc crc cryp dma flash i2c pwr rcc
    rng rtc smartcard spi tim uart usart
)
set(HAL_LL_DRIVERS_WL
    adc comp crc dac dma exti gpio i2c lptim lpuart pka pwr rcc
    rng rtc spi tim usart utils
)

foreach(FAMILY_SUFFIX ${STM32_SUPPORTED_FAMILIES_SHORT_NAME})
    list(APPEND HAL_DRIVERS ${HAL_DRIVERS_${FAMILY_SUFFIX}})
    list(APPEND HAL_LL_DRIVERS ${HAL_LL_DRIVERS_${FAMILY_SUFFIX}})
endforeach()
list(REMOVE_DUPLICATES HAL_DRIVERS)
list(REMOVE_DUPLICATES HAL_LL_DRIVERS)

foreach(COMP ${HAL_FIND_COMPONENTS})
    string(TOLOWER ${COMP} COMP_L)
    string(TOUPPER ${COMP} COMP_U)

    string(REGEX MATCH "^STM32([FGHLMUW]P?[0-9BL])([0-9A-Z][0-9M][A-Z][0-9A-Z])?_?(M0PLUS|M4|M7)?.*$" COMP_U ${COMP_U})
    if(CMAKE_MATCH_1)
        list(APPEND HAL_FIND_COMPONENTS_FAMILIES ${COMP})
        message(TRACE "FindHAL: append COMP ${COMP} to HAL_FIND_COMPONENTS_FAMILIES")
        continue()
    endif()
    if(${COMP_L} IN_LIST HAL_DRIVERS)
        list(APPEND HAL_FIND_COMPONENTS_DRIVERS ${COMP})
        message(TRACE "FindHAL: append COMP ${COMP} to HAL_FIND_COMPONENTS_DRIVERS")
        continue()
    endif()
    string(REGEX REPLACE "^ll_" "" COMP_L ${COMP_L})
    if(${COMP_L} IN_LIST HAL_LL_DRIVERS)
        list(APPEND HAL_FIND_COMPONENTS_DRIVERS_LL ${COMP})
        message(TRACE "FindHAL: append COMP ${COMP} to HAL_FIND_COMPONENTS_DRIVERS_LL")
        continue()
    endif()
    message(FATAL_ERROR "FindHAL: unknown HAL component: ${COMP}")
endforeach()

if(NOT HAL_FIND_COMPONENTS_FAMILIES)
    set(HAL_FIND_COMPONENTS_FAMILIES ${STM32_SUPPORTED_FAMILIES_LONG_NAME})
endif()

if(STM32H7 IN_LIST HAL_FIND_COMPONENTS_FAMILIES)
    list(REMOVE_ITEM HAL_FIND_COMPONENTS_FAMILIES STM32H7)
    list(APPEND HAL_FIND_COMPONENTS_FAMILIES STM32H7_M7 STM32H7_M4)
endif()

if(STM32WB IN_LIST HAL_FIND_COMPONENTS_FAMILIES)
    list(REMOVE_ITEM HAL_FIND_COMPONENTS_FAMILIES STM32WB)
    list(APPEND HAL_FIND_COMPONENTS_FAMILIES STM32WB_M4)
endif()

if(STM32WL IN_LIST HAL_FIND_COMPONENTS_FAMILIES)
    list(REMOVE_ITEM HAL_FIND_COMPONENTS_FAMILIES STM32WL)
    list(APPEND HAL_FIND_COMPONENTS_FAMILIES STM32WL_M4 STM32WL_M0PLUS)
endif()

if(STM32MP1 IN_LIST HAL_FIND_COMPONENTS_FAMILIES)
    list(REMOVE_ITEM HAL_FIND_COMPONENTS_FAMILIES STM32MP1)
    list(APPEND HAL_FIND_COMPONENTS_FAMILIES STM32MP1_M4)
endif()

list(REMOVE_DUPLICATES HAL_FIND_COMPONENTS_FAMILIES)

# when no explicit driver and driver_ll is given to find_component(HAL )
# then search for all supported driver and driver_ll
if((NOT HAL_FIND_COMPONENTS_DRIVERS) AND (NOT HAL_FIND_COMPONENTS_DRIVERS_LL))
    set(HAL_FIND_COMPONENTS_DRIVERS ${HAL_DRIVERS})
    set(HAL_FIND_COMPONENTS_DRIVERS_LL ${HAL_LL_DRIVERS})
endif()
list(REMOVE_DUPLICATES HAL_FIND_COMPONENTS_DRIVERS)
list(REMOVE_DUPLICATES HAL_FIND_COMPONENTS_DRIVERS_LL)

message(STATUS "Search for HAL families: ${HAL_FIND_COMPONENTS_FAMILIES}")
message(STATUS "Search for HAL drivers: ${HAL_FIND_COMPONENTS_DRIVERS}")
message(STATUS "Search for HAL LL drivers: ${HAL_FIND_COMPONENTS_DRIVERS_LL}")

foreach(COMP ${HAL_FIND_COMPONENTS_FAMILIES})
    string(TOUPPER ${COMP} COMP_U)

    string(REGEX MATCH "^STM32([FGHLMUW]P?[0-9BL])([0-9A-Z][0-9M][A-Z][0-9A-Z])?_?(M0PLUS|M4|M7)?.*$" COMP_U ${COMP_U})
    if(CMAKE_MATCH_3)
        set(CORE ${CMAKE_MATCH_3})
        set(CORE_C "::${CORE}")
        set(CORE_U "_${CORE}")
    else()
        unset(CORE)
        unset(CORE_C)
        unset(CORE_U)
    endif()

    set(FAMILY ${CMAKE_MATCH_1})
    string(TOLOWER ${FAMILY} FAMILY_L)

    if((NOT STM32_HAL_${FAMILY}_PATH) AND (NOT STM32_CUBE_${FAMILY}_PATH) AND (DEFINED ENV{STM32_CUBE_${FAMILY}_PATH}))
        set(STM32_CUBE_${FAMILY}_PATH $ENV{STM32_CUBE_${FAMILY}_PATH} CACHE PATH "Path to STM32Cube${FAMILY}")
        message(STATUS "ENV STM32_CUBE_${FAMILY}_PATH specified, using STM32_CUBE_${FAMILY}_PATH: ${STM32_CUBE_${FAMILY}_PATH}")
    endif()

    if((NOT STM32_HAL_${FAMILY}_PATH) AND (NOT STM32_CUBE_${FAMILY}_PATH))
        set(STM32_CUBE_${FAMILY}_PATH /opt/STM32Cube${FAMILY} CACHE PATH "Path to STM32Cube${FAMILY}")
        message(STATUS "Neither STM32_CUBE_${FAMILY}_PATH nor STM32_HAL_${FAMILY}_PATH specified using default STM32_CUBE_${FAMILY}_PATH: ${STM32_CUBE_${FAMILY}_PATH}")
    endif()

    #Checking HAL patch or release version
    unset(VERSION_INFO)
    find_file(PACKAGE_FILE NAMES package.xml PATHS ${STM32_CUBE_${FAMILY}_PATH})
    if(PACKAGE_FILE)
        file(READ ${PACKAGE_FILE} PACKAGE_FILE_CONTENT)
        string(REGEX MATCH "PackDescription Release=\"FW.${FAMILY}.([0-9.]+)\"( Patch=\"FW.${FAMILY}.([0-9.]+)\")?" VERSION_INFO ${PACKAGE_FILE_CONTENT})
        if(CMAKE_MATCH_3) # This is the "Patch" revision
            set(HAL_${COMP}_VERSION ${CMAKE_MATCH_3})
            set(HAL_VERSION ${CMAKE_MATCH_3})
        else(CMAKE_MATCH_1) #This is the "Release" version
            set(HAL_${COMP}_VERSION ${CMAKE_MATCH_1})
            set(HAL_VERSION ${CMAKE_MATCH_1})
        endif()
    endif()
    if(NOT VERSION_INFO)
        message(STATUS "Could not read the HAL version from package.xml for ${COMP}")
    endif()

    find_path(HAL_${FAMILY}_PATH
        NAMES Inc/stm32${FAMILY_L}xx_hal.h
        PATHS "${STM32_HAL_${FAMILY}_PATH}" "${STM32_CUBE_${FAMILY}_PATH}/Drivers/STM32${FAMILY}xx_HAL_Driver"
        NO_DEFAULT_PATH
    )
    if (NOT HAL_${FAMILY}_PATH)
        message(DEBUG "Missing HAL_${FAMILY}_PATH path")
        continue()
    endif()

    find_path(HAL_${FAMILY}${CORE_U}_INCLUDE
        NAMES stm32${FAMILY_L}xx_hal.h
        PATHS "${HAL_${FAMILY}_PATH}/Inc"
        NO_DEFAULT_PATH
    )
    find_file(HAL_${FAMILY}${CORE_U}_SOURCE
        NAMES stm32${FAMILY_L}xx_hal.c
        PATHS "${HAL_${FAMILY}_PATH}/Src"
        NO_DEFAULT_PATH
    )

    if ((NOT HAL_${FAMILY}${CORE_U}_INCLUDE) OR (NOT HAL_${FAMILY}${CORE_U}_SOURCE))
        set(HAL_${COMP}_FOUND FALSE)
        message(DEBUG "FindHAL: did not find path to HAL /src or /inc dir")
        continue()
    endif()

    if(NOT (TARGET HAL::STM32::${FAMILY}${CORE_C}))
        message(TRACE "FindHAL: creating library HAL::STM32::${FAMILY}${CORE_C}")
        add_library(HAL::STM32::${FAMILY}${CORE_C} INTERFACE IMPORTED)
        target_link_libraries(HAL::STM32::${FAMILY}${CORE_C} INTERFACE
                                                    STM32::${FAMILY}${CORE_C}
                                                    CMSIS::STM32::${FAMILY}${CORE_C})
        target_include_directories(HAL::STM32::${FAMILY}${CORE_C} INTERFACE "${HAL_${FAMILY}${CORE_U}_INCLUDE}")
        target_sources(HAL::STM32::${FAMILY}${CORE_C} INTERFACE "${HAL_${FAMILY}${CORE_U}_SOURCE}")
    endif()

    foreach(DRV_COMP ${HAL_FIND_COMPONENTS_DRIVERS})
        string(TOLOWER ${DRV_COMP} DRV_L)
        string(TOUPPER ${DRV_COMP} DRV)

        if(NOT (DRV_L IN_LIST HAL_DRIVERS_${FAMILY}))
            continue()
        endif()

        find_file(HAL_${FAMILY}${CORE_U}_${DRV}_SOURCE
            NAMES stm32${FAMILY_L}xx_hal_${DRV_L}.c
            PATHS "${HAL_${FAMILY}_PATH}/Src"
            NO_DEFAULT_PATH
        )
        list(APPEND HAL_${FAMILY}${CORE_U}_SOURCES "${HAL_${FAMILY}_${DRV}_SOURCE}")
        if(NOT HAL_${FAMILY}${CORE_U}_${DRV}_SOURCE)
            message(WARNING "Cannot find ${DRV} driver for ${FAMILY}${CORE_U}")
            set(HAL_${DRV_COMP}_FOUND FALSE)
            continue()
        endif()

        set(HAL_${DRV_COMP}_FOUND TRUE)
        if(HAL_${FAMILY}${CORE_U}_${DRV}_SOURCE AND (NOT (TARGET HAL::STM32::${FAMILY}::${DRV})))
            message(TRACE "FindHAL: creating library HAL::STM32::${FAMILY}${CORE_C}::${DRV}")
            add_library(HAL::STM32::${FAMILY}${CORE_C}::${DRV} INTERFACE IMPORTED)
            target_link_libraries(HAL::STM32::${FAMILY}${CORE_C}::${DRV} INTERFACE HAL::STM32::${FAMILY}${CORE_C})
            target_sources(HAL::STM32::${FAMILY}${CORE_C}::${DRV} INTERFACE "${HAL_${FAMILY}${CORE_U}_${DRV}_SOURCE}")
        endif()

        if(HAL_${FAMILY}${CORE_U}_${DRV}_SOURCE AND (${DRV_L} IN_LIST HAL_EX_DRIVERS_${FAMILY}))
            find_file(HAL_${FAMILY}${CORE_U}_${DRV}_EX_SOURCE
                NAMES stm32${FAMILY_L}xx_hal_${DRV_L}_ex.c
                PATHS "${HAL_${FAMILY}_PATH}/Src"
                NO_DEFAULT_PATH
            )
            list(APPEND HAL_${FAMILY}${CORE_U}_SOURCES "${HAL_${FAMILY}${CORE_U}_${DRV}_EX_SOURCE}")
            if(NOT HAL_${FAMILY}${CORE_U}_${DRV}_EX_SOURCE)
                message(WARNING "Cannot find ${DRV}Ex driver for ${FAMILY}${CORE_U}")
            endif()

            if((TARGET HAL::STM32::${FAMILY}${CORE_C}::${DRV}) AND (NOT (TARGET HAL::STM32::${FAMILY}${CORE_C}::${DRV}Ex)))
                message(TRACE "FindHAL: creating library HAL::STM32::${FAMILY}${CORE_C}::${DRV}Ex")
                add_library(HAL::STM32::${FAMILY}${CORE_C}::${DRV}Ex INTERFACE IMPORTED)
                target_link_libraries(HAL::STM32::${FAMILY}${CORE_C}::${DRV}Ex INTERFACE HAL::STM32::${FAMILY}${CORE_C}::${DRV})
                target_sources(HAL::STM32::${FAMILY}${CORE_C}::${DRV}Ex INTERFACE "${HAL_${FAMILY}${CORE_U}_${DRV}_EX_SOURCE}")
            endif()
        endif()
    endforeach()

    foreach(DRV_COMP ${HAL_FIND_COMPONENTS_DRIVERS_LL})
        string(TOLOWER ${DRV_COMP} DRV_L)
        string(REGEX REPLACE "^ll_" "" DRV_L ${DRV_L})
        string(TOUPPER ${DRV_L} DRV)

        if(NOT (DRV_L IN_LIST HAL_LL_DRIVERS_${FAMILY}))
            continue()
        endif()

        find_file(HAL_${FAMILY}${CORE_U}_${DRV}_LL_SOURCE
            NAMES stm32${FAMILY_L}xx_ll_${DRV_L}.c
            PATHS "${HAL_${FAMILY}_PATH}/Src"
            NO_DEFAULT_PATH
        )
        list(APPEND HAL_${FAMILY}${CORE_U}_SOURCES "${HAL_${FAMILY}_${DRV}_LL_SOURCE}")
        if(NOT HAL_${FAMILY}${CORE_U}_${DRV}_LL_SOURCE)
            message(WARNING "Cannot find LL_${DRV} driver for ${FAMILY}${CORE_U}")
            set(HAL_${DRV_COMP}_FOUND FALSE)
            continue()
        endif()

        set(HAL_${DRV_COMP}_FOUND TRUE)
        if(HAL_${FAMILY}${CORE_U}_${DRV}_LL_SOURCE AND (NOT (TARGET HAL::STM32::${FAMILY}${CORE_C}::LL_${DRV})))
            message(TRACE "FindHAL: creating library HAL::STM32::${FAMILY}${CORE_C}::LL_${DRV}")
            add_library(HAL::STM32::${FAMILY}${CORE_C}::LL_${DRV} INTERFACE IMPORTED)
            target_include_directories(HAL::STM32::${FAMILY}${CORE_C}::LL_${DRV} INTERFACE "${HAL_${FAMILY}${CORE_U}_INCLUDE}")
            target_sources(HAL::STM32::${FAMILY}${CORE_C}::LL_${DRV} INTERFACE "${HAL_${FAMILY}${CORE_U}_${DRV}_LL_SOURCE}")
        endif()
    endforeach()

    set(HAL_${COMP}_FOUND TRUE)
    list(APPEND HAL_INCLUDE_DIRS "${HAL_${FAMILY}${CORE_U}_INCLUDE}")
    list(APPEND HAL_SOURCES "${HAL_${FAMILY}${CORE_U}_SOURCES}")
endforeach()

list(REMOVE_DUPLICATES HAL_INCLUDE_DIRS)
list(REMOVE_DUPLICATES HAL_SOURCES)

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(HAL
    REQUIRED_VARS HAL_INCLUDE_DIRS HAL_SOURCES
    FOUND_VAR HAL_FOUND
    HANDLE_COMPONENTS
)


text:
package in.jugchennai.urbantravellers.game;

/**
 * Class that creates GameBoard
 * @author prasannakumar
 */
public final class GameBoardFactory {

    public static GameBoard createGameBoard(GameBoardConfig boardConfig) {
        return new GameBoard(boardConfig);
    }
}


text:
CREATE DATABASE IF NOT EXISTS testdb;
USE testdb;

-- Create a database user for the test database
GRANT ALL ON testdb.* TO test@localhost IDENTIFIED BY 'test';

-- Ensure UTF8 on the database connection
SET NAMES utf8;

-- Table User
DROP TABLE IF EXISTS User;
CREATE TABLE User (
    `id` INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
    `mail` VARCHAR(80) UNIQUE NOT NULL,
    `password` VARCHAR(255) NOT NULL,
    `userType` VARCHAR(50) DEFAULT "user",
    `created` DATETIME,
    `updated` DATETIME,
    `deleted` DATETIME,
    `active` DATETIME
) ENGINE INNODB CHARACTER SET utf8 COLLATE utf8_swedish_ci;

-- Comment table
DROP TABLE IF EXISTS c_comments;
CREATE TABLE `c_comments`(
    id INTEGER AUTO_INCREMENT PRIMARY KEY,
    userId INTEGER,
    userMail VARCHAR(100),
    msg TEXT,
    heading VARCHAR(100),
    postDate timestamp,
    deleted timestamp,
    updated timestamp,
    liked INTEGER DEFAULT 0,
    FOREIGN KEY (`userId`) REFERENCES `User`(`id`)
) ENGINE INNODB;

-- Dummy User
INSERT INTO `User`(`mail`, `password`, `userType`) VALUES
	("admin", "$2y$10$dW3URRs8Xer0SQUG9Ufrf.Mfi5uOw4Et3OhCd5ursnjnaoWC8NZmu", "admin")
;

-- Dummy Comment
INSERT INTO `c_comments`(userId, userMail, msg, heading) VALUES
	(1, "admin", "Ett testmeddelande", "Title")
;


text:
package com.github.davidmoten.guavamini;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.Iterator;

import org.junit.Test;

import com.github.davidmoten.junit.Asserts;

public class SetsTest {

    @Test
    public void testCreate() {
        assertTrue(Sets.newHashSet(1, 2, 3).contains(2));
    }

    @Test
    public void testCreateFromIterator() {
        assertTrue(Sets.newHashSet(Sets.newHashSet(1, 2, 3).iterator()).contains(2));
    }

    @Test
    public void testCreateFromIterable() {
        assertTrue(Sets.newHashSet(Sets.newHashSet(1, 2, 3)).contains(2));
    }

    @Test
    public void testCreateFromNonCollectionIterable() {
        assertTrue(Sets.newHashSet(new Iterable<Integer>() {

            @Override
            public Iterator<Integer> iterator() {
                return Sets.newHashSet(1, 2).iterator();
            }
        }).contains(2));
    }

    @Test
    public void testIsUtilityClass() {
        Asserts.assertIsUtilityClass(Sets.class);
    }

    @Test
    public void testCheckNonNegativeZero() {
        Sets.checkNonnegative(0, "boo");
    }

    @Test
    public void testCheckNonNegativePositive() {
        Sets.checkNonnegative(1, "boo");
    }

    @Test(expected = IllegalArgumentException.class)
    public void testCheckNonNegativeNegative() {
        Sets.checkNonnegative(-1, "boo");
    }

    @Test
    public void testCapacityForOne() {
        assertEquals(2, Sets.capacity(1));
    }

    @Test
    public void testCapacityForLarge() {
        assertEquals(Integer.MAX_VALUE, Sets.capacity(Sets.MAX_POWER_OF_TWO + 1));
    }
}


text:
#include <aws/alexaforbusiness/model/ContactData.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace AlexaForBusiness
{
namespace Model
{

ContactData::ContactData() :
    m_contactArnHasBeenSet(false),
    m_displayNameHasBeenSet(false),
    m_firstNameHasBeenSet(false),
    m_lastNameHasBeenSet(false),
    m_phoneNumberHasBeenSet(false),
    m_phoneNumbersHasBeenSet(false),
    m_sipAddressesHasBeenSet(false)
{
}

ContactData::ContactData(JsonView jsonValue) :
    m_contactArnHasBeenSet(false),
    m_displayNameHasBeenSet(false),
    m_firstNameHasBeenSet(false),
    m_lastNameHasBeenSet(false),
    m_phoneNumberHasBeenSet(false),
    m_phoneNumbersHasBeenSet(false),
    m_sipAddressesHasBeenSet(false)
{
  *this = jsonValue;
}

ContactData& ContactData::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ContactArn"))
  {
    m_contactArn = jsonValue.GetString("ContactArn");

    m_contactArnHasBeenSet = true;
  }

  if(jsonValue.ValueExists("DisplayName"))
  {
    m_displayName = jsonValue.GetString("DisplayName");

    m_displayNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("FirstName"))
  {
    m_firstName = jsonValue.GetString("FirstName");

    m_firstNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("LastName"))
  {
    m_lastName = jsonValue.GetString("LastName");

    m_lastNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("PhoneNumber"))
  {
    m_phoneNumber = jsonValue.GetString("PhoneNumber");

    m_phoneNumberHasBeenSet = true;
  }

  if(jsonValue.ValueExists("PhoneNumbers"))
  {
    Aws::Utils::Array<JsonView> phoneNumbersJsonList = jsonValue.GetArray("PhoneNumbers");
    for(unsigned phoneNumbersIndex = 0; phoneNumbersIndex < phoneNumbersJsonList.GetLength(); ++phoneNumbersIndex)
    {
      m_phoneNumbers.push_back(phoneNumbersJsonList[phoneNumbersIndex].AsObject());
    }
    m_phoneNumbersHasBeenSet = true;
  }

  if(jsonValue.ValueExists("SipAddresses"))
  {
    Aws::Utils::Array<JsonView> sipAddressesJsonList = jsonValue.GetArray("SipAddresses");
    for(unsigned sipAddressesIndex = 0; sipAddressesIndex < sipAddressesJsonList.GetLength(); ++sipAddressesIndex)
    {
      m_sipAddresses.push_back(sipAddressesJsonList[sipAddressesIndex].AsObject());
    }
    m_sipAddressesHasBeenSet = true;
  }

  return *this;
}

JsonValue ContactData::Jsonize() const
{
  JsonValue payload;

  if(m_contactArnHasBeenSet)
  {
   payload.WithString("ContactArn", m_contactArn);

  }

  if(m_displayNameHasBeenSet)
  {
   payload.WithString("DisplayName", m_displayName);

  }

  if(m_firstNameHasBeenSet)
  {
   payload.WithString("FirstName", m_firstName);

  }

  if(m_lastNameHasBeenSet)
  {
   payload.WithString("LastName", m_lastName);

  }

  if(m_phoneNumberHasBeenSet)
  {
   payload.WithString("PhoneNumber", m_phoneNumber);

  }

  if(m_phoneNumbersHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> phoneNumbersJsonList(m_phoneNumbers.size());
   for(unsigned phoneNumbersIndex = 0; phoneNumbersIndex < phoneNumbersJsonList.GetLength(); ++phoneNumbersIndex)
   {
     phoneNumbersJsonList[phoneNumbersIndex].AsObject(m_phoneNumbers[phoneNumbersIndex].Jsonize());
   }
   payload.WithArray("PhoneNumbers", std::move(phoneNumbersJsonList));

  }

  if(m_sipAddressesHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> sipAddressesJsonList(m_sipAddresses.size());
   for(unsigned sipAddressesIndex = 0; sipAddressesIndex < sipAddressesJsonList.GetLength(); ++sipAddressesIndex)
   {
     sipAddressesJsonList[sipAddressesIndex].AsObject(m_sipAddresses[sipAddressesIndex].Jsonize());
   }
   payload.WithArray("SipAddresses", std::move(sipAddressesJsonList));

  }

  return payload;
}

} // namespace Model
} // namespace AlexaForBusiness
} // namespace Aws


text:
package es.tid.vntm;

/**
 *
 * @author baam
 *
 */
public class OpTable {

	private String AppIP;
	private String PCCIP;
	private String PCCPort;
	private long PCCoperationID;
	private String workflow;

	public OpTable (String appString, String pccipString, String PCCport, long pccopidString, String workflow){
		this.AppIP=appString;
		this.PCCIP=pccipString;
		this.PCCPort=PCCport;
		this.PCCoperationID=pccopidString;
		this.workflow=workflow;
	}

	public String getAppIP() {
		return AppIP;
	}

	public void setAppIP(String appIP) {
		AppIP = appIP;
	}

	public String getPCCIP() {
		return PCCIP;
	}

	public void setPCCIP(String pCCIP) {
		PCCIP = pCCIP;
	}

	public long getPCCoperationID() {
		return PCCoperationID;
	}

	public void setPCCoperationID(long pCCoperationID) {
		PCCoperationID = pCCoperationID;
	}

	public String getPCCPort() {
		return PCCPort;
	}

	public void setPCCPort(String pCCPort) {
		PCCPort = pCCPort;
	}

	public String getWorkflow() {
		return workflow;
	}

	public void setWorkflow(String workflow) {
		this.workflow = workflow;
	}

}


text:
package com.googlecode.jmxtrans.model;

import lombok.EqualsAndHashCode;
import lombok.ToString;

import javax.annotation.Nonnull;

@ToString
@EqualsAndHashCode(of = "outputWriterFactory")
public class SingletonOutputWriterFactory<T extends OutputWriter> implements OutputWriterFactory<T> {

	@Nonnull private final T outputWriter;

	@Nonnull private final OutputWriterFactory<T> outputWriterFactory;

	public SingletonOutputWriterFactory(@Nonnull OutputWriterFactory<T> outputWriterFactory) {
		this.outputWriterFactory = outputWriterFactory;
		outputWriter = outputWriterFactory.create();
	}

	@Override
	public T create() {
		return outputWriter;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 ~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 ~
 ~ Licensed under the Apache License, Version 2.0 (the "License");
 ~ you may not use this file except in compliance with the License.
 ~ You may obtain a copy of the License at
 ~
 ~      http://www.apache.org/licenses/LICENSE-2.0
 ~
 ~ Unless required by applicable law or agreed to in writing, software
 ~ distributed under the License is distributed on an "AS IS" BASIS,
 ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ~ See the License for the specific language governing permissions and
 ~ limitations under the License.
-->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <parent>
        <groupId>org.wso2.carbon</groupId>
        <artifactId>dashboard-feature</artifactId>
        <version>4.3.0-SNAPSHOT</version>
	<relativePath>../pom.xml</relativePath>
    </parent>

    <version>4.3.0-SNAPSHOT</version>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>org.wso2.carbon.dashboard.mgt.oauth.ui.feature</artifactId>
    <packaging>pom</packaging>
    <name>WSO2 Carbon - Dashboard oauth UI Feature</name>
    <url>http://wso2.org</url>
    <description>This feature contains the bundles required for dashboard oauth front-end
    </description>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.dashboard.common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.dashboard.mgt.oauth.ui</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.dashboard.mgt.oauth.stub</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.wso2.maven</groupId>
                <artifactId>carbon-p2-plugin</artifactId>
                <version>${carbon.p2.plugin.version}</version>
                <executions>
                    <execution>
                        <id>p2-feature-generation</id>
                        <phase>package</phase>
                        <goals>
                            <goal>p2-feature-gen</goal>
                        </goals>
                        <configuration>
                            <id>org.wso2.carbon.dashboard.mgt.oauth.ui</id>
                            <propertiesFile>../../../etc/feature.properties</propertiesFile>
                            <adviceFile>
                                <properties>
                                    <propertyDef>org.wso2.carbon.p2.category.type:console</propertyDef>
                                    <propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
                                </properties>
                            </adviceFile>
                            <bundles>
                            	<bundleDef>org.wso2.carbon:org.wso2.carbon.dashboard.mgt.oauth.stub</bundleDef>
                                <bundleDef>org.wso2.carbon:org.wso2.carbon.dashboard.common</bundleDef>
                                <bundleDef>org.wso2.carbon:org.wso2.carbon.dashboard.mgt.oauth.ui</bundleDef>
                            </bundles>
                            <importFeatures>
                                <importFeatureDef>org.wso2.carbon.core.ui</importFeatureDef>
                            </importFeatures>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <properties>
    </properties>
</project>


text:
DROP TRIGGER IF EXISTS institution_specializations_ai $$
CREATE TRIGGER institution_specializations_ai AFTER INSERT on `institution_specializations`
FOR EACH ROW
BEGIN
    DECLARE DOCUMENT_TYPE_SPECIALIZATION tinyint(3);
    SET DOCUMENT_TYPE_SPECIALIZATION = 1;
    #
    #IF NEW.status = 1 THEN
    #    -- insert search terms for this added institution specialization
    #    INSERT INTO `search_terms` (`term_id`, `institution_id`, `institution_medical_center_id`, `term_document_id`, `document_id`, `type`, `specialization_id`, `sub_specialization_id`, `treatment_id`, `country_id`, `city_id`, `specialization_name`, `sub_specialization_name`, `treatment_name`, `country_name`, `city_name`, `status`)
    #    SELECT td.`term_id`, inst.`id` as institution_id, imc.`id` as institution_medical_center_id, td.`id` as term_document_id, td.`document_id`, td.`type`,  sp.`id` as specialization_id, NULL as sub_specialization_id, NULL as treatment_id, inst.`country_id`, inst.`city_id`, sp.`name` as specialization, NULL as sub_specialization, NULL as treatment, co.`name` as country, ci.`name` as city, (IF(imc.status = 2 AND inst.status = 9, 1, 0)) as status
    #    FROM `term_documents` td
    #    INNER JOIN `specializations` sp ON td.`document_id` = sp.id AND td.`type` = DOCUMENT_TYPE_SPECIALIZATION
    #    INNER JOIN `institution_specializations` ins_sp ON sp.`id` = ins_sp.`specialization_id`
    #    INNER JOIN `institution_medical_centers` imc ON imc.`id` = ins_sp.`institution_medical_center_id`
    #    INNER JOIN `institutions` inst ON inst.`id` = imc.`institution_id`
    #    INNER JOIN `countries` co ON co.`id` = inst.`country_id`
    #    LEFT JOIN `cities` ci ON ci.id = inst.`city_id`
    #    WHERE sp.`id` = NEW.`specialization_id`
    #    AND imc.id = NEW.`institution_medical_center_id`;
    #END IF;

END; $$
### end institution_specializations_ai trigger definition

##----------------------
# AFTER DELETE institution_specializations trigger.
#
# name: `institution_specializations_ad`
# table: `institution_specializations`
# event: AFTER DELETE
# author: acgvelarde
DROP TRIGGER IF EXISTS institution_specializations_ad $$
CREATE TRIGGER institution_specializations_ad AFTER DELETE ON `institution_specializations`
FOR EACH ROW
BEGIN
    DECLARE DOCUMENT_TYPE_SPECIALIZATION tinyint(3);
    SET DOCUMENT_TYPE_SPECIALIZATION = 1;

    -- delete search terms that are pointing to this institution specialization
    DELETE FROM `search_terms` WHERE document_id = OLD.`specialization_id`
    AND type = DOCUMENT_TYPE_SPECIALIZATION
    AND institution_medical_center_id = OLD.`institution_medical_center_id`;
END; $$
### end institution_specializations_ad


text:
package org.kiji.express

import com.twitter.scalding.Job
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path

import org.kiji.express.flow.ExpressTool
import org.kiji.mapreduce.HFileLoader
import org.kiji.schema.KijiTable

/**
 * Provides helper functions for writing integration tests against scalding.
 */
object IntegrationUtil {

  /**
   * Run a job with the given arguments.
   * @param jobClass class of job
   * @param args to supply to job
   */
  def runJob(jobClass: Class[_ <: Job], args: String*): Unit =
    ExpressTool.main(jobClass.getName +: args.toArray)

  /**
   * Bulk load HFiles from the given path into the table specified with the uri and conf.
   *
   * @param path to HFiles
   * @param table to bulk-load into
   */
  def bulkLoadHFiles(path: String, conf: Configuration, table: KijiTable): Unit =
    HFileLoader.create(conf).load(new Path(path), table)
}


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of bookingmodel
 *
 * @author Sameera
 */
class bookingmodel extends CI_Model {

    function temp_booking($temp_data) {

        if ($this->db->insert('temp_booking_data', $temp_data)) {
            $current_txn_id = $this->db->insert_id();
            if (!empty($current_txn_id)) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

    function cancel_booking($session_id) {
        $this->db->delete('temp_booking_data', array('unique_id' => $session_id));
        $this->db->delete('temp_package_data', array('unique_id' => $session_id));
        return TRUE;
    }

    function get_temp_data($session_id) {
        $query = $this->db->get_where('temp_booking_data', array('unique_id' => $session_id));
        return $query->result();
    }

    function get_next_booking_id() {
        $invoice_id = "";
        $this->db->select_max('id');
        $query = $this->db->get('booking');
        foreach ($query->result() as $booking_data) {
            $invoice_id = $booking_data->id + 1;
        }
        return $invoice_id;
    }

    function delete_temp_booking($id, $session_id) {
        $this->db->delete('temp_booking_data', array('unique_id' => $session_id, 'id' => $id));
    }
    function delete_temp_package($id, $session_id) {
        $this->db->delete('temp_package_data', array('unique_id' => $session_id, 'id' => $id));
    }

    function insert_package($pro_data) {
        if ($this->db->insert('temp_package_data', $pro_data)) {
            $current_txn_id = $this->db->insert_id();
            if (!empty($current_txn_id)) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

    function add_booking($booking_data) {
        if ($this->db->insert('booking', $booking_data)) {
            $current_txn_id = $this->db->insert_id();
            if (!empty($current_txn_id)) {
                return $current_txn_id;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }
    function add_package($pack_data) {
        if ($this->db->insert('package_linked', $pack_data)) {
            $current_txn_id = $this->db->insert_id();
            if (!empty($current_txn_id)) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }
    function add_sub_booking($booking_data) {
        if ($this->db->insert('booking_linked', $booking_data)) {
            $current_txn_id = $this->db->insert_id();
            if (!empty($current_txn_id)) {
                return $current_txn_id;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

}


text:
package org.ujorm.extensions;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import org.ujorm.CompositeKey;
import org.ujorm.Key;
import org.ujorm.Ujo;
import org.ujorm.WeakKey;
import org.ujorm.core.IllegalUjormException;
import org.ujorm.core.UjoManager;
import org.ujorm.core.WeakKeyFactory;
import static org.ujorm.extensions.PropertyModifier.*;

/**
 * The WeakKeyImpl is a default WeakKeyKey implementation without the generic parameter for the domain type.
 * The default implementation does not have the full support of several methods:
 *

 *
{@link Key#getDomainType()} - method return the result {@code Ujo.class} always

 *
{@link Key#add(org.ujorm.Key)} - method is not supported by the default implementation

 *
{@link Key#descending() } - result is not type of WeakKey

 *

 * , and some more methods are not fully type-safe.
 * On the other side the interface supports some operations with the {@link List} and {@link Map} interfaces.
 * To create new keys use an instance of the factory class {@link WeakKeyFactory}.
 * @author Pavel Ponec
 */
public class WeakKeyImpl<VALUE>
        extends Property<Ujo, VALUE>
        implements WeakKey<VALUE> {

    /** Constructor for an internal use only.
     * Use the factory {@link WeakKeyFactory} to create a new instance.
     * @see WeakKeyFactory
     */
    WeakKeyImpl(int index) {
        this(null, null, index);
    }

    /** Constructor for an internal use only.
     * Use the factory {@link WeakKeyFactory} to create a new instance.
     * @see WeakKeyFactory
     */
    public WeakKeyImpl(String name, VALUE defaultValue, int index) {
        super(index);
        init(NAME, name);
        init(DEFAULT_VALUE, defaultValue);
    }

    /**
     * It is an extended method for setting an appropriate type safe value to a common Map object.
     */
    @Override
    public void setValue(Map<String, ? super VALUE> map, VALUE value) {
        map.put(getName(), value);
    }

    /**
     * An alias for the method {@link #of(java.util.Map) } .
     * @see #getValue(java.util.Map)
     */
    @Override
    public final VALUE getValue(Map<String, ? super VALUE> map) {
        return of(map);
    }

   /**
     * It is an extended method for getting an appropriate type safe value from a common Map object.
     * @param ujo If a NULL parameter is used then an exception NullPointerException is throwed.
     * @return Returns a type safe value from the map object.
     */
    @Override
    @SuppressWarnings("unchecked")
    public VALUE of(Map<String, ? super VALUE> map) {
        final Object result = map.get(getName());
        return result != null ? (VALUE) result : getDefault();
    }

    /**
     * It is an extended method for getting an appropriate type safe value from a common Map object.
     * In case the size of the list is insufficient, the list is filled by the {@code null} values.
     */
    @Override
    public void setValue(List<? super VALUE> list, VALUE value) {
        final int i = getIndex();
        while (list.size() <= i) {
            list.add(null);
        }
        list.set(i, value);
    }

    /**
     * It is an extended method for getting an appropriate type safe value from a common Map object.
     * @param ujo If a NULL parameter is used then an exception NullPointerException is throwed.
     * @return Returns a type safe value from the map object.
     */
    @Override
    public final VALUE getValue(List<? super VALUE> list) {
        return getValue(list);
    }

    /**
     * A shortcut for the method {@link #getValue(java.util.List) } .
     * @see #getValue(java.util.List)
     */
    @Override
    public VALUE of(List<? super VALUE> list) {
        final int i = getIndex();
        final Object result = i < list.size() ? list.get(i) : null;
        return result != null ? (VALUE) result : getDefault();
    }

    /**
     * Returns an value from the Servlet Request.
     * @servletReqest An object type of: javax.servlet.ServletRequest, where the {@code null} result is replaced for a default value
     * @return Returns object converted to a required type.
     */
    @Override
    @SuppressWarnings("unchecked")
    public final VALUE getRequestValue(Object servletReqest) throws IllegalArgumentException {
        try {
            final Method m = servletReqest.getClass().getMethod("getParameter", String.class);
            final Object result = m.invoke(servletReqest, getName());
            return result!=null
                   ? (VALUE) UjoManager.getInstance().decodeValue(getType(), result.toString())
                   : getDefault() ;
        } catch (RuntimeException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new IllegalUjormException("Can't get parameter " + getName() + " from the servletRequest: " + servletReqest, e);
        }
    }

    /** The WeakKeyImpl does not support chaining of the Keys. */
    @Override
    @Deprecated
    public <T> CompositeKey<Ujo, T> add(Key<? super VALUE, T> key) {
        throw new UnsupportedOperationException("An unsupported operation in the " + getClass());
    }
}


text:
namespace AdventureWorks.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("Production.WorkOrderRouting")]
    public partial class WorkOrderRouting
    {
        [Key]
        [Column(Order = 0)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int WorkOrderID { get; set; }

        [Key]
        [Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int ProductID { get; set; }

        [Key]
        [Column(Order = 2)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public short OperationSequence { get; set; }

        public short LocationID { get; set; }

        public DateTime ScheduledStartDate { get; set; }

        public DateTime ScheduledEndDate { get; set; }

        public DateTime? ActualStartDate { get; set; }

        public DateTime? ActualEndDate { get; set; }

        public decimal? ActualResourceHrs { get; set; }

        [Column(TypeName = "money")]
        public decimal PlannedCost { get; set; }

        [Column(TypeName = "money")]
        public decimal? ActualCost { get; set; }

        public DateTime ModifiedDate { get; set; }

        public virtual Location Location { get; set; }

        public virtual WorkOrder WorkOrder { get; set; }
    }
}


text:
TARGET = vmmalloc_out_of_memory
OBJS = vmmalloc_out_of_memory.o

include ../Makefile.inc


text:
<?php
namespace Scalr\Service\CloudStack\Services\Template\V26032014;

use Scalr\Service\CloudStack\Client\ClientInterface;
use Scalr\Service\CloudStack\DataType\ExtractTemplateResponseData;
use Scalr\Service\CloudStack\DataType\PaginationType;
use Scalr\Service\CloudStack\DataType\ResponseDeleteData;
use Scalr\Service\CloudStack\DataType\TemplatePermissionsList;
use Scalr\Service\CloudStack\DataType\TemplateResponseData;
use Scalr\Service\CloudStack\DataType\TemplateResponseList;
use Scalr\Service\CloudStack\Services\AbstractApi;
use Scalr\Service\CloudStack\Services\TagsTrait;
use Scalr\Service\CloudStack\Services\Template\DataType\CreateTemplateData;
use Scalr\Service\CloudStack\Services\Template\DataType\ExtractTemplateData;
use Scalr\Service\CloudStack\Services\Template\DataType\ListTemplatesData;
use Scalr\Service\CloudStack\Services\Template\DataType\RegisterTemplateData;
use Scalr\Service\CloudStack\Services\Template\DataType\UpdateTemplateData;
use Scalr\Service\CloudStack\Services\Template\DataType\UpdateTemplatePermissionsData;
use Scalr\Service\CloudStack\Services\TemplateService;
use Scalr\Service\CloudStack\Services\TemplateTrait;
use Scalr\Service\CloudStack\Services\UpdateTrait;
use Scalr\Service\CloudStack\Services\VirtualTrait;

/**
 * CloudStack API v4.3.0 (March 26, 2014)
 *
 * @author   Vlad Dobrovolskiy  <v.dobrovolskiy@scalr.com>
 * @since    4.5.2
 */
class TemplateApi extends AbstractApi
{
    use VirtualTrait, TagsTrait, UpdateTrait, TemplateTrait;

    /**
     * @var TemplateService
     */
    protected $service;

    /**
     * Constructor
     *
     * @param   TemplateService $template
     */
    public function __construct(TemplateService $template)
    {
        $this->service = $template;
    }

    /**
     * Gets HTTP Client
     *
     * @return  ClientInterface Returns HTTP Client
     */
    public function getClient()
    {
        return $this->service->getCloudStack()->getClient();
    }

    /**
     * Creates a template of a virtual machine.
     * The virtual machine must be in a STOPPED state.
     * A template created from this command is automatically designated as a private template visible to the account that created it.
     *
     * @param CreateTemplateData $requestData Create Template request data
     * @return TemplateResponseData
     */
    public function createTemplate(CreateTemplateData $requestData)
    {
        $result = null;

        $response = $this->getClient()->call('createTemplate', $requestData->toArray());

        if ($response->hasError() === false) {
            $resultObject = $response->getResult();
            if (!empty($resultObject)) {
                $result = $this->_loadTemplateResponseData($resultObject);
            }
        }

        return $result;
    }

    /**
     * Registers an existing template into the Cloud.com cloud.
     *
     * @param RegisterTemplateData $requestData Register template request data
     * @return TemplateResponseData
     */
    public function registerTemplate(RegisterTemplateData $requestData)
    {
        $result = null;

        $response = $this->getClient()->call('registerTemplate', $requestData->toArray());

        if ($response->hasError() === false) {
            $resultObject = $response->getResult();
            if (!empty($resultObject)) {
                $result = $this->_loadTemplateResponseData($resultObject);
            }
        }

        return $result;
    }

    /**
     * Updates attributes of a template.
     *
     * @param UpdateTemplateData $requestData Update template request data
     * @return TemplateResponseData
     */
    public function updateTemplate(UpdateTemplateData $requestData)
    {
        $result = null;

        $response = $this->getClient()->call('updateTemplate', $requestData->toArray());

        if ($response->hasError() === false) {
            $resultObject = $response->getResult();
            if (!empty($resultObject)) {
                $result = $this->_loadTemplateResponseData($resultObject);
            }
        }

        return $result;
    }

    /**
     * Copies a template from one zone to another.
     *
     * @param string $id             Template ID.
     * @param string $destzoneId     ID of the zone the template is being copied to.
     * @param string $sourceZoneId   ID of the zone the template is currently hosted on.
     *                               If not specified and template is cross-zone, then we will sync this template to region wide image store
     * @return TemplateResponseData
     */
    public function copyTemplate($id, $destzoneId, $sourceZoneId = null)
    {
        $result = null;

        $response = $this->getClient()->call(
            'copyTemplate', array(
                'id' => $this->escape($id),
                'destzoneid' => $this->escape($destzoneId),
                'sourcezoneid' => $this->escape($sourceZoneId),
             )
        );
        if ($response->hasError() === false) {
            $resultObject = $response->getResult();
            if (!empty($resultObject)) {
                $result = $this->_loadTemplateResponseData($resultObject);
            }
        }

        return $result;
    }

    /**
     * Deletes a template from the system.
     * All virtual machines using the deleted template will not be affected.
     *
     * @param string $id the ID of the template
     * @param string $zoneId the ID of zone of the template
     * @return ResponseDeleteData
     */
    public function deleteTemplate($id, $zoneId = null)
    {
        $result = null;

        $response = $this->getClient()->call(
            'deleteTemplate', array(
                'id' => $this->escape($id),
                'zoneid' => $this->escape($zoneId)
             )
        );

        if ($response->hasError() === false) {
            $resultObject = $response->getResult();
            if (!empty($resultObject)) {
                $result = $this->_loadUpdateData($resultObject);
            }
        }

        return $result;
    }

    /**
     * List all public, private, and privileged templates.
     *
     * @param ListTemplatesData $requestData List template request data
     * @param PaginationType $pagination Pagination
     * @return TemplateResponseList|null
     */
    public function listTemplates(ListTemplatesData $requestData, PaginationType $pagination = null)
    {
        $result = null;
        $args = $requestData->toArray();
        if ($pagination !== null) {
            $args = array_merge($args, $pagination->toArray());
        }

        $response = $this->getClient()->call('listTemplates', $args);

        if ($response->hasError() === false) {
            $resultObject = $response->getResult();

            if (!empty($resultObject) && property_exists($resultObject, 'count') && $resultObject->count > 0) {
                $result = $this->_loadTemplateResponseList($resultObject->template);
            }
        }

        return $result;
    }

    /**
     * Updates a template visibility permissions.
     * A public template is visible to all accounts within the same domain.
     * A private template is visible only to the owner of the template.
     * A priviledged template is a private template with account permissions added.
     * Only accounts specified under the template permissions are visible to them.
     *
     * @param UpdateTemplatePermissionsData $requestData Update template permissions request data
     * @return ResponseDeleteData
     */
    public function updateTemplatePermissions(UpdateTemplatePermissionsData $requestData)
    {
        $result = null;

        $response = $this->getClient()->call('updateTemplatePermissions', $requestData->toArray());

        if ($response->hasError() === false) {
            $resultObject = $response->getResult();
            if (!empty($resultObject)) {
                $result = $this->_loadUpdateData($resultObject);
            }
        }

        return $result;
    }

    /**
     * List template visibility and all accounts that have permissions to view this template.
     *
     * @param string $id         The template ID
     * @param string $account    List template visibility and permissions for the specified account.
     *                           Must be used with the domainId parameter.
     * @param string $domainId   List template visibility and permissions by domain.
     *                           If used with the account parameter, specifies in which domain the specified account exists.
     * @param PaginationType $pagination Pagination
     * @return TemplatePermissionsList|null
     */
    public function listTemplatePermissions($id, $account = null, $domainId = null, PaginationType $pagination = null)
    {
        $result = null;
        $args = array(
           'id'        => $this->escape($id),
           'account'   => $this->escape($account),
           'domainId'  => $this->escape($domainId)
        );
        if ($pagination !== null) {
            $args = array_merge($args, $pagination->toArray());
        }

        $response = $this->getClient()->call(
            'listTemplatePermissions', $args
        );

        if ($response->hasError() === false) {
            $resultObject = $response->getResult();

            if (!empty($resultObject) && property_exists($resultObject, 'count') && $resultObject->count > 0) {
                $result = $this->_loadTemplatePermissionsList($resultObject->templatepermission);
            }
        }

        return $result;
    }

    /**
     * Extracts a template
     *
     * @param ExtractTemplateData $requestData Extract template request data
     * @return ExtractTemplateResponseData
     */
    public function extractTemplate(ExtractTemplateData $requestData)
    {
        $result = null;

        $response = $this->getClient()->call('extractTemplate', $requestData->toArray());

        if ($response->hasError() === false) {
            $resultObject = $response->getResult();
            if (!empty($resultObject)) {
                $result = $this->_loadExtractTemplateData($resultObject);
            }
        }

        return $result;
    }

}


text:
package com.netflix.astyanax.thrift.model;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.netflix.astyanax.Serializer;
import com.netflix.astyanax.model.AbstractColumnList;
import com.netflix.astyanax.model.Column;
import org.apache.cassandra.thrift.CounterColumn;

public class ThriftCounterColumnListImpl<C> extends AbstractColumnList<C> {
    private final List<CounterColumn> columns;
    private Map<C, CounterColumn> lookup;
    private final Serializer<C> colSer;

    public ThriftCounterColumnListImpl(List<CounterColumn> columns, Serializer<C> colSer) {
        this.columns = columns;
        this.colSer = colSer;
    }

    @Override
    public Iterator<Column<C>> iterator() {
        class IteratorImpl implements Iterator<Column<C>> {
            Iterator<CounterColumn> base;

            public IteratorImpl(Iterator<CounterColumn> base) {
                this.base = base;
            }

            @Override
            public boolean hasNext() {
                return base.hasNext();
            }

            @Override
            public Column<C> next() {
                CounterColumn c = base.next();
                return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c);
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Iterator is immutable");
            }
        }
        return new IteratorImpl(columns.iterator());
    }

    @Override
    public Column<C> getColumnByName(C columnName) {
        constructMap();

        CounterColumn c = lookup.get(columnName);
        if (c == null) {
            return null;
        }
        return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c);
    }

    @Override
    public Column<C> getColumnByIndex(int idx) {
        CounterColumn c = columns.get(idx);
        return new ThriftCounterColumnImpl<C>(colSer.fromBytes(c.getName()), c);
    }

    @Override
    public <C2> Column<C2> getSuperColumn(C columnName, Serializer<C2> colSer) {
        throw new UnsupportedOperationException("Call getCounter");
    }

    @Override
    public <C2> Column<C2> getSuperColumn(int idx, Serializer<C2> colSer) {
        throw new UnsupportedOperationException("Call getCounter");
    }

    @Override
    public boolean isEmpty() {
        return columns.isEmpty();
    }

    @Override
    public int size() {
        return columns.size();
    }

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

    @Override
    public Collection<C> getColumnNames() {
        constructMap();
        return lookup.keySet();
    }

    private void constructMap() {
        if (lookup == null) {
            lookup = Maps.newHashMap();
            for (CounterColumn column : columns) {
                lookup.put(colSer.fromBytes(column.getName()), column);
            }
        }
    }
}


text:
In this lab, you will enable managed services used in MLOps evironment and provision a [standalone deployment of Kubeflow Pipelines](https://www.kubeflow.org/docs/pipelines/installation/standalone-deployment/).

Provisioning of the environment has been automated with the `./install.sh` script.

The script goes through the following steps:
1. Enables required cloud services
1. Provisions an MVP infrastructure to host a standalone deployment of Kubeflow Pipelines. This step has been automated with [Terraform](https://www.terraform.io/):
    1. Creates a VPC
    1. Creates and configures a GKE cluster
    1. Creates an instance of Cloud SQL
    1. Creates a GCS bucket
    1. Creates a service account for GKE worker nodes and a service account to be used by KFP pipelines
1. Deploys Kubeflow Pipelines and configures the KFP services to use Cloud SQL for ML metadata management and GCS for artifact storage. This step has been automated with [Kustomize](https://kustomize.io/).

## Running the installation script

You will run the provisioning script using [Cloud Shell](https://cloud.google.com/shell/).

**Terraform** is pre-installed in **Cloud Shell**. The version of `kubectl` installed by default in **Cloud Shell** does not support **Kustomize**. *When `kubectl` in **Cloud Shell** is upgraded to the version that supports **Kustomize** the step below will not be necessary*.

To install **Kustomize** in **Cloud Shell**:
```
cd /usr/local/bin
sudo wget https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2Fv3.3.0/kustomize_v3.3.0_linux_amd64.tar.gz
sudo tar xvf kustomize_v3.3.0_linux_amd64.tar.gz
sudo rm kustomize_v3.3.0_linux_amd64.tar.gz
cd
```
The above command installs **Kustomize** to the `/usr/local/bin` folder, which by default is on the `PATH`. **Kustomize** is a single executable. Note that this folder will be reset - and Kustomize removed - after you disconnect from **Cloud Shell**.

To start the provisioning script:

1. Open **Cloud Shell**
2. Clone this repo under your `home` folder.
```
cd
git clone https://github.com/GoogleCloudPlatform/mlops-on-gcp.git
cd mlops-on-gcp/environments_setup/mlops-env-on-gcp/provisioning-kfp
```

3. Start installation
```
./install.sh [PROJECT_ID] [SQL_PASSWORD] [PREFIX] [REGION] [ZONE] [NAMESPACE]
```

Where:

|Parameter|Optional|Description|
|-------------|---------|-------------------------------|
|[PROJECT_ID]| Required|The project id of your project.|
|[SQL_PASSWORD]| Required|The password for the Cloud SQL root user|
|[PREFIX]|Optional|A name prefix tha will be added to the names of the provisioned resources. If not provided [PROJECT_ID] will be used as the prefix|
|[REGION]|Optional|The region for the Cloud SQL instance.  If not provided the `us-central1` region will be used|
|[ZONE]|Optional|The zone for the GKE cluster. If not provided the `us-central1-a` will be used.|
|[NAMESPACE]|Optional|The namespace to deploy KFP to. If not provided the `kubeflow` namespace will be used|

We recommend using the defaults for the region, the zone and the namespace.

4. Review the logs generated by the script for any errors.

## Accessing KFP UI

After the installation completes, you can access the KFP UI from the following URL. You may need to wait a few minutes before the URL is operational.

```
gcloud container clusters get-credentials $PREFIX-cluster --zone $ZONE
echo "https://"$(kubectl describe configmap inverse-proxy-config -n kubeflow | \
grep "googleusercontent.com")
```


text:
.class Landroid/support/v4/view/WindowInsetsCompatApi20;
.super Ljava/lang/Object;
.source "WindowInsetsCompatApi20.java"

# annotations
.annotation build Landroid/support/annotation/RequiresApi;
    value = 0x14
.end annotation

# direct methods
.method constructor <init>()V
    .registers 1

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

    return-void
.end method

.method public static consumeSystemWindowInsets(Ljava/lang/Object;)Ljava/lang/Object;
    .registers 2
    .param p0, "insets"    # Ljava/lang/Object;

    .prologue
    .line 25
    check-cast p0, Landroid/view/WindowInsets;

    .end local p0    # "insets":Ljava/lang/Object;
    invoke-virtual {p0}, Landroid/view/WindowInsets;->consumeSystemWindowInsets()Landroid/view/WindowInsets;

    move-result-object v0

    return-object v0
.end method

.method public static getSourceWindowInsets(Ljava/lang/Object;)Ljava/lang/Object;
    .registers 2
    .param p0, "src"    # Ljava/lang/Object;

    .prologue
    .line 62
    new-instance v0, Landroid/view/WindowInsets;

    check-cast p0, Landroid/view/WindowInsets;

    .end local p0    # "src":Ljava/lang/Object;
    invoke-direct {v0, p0}, Landroid/view/WindowInsets;-><init>(Landroid/view/WindowInsets;)V

    return-object v0
.end method

.method public static getSystemWindowInsetBottom(Ljava/lang/Object;)I
    .registers 2
    .param p0, "insets"    # Ljava/lang/Object;

    .prologue
    .line 29
    check-cast p0, Landroid/view/WindowInsets;

    .end local p0    # "insets":Ljava/lang/Object;
    invoke-virtual {p0}, Landroid/view/WindowInsets;->getSystemWindowInsetBottom()I

    move-result v0

    return v0
.end method

.method public static getSystemWindowInsetLeft(Ljava/lang/Object;)I
    .registers 2
    .param p0, "insets"    # Ljava/lang/Object;

    .prologue
    .line 33
    check-cast p0, Landroid/view/WindowInsets;

    .end local p0    # "insets":Ljava/lang/Object;
    invoke-virtual {p0}, Landroid/view/WindowInsets;->getSystemWindowInsetLeft()I

    move-result v0

    return v0
.end method

.method public static getSystemWindowInsetRight(Ljava/lang/Object;)I
    .registers 2
    .param p0, "insets"    # Ljava/lang/Object;

    .prologue
    .line 37
    check-cast p0, Landroid/view/WindowInsets;

    .end local p0    # "insets":Ljava/lang/Object;
    invoke-virtual {p0}, Landroid/view/WindowInsets;->getSystemWindowInsetRight()I

    move-result v0

    return v0
.end method

.method public static getSystemWindowInsetTop(Ljava/lang/Object;)I
    .registers 2
    .param p0, "insets"    # Ljava/lang/Object;

    .prologue
    .line 41
    check-cast p0, Landroid/view/WindowInsets;

    .end local p0    # "insets":Ljava/lang/Object;
    invoke-virtual {p0}, Landroid/view/WindowInsets;->getSystemWindowInsetTop()I

    move-result v0

    return v0
.end method

.method public static hasInsets(Ljava/lang/Object;)Z
    .registers 2
    .param p0, "insets"    # Ljava/lang/Object;

    .prologue
    .line 45
    check-cast p0, Landroid/view/WindowInsets;

    .end local p0    # "insets":Ljava/lang/Object;
    invoke-virtual {p0}, Landroid/view/WindowInsets;->hasInsets()Z

    move-result v0

    return v0
.end method

.method public static hasSystemWindowInsets(Ljava/lang/Object;)Z
    .registers 2
    .param p0, "insets"    # Ljava/lang/Object;

    .prologue
    .line 49
    check-cast p0, Landroid/view/WindowInsets;

    .end local p0    # "insets":Ljava/lang/Object;
    invoke-virtual {p0}, Landroid/view/WindowInsets;->hasSystemWindowInsets()Z

    move-result v0

    return v0
.end method

.method public static isRound(Ljava/lang/Object;)Z
    .registers 2
    .param p0, "insets"    # Ljava/lang/Object;

    .prologue
    .line 53
    check-cast p0, Landroid/view/WindowInsets;

    .end local p0    # "insets":Ljava/lang/Object;
    invoke-virtual {p0}, Landroid/view/WindowInsets;->isRound()Z

    move-result v0

    return v0
.end method

.method public static replaceSystemWindowInsets(Ljava/lang/Object;IIII)Ljava/lang/Object;
    .registers 6
    .param p0, "insets"    # Ljava/lang/Object;
    .param p1, "left"    # I
    .param p2, "top"    # I
    .param p3, "right"    # I
    .param p4, "bottom"    # I

    .prologue
    .line 58
    check-cast p0, Landroid/view/WindowInsets;

    .end local p0    # "insets":Ljava/lang/Object;
    invoke-virtual {p0, p1, p2, p3, p4}, Landroid/view/WindowInsets;->replaceSystemWindowInsets(IIII)Landroid/view/WindowInsets;

    move-result-object v0

    return-object v0
.end method


text:
package router

import (
	"encoding/json"
	"errors"
	"fmt"
	"git"
	"git/processor"
	"html/template"
	"jwts"
	"log"
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"time"
	"user"

	"github.com/dgrijalva/jwt-go"
	"github.com/gorilla/mux"
)

// Page contains all data needed to Render the HTML files
type Page struct {
	Title,
	SinceDateString,
	GitClientID string
	RepoData []Repodata
	Settings git.Config
	Authors,
	Repos []string
}

// Repodata contains data for rendering the repository list
type Repodata struct {
	Name       string
	Branches   []string
	NrBranches int
}

// Buttondata contains data for rendering the commit button list
type Buttondata struct {
	Name,
	ID,
	DateString,
	Repository string
	NanoTime int64
}

const (
	// TITLE is the title of the index page
	TITLE = "CHF"
)

var jwtProvider jwts.Provider

// InitJWT intilialises the json web tocken Provider
func InitJWT() {
	jwtProvider = jwts.New([]byte(GlobalServerConfig.JWTSecret), jwts.Config{Method: jwt.SigningMethodHS256, TTL: 3600 * 24 * 3})
}

var page Page

var templates = template.Must(template.ParseFiles("commits.html", "headAndNavbar.html", "repositories.html", "settings.html", "authors.html", "scripts.html", "login.html"))

func updatePageData(userCache *git.UserCache) {
	page.Title = TITLE
	page.GitClientID = GlobalServerConfig.GitClientID
	page.Authors = processor.GetCachedAuthors(userCache)
	page.Repos = processor.GetCachedRepos(userCache)
	page.Settings = userCache.Config
	page.SinceDateString = processor.GetCacheTimeString(userCache) //page.Settings.SinceTime.Format(time.RFC3339)[:10]
}

func gitHubSignIn(code string) (jwtBytes *jwt.Token, ID string, Error error) {

	authToken, err := git.GetAuthKeyFromGit(code, GlobalServerConfig.GitClientID, GlobalServerConfig.GitClientSecret)
	if err != nil {
		log.Println(err)
		return nil, "", err
	}

	currentUser := git.GetUserFromToken(authToken)
	stringID := strconv.Itoa(currentUser.ID)
	if !user.Exists(stringID) {
		user.AddUser(stringID, authToken)
		processor.SaveCompleteConfig(user.GetUserCache(stringID), stringID)
	}

	token := jwtProvider.New()
	claims := token.Claims.(jwt.MapClaims)
	claims["userID"] = stringID
	return token, stringID, nil
}

// Index handler
func Index(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)

	var userID string
	var err error
	var token *jwt.Token
	// if redirected from github login
	code, redirectedFromGithub := vars["githubLoginCode"]
	if redirectedFromGithub {
		var newJwtBytes []byte
		token, userID, err = gitHubSignIn(code)
		if err != nil {
			// TODO
			log.Println(err)
		}
		newJwtBytes, err = jwtProvider.Sign(token)
		if err != nil {
			log.Println(err)
		}
		expiration := time.Now().Add(24 * 7 * time.Hour)
		cookie := http.Cookie{Name: "jwt", Value: string(newJwtBytes), Expires: expiration}
		http.SetCookie(w, &cookie)

	} else {
		userID, err = checkJWTandGetUserID(r)
		if err != nil {
			log.Println(err)
		}
	}
	if userID == "" {
		log.Println("Not logged in")
		updatePageData(&git.UserCache{})
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}

	if !user.ConfigLoaded(userID) {
		hasConfig := false
		for _, configFileName := range processor.GetSavedConfigs() {
			if configFileName == userID {
				hasConfig = true
				break
			}
		}
		if hasConfig {
			processor.LoadCompleteConfig(userID)
			user.SetConfigLoaded(userID, true)
		}

		// when config is loaded check JWT again against timestamp
		// but skip if new sign in (redirected from github) -> no jwt in request
		if !redirectedFromGithub {
			_, err = checkJWTandGetUserID(r)
			if err != nil {
				log.Println(err)
				http.Redirect(w, r, "/login", http.StatusFound)
				return
			}
		}
	}

	// if cookie valid but AccessToken not found
	if _, ok := user.GetAccessToken(userID); !ok {
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}

	w.Header().Set("Content-type", "text/html")
	templates = template.Must(template.ParseFiles("commits.html", "headAndNavbar.html", "repositories.html", "settings.html", "authors.html", "scripts.html", "login.html"))
	userCache := user.GetUserCache(userID)
	updatePageData(&userCache)

	templates.ExecuteTemplate(w, "commits.html", page)
}

// RefreshJWT refreshes the JWT cookie
func RefreshJWT(w http.ResponseWriter, r *http.Request) {
	userID, err := checkJWTandGetUserID(r)
	if err != nil {
		log.Println(err)
		http.Error(w, err.Error(), http.StatusUnauthorized)
		return
	}
	freshToken := jwtProvider.New()
	claims := freshToken.Claims.(jwt.MapClaims)
	claims["userID"] = userID
	expiration := time.Now().Add(24 * 7 * time.Hour)
	freshTokenBytes, err := jwtProvider.Sign(freshToken)
	if err != nil {
		log.Fatalln(err)
	}
	updateIssuedAt(userID, claims["iatStr"].(string))
	cookie := http.Cookie{Name: "jwt", Value: string(freshTokenBytes), Expires: expiration}
	http.SetCookie(w, &cookie)
}

// CommitsShowJSON handler
func CommitsShowJSON(w http.ResponseWriter, r *http.Request) {
	userID, err := checkJWTandGetUserID(r)
	if err != nil {
		log.Println(err)
		return
	}
	if !user.Exists(userID) {
		return
	}
	authToken, _ := user.GetAccessToken(userID)
	cacheTimeBefore := user.GetUserCache(userID).CacheTime
	metaData := git.AuthTokenToLastResponse[authToken]

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.Header().Set("Page-has-updates", "false")
	w.Header().Set("Last-GitHub-Response-RateLimit", strconv.Itoa(metaData.RateLimit))
	w.Header().Set("Last-GitHub-Response-RateLimitRemaining", strconv.Itoa(metaData.RateLimitRemaining))
	w.Header().Set("Last-GitHub-Response-RateLimitReset", strconv.Itoa(metaData.RateLimitReset))
	w.Header().Set("Last-GitHub-Response-Status", metaData.Status)

	vars := map[string]string{"commit": r.FormValue("commit"), "author": r.FormValue("author"), "repo": r.FormValue("repo"), "date": r.FormValue("date")}
	query := getQueryFromVars(vars)

	queryResult := git.Commits{}
	commitChanel := make(chan git.Commit)
	go processor.SendCommits(userID, query, commitChanel)
	for commit := range commitChanel {
		queryResult = append(queryResult, commit)
	}
	sort.Sort(queryResult)

	cacheTimeAfterQuery := user.GetUserCache(userID).CacheTime
	if cacheTimeAfterQuery.Before(cacheTimeBefore) {
		w.Header().Set("Page-has-updates", "true")
	}

	//For paging. On empty or error: no paging
	page, _ := strconv.Atoi(r.FormValue("page"))
	perPage, _ := strconv.Atoi(r.FormValue("perPage"))
	var maxIndex, minIndex int

	if page != 0 {
		// if not specified 30 commits per page
		if perPage == 0 {
			perPage = 30
		}
		maxIndex = page*perPage - 1
		minIndex = page*perPage - perPage
	}

	currentIndex := -1
	commitData := []Buttondata{}
	for _, com := range queryResult {
		currentIndex++
		formatedDate := com.Time.Format(time.RFC822)[:10]
		if page != 0 {
			if currentIndex < minIndex {
				continue
			}
			if currentIndex > maxIndex {
				break
			}
		}
		commitData = append(commitData, Buttondata{com.Comment, com.Sha, formatedDate, com.Repo + "/" + com.Branch, com.Time.UnixNano()})
	}
	if err := json.NewEncoder(w).Encode(commitData); err != nil {
		panic(err)
	}
}

// AuthorsShowJSON handler
func AuthorsShowJSON(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	userID, err := checkJWTandGetUserID(r)
	if err != nil {
		log.Println(err)
		return
	}
	userCache := user.GetUserCache(userID)
	if err := json.NewEncoder(w).Encode(processor.GetCachedAuthors(&userCache)); err != nil {
		panic(err)
	}
	w.WriteHeader(http.StatusOK)
}

// AuthorsShow handler
func AuthorsShow(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-type", "text/html")
	userID, err := checkJWTandGetUserID(r)
	if err != nil {
		log.Println(err)
	}
	if !user.Exists(userID) {
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}
	userCache := user.GetUserCache(userID)
	authorButtons := []Buttondata{}
	for _, author := range processor.GetCachedAuthors(&userCache) {
		authorButtons = append(authorButtons, Buttondata{author, author, "", "", 0})
	}
	updatePageData(&userCache)
	templates.ExecuteTemplate(w, "authors.html", page)
}

// LoginHTML handler
func LoginHTML(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-type", "text/html")
	updatePageData(&git.UserCache{})
	templates = template.Must(template.ParseFiles("headAndNavbar.html", "scripts.html", "login.html"))
	templates.ExecuteTemplate(w, "login.html", page)
}

// SettingsShow handler
func SettingsShow(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-type", "text/html")
	userID, err := checkJWTandGetUserID(r)
	if err != nil {
		log.Println(err)
	}
	if !user.Exists(userID) {
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}
	templates = template.Must(template.ParseFiles("commits.html", "headAndNavbar.html", "repositories.html", "settings.html", "authors.html", "scripts.html"))
	err = r.ParseForm()
	if err != nil {
		http.Error(w, fmt.Sprintf("error parsing url %v", err), 500)
	}
	userCache := user.GetUserCache(userID)
	updatePageData(&userCache)
	templates.ExecuteTemplate(w, "settings.html", page)
}

// SettingsPost handler
func SettingsPost(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-type", "text/html")
	templates = template.Must(template.ParseFiles("commits.html", "headAndNavbar.html", "repositories.html", "settings.html", "authors.html", "scripts.html"))
	err := r.ParseForm()
	if err != nil {
		http.Error(w, fmt.Sprintf("error parsing url %v", err), 500)
	}
	config := getConfigFromForm(r.Form)
	userID, err := checkJWTandGetUserID(r)
	if err != nil {
		log.Println(err)
		return
	}
	processor.SetConfig(userID, config)
	userCache := user.GetUserCache(userID)
	processor.SaveCompleteConfig(userCache, userID)
	updatePageData(&userCache)
	templates.ExecuteTemplate(w, "settings.html", page)
}

// ReposShowHTML handler
func ReposShowHTML(w http.ResponseWriter, r *http.Request) {
	userID, err := checkJWTandGetUserID(r)
	if err != nil {
		log.Println(err)
	}
	if !user.Exists(userID) {
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}
	userCache := user.GetUserCache(userID)
	w.Header().Set("Content-type", "text/html")
	templates = template.Must(template.ParseFiles("commits.html", "headAndNavbar.html", "repositories.html", "settings.html", "authors.html", "scripts.html", "login.html"))
	err = r.ParseForm()
	if err != nil {
		http.Error(w, fmt.Sprintf("error parsing url %v", err), 500)
	}
	repos, err := processor.GetCachedRepoObjects(userID)
	if err != nil {
		panic(err)
	}
	repodata := []Repodata{}
	for _, repo := range repos {
		branches := []string{repo.SelectedBranch}
		for branch := range repo.Branches {
			if branch != repo.SelectedBranch {
				branches = append(branches, branch)
			}
		}
		repodata = append(repodata, Repodata{repo.Name, branches, len(branches)})

	}
	updatePageData(&userCache)
	page.RepoData = repodata
	templates.ExecuteTemplate(w, "repositories.html", page)
}

// RepoBranchChange handler
func RepoBranchChange(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		http.Error(w, fmt.Sprintf("error parsing url %v", err), 500)
	}
	repo := r.FormValue("repo")
	branch := r.FormValue("branch")

	userID, err := checkJWTandGetUserID(r)
	if err != nil {
		log.Println(err)
		return
	}

	processor.SetRepoBranch(userID, repo, branch)
}

// ReposShow handler
func ReposShow(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	templates = template.Must(template.ParseFiles("commits.html", "headAndNavbar.html", "repositories.html", "settings.html", "authors.html", "scripts.html"))
	userID, err := checkJWTandGetUserID(r)
	if err != nil {
		log.Println(err)
		return
	}
	userCache := user.GetUserCache(userID)
	w.WriteHeader(http.StatusOK)
	if err := json.NewEncoder(w).Encode(processor.GetCachedRepos(&userCache)); err != nil {
		panic(err)
	}
}

// ShowSingleCommit handler
func ShowSingleCommit(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
	vars := mux.Vars(r)
	sha, ok := vars["sha"]
	if !ok {
		// TODO
	}
	userID, err := checkJWTandGetUserID(r)
	if err != nil {
		log.Println(err)
		return
	}
	userCache := user.GetUserCache(userID)
	if err := json.NewEncoder(w).Encode(processor.GetSingleCommit(userCache, sha)); err != nil {
		panic(err)
	}
}

func getQueryFromVars(vars map[string]string) processor.Query {

	query := processor.Query{}

	authors := vars["author"]
	if authors != "" {
		if form, err := url.QueryUnescape(authors); err == nil {
			authors = form
		}
		query.Authors = strings.Split(authors, ";")
	}

	repos := vars["repo"]
	if repos != "" {
		if form, err := url.QueryUnescape(repos); err == nil {
			repos = form
		}
		query.Repos = strings.Split(repos, ";")
	}

	since := vars["date"]
	if since != "" {
		if d, err := time.Parse(time.RFC3339, since); err == nil {
			query.Since = d
		}
	}

	query.Commit = vars["commit"]
	query.UseRegex = true

	return query
}

func getConfigFromForm(form url.Values) git.Config {
	config := git.Config{}
	config.GitURL = form.Get("baseURL")
	config.BaseOrganisation = form.Get("baseOrg")
	config.GitAuthkey = form.Get("authKey")
	config.MiscDefaultBranch = form.Get("defaultBranch")
	if d, err := time.Parse("2006-01-02", form.Get("sinceTime")); err == nil {
		// add a day to include commits on day 'since'
		config.SinceTime = d.AddDate(0, 0, 1)
	} else {
		config.SinceTime = time.Time{}
	}
	config.MaxRepos, _ = strconv.Atoi(form.Get("maxRepos"))
	config.MaxBranches, _ = strconv.Atoi(form.Get("maxBranches"))

	return config
}

func checkJWTandGetUserID(r *http.Request) (string, error) {
	var userID string
	JWT, err := jwtProvider.Get(r)
	if err != nil {
		// TODO no one logged in
		return "", err
	}
	claims := JWT.Claims.(jwt.MapClaims)
	userID = claims["userID"].(string)
	if userID == "" {
		return "", errors.New("Error: Empty userID in JWT!")
	}
	if claims["iatStr"] == nil {
		return "", errors.New("Error: JWT valid but no claim 'iatStr'!")
	}
	issuedAt := claims["iatStr"].(string)
	// if user isn't created yet there should be no previous issuedAt time
	if user.Exists(userID) {
		userConfig := user.GetUserCache(userID).Config
		if issuedAt < userConfig.JWTissuedAt {
			return "", errors.New("Error: JWT valid but expired! (not the latest one)")
		}
	}

	return userID, nil
}

func updateIssuedAt(userID string, issuedAt string) {
	cache := user.GetUserCache(userID)
	config := cache.Config
	config.JWTissuedAt = issuedAt
	cache.Config = config
	user.SetUserCache(userID, cache)
	processor.SaveCompleteConfig(cache, userID)
}


text:
async def f():
    yield True
    x = yield True

def f():
    async for fob in oar:
        pass

async for fob in oar:
    pass

def f():
    async with baz:
        pass

async with baz:
    pass