text:
from typing import (  # pylint: disable=unused-import
    Union, Optional, Any, IO, Iterable, AnyStr, Dict, List, Tuple,
    TypeVar, TYPE_CHECKING
)

from azure.core.exceptions import HttpResponseError
from azure.core.tracing.decorator_async import distributed_trace_async

from .._shared.response_handlers import return_response_headers, process_storage_error
from .._serialize import get_modify_conditions
from .._lease import BlobLeaseClient as LeaseClientBase

if TYPE_CHECKING:
    from datetime import datetime
    from .._generated.operations import BlobOperations, ContainerOperations
    BlobClient = TypeVar("BlobClient")
    ContainerClient = TypeVar("ContainerClient")

class BlobLeaseClient(LeaseClientBase):
    """Creates a new BlobLeaseClient.

    This client provides lease operations on a BlobClient or ContainerClient.

    :ivar str id:
        The ID of the lease currently being maintained. This will be `None` if no
        lease has yet been acquired.
    :ivar str etag:
        The ETag of the lease currently being maintained. This will be `None` if no
        lease has yet been acquired or modified.
    :ivar ~datetime.datetime last_modified:
        The last modified timestamp of the lease currently being maintained.
        This will be `None` if no lease has yet been acquired or modified.

    :param client:
        The client of the blob or container to lease.
    :type client: ~azure.storage.blob.aio.BlobClient or
        ~azure.storage.blob.aio.ContainerClient
    :param str lease_id:
        A string representing the lease ID of an existing lease. This value does not
        need to be specified in order to acquire a new lease, or break one.
    """

    def __enter__(self):
        raise TypeError("Async lease must use 'async with'.")

    def __exit__(self, *args):
        self.release()

    async def __aenter__(self):
        return self

    async def __aexit__(self, *args):
        await self.release()

    @distributed_trace_async
    async def acquire(self, lease_duration=-1, **kwargs):
        # type: (int, Any) -> None
        """Requests a new lease.

        If the container does not have an active lease, the Blob service creates a
        lease on the container and returns a new lease ID.

        :param int lease_duration:
            Specifies the duration of the lease, in seconds, or negative one
            (-1) for a lease that never expires. A non-infinite lease can be
            between 15 and 60 seconds. A lease duration cannot be changed
            using renew or change. Default is -1 (infinite lease).
        :keyword ~datetime.datetime if_modified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only
            if the resource has been modified since the specified time.
        :keyword ~datetime.datetime if_unmodified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only if
            the resource has not been modified since the specified date/time.
        :keyword str etag:
            An ETag value, or the wildcard character (*). Used to check if the resource has changed,
            and act according to the condition specified by the `match_condition` parameter.
        :keyword ~azure.core.MatchConditions match_condition:
            The match condition to use upon the etag.
        :keyword str if_tags_match_condition:
            Specify a SQL where clause on blob tags to operate only on blob with a matching value.
            eg. ``\"\\\"tagname\\\"='my tag'\"``

            .. versionadded:: 12.4.0

        :keyword int timeout:
            The timeout parameter is expressed in seconds.
        :rtype: None
        """
        mod_conditions = get_modify_conditions(kwargs)
        try:
            response = await self._client.acquire_lease(
                timeout=kwargs.pop('timeout', None),
                duration=lease_duration,
                proposed_lease_id=self.id,
                modified_access_conditions=mod_conditions,
                cls=return_response_headers,
                **kwargs)
        except HttpResponseError as error:
            process_storage_error(error)
        self.id = response.get('lease_id')  # type: str
        self.last_modified = response.get('last_modified')   # type: datetime
        self.etag = response.get('etag')  # type: str

    @distributed_trace_async
    async def renew(self, **kwargs):
        # type: (Any) -> None
        """Renews the lease.

        The lease can be renewed if the lease ID specified in the
        lease client matches that associated with the container or blob. Note that
        the lease may be renewed even if it has expired as long as the container
        or blob has not been leased again since the expiration of that lease. When you
        renew a lease, the lease duration clock resets.

        :keyword ~datetime.datetime if_modified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only
            if the resource has been modified since the specified time.
        :keyword ~datetime.datetime if_unmodified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only if
            the resource has not been modified since the specified date/time.
        :keyword str etag:
            An ETag value, or the wildcard character (*). Used to check if the resource has changed,
            and act according to the condition specified by the `match_condition` parameter.
        :keyword ~azure.core.MatchConditions match_condition:
            The match condition to use upon the etag.
        :keyword str if_tags_match_condition:
            Specify a SQL where clause on blob tags to operate only on blob with a matching value.
            eg. ``\"\\\"tagname\\\"='my tag'\"``

            .. versionadded:: 12.4.0

        :keyword int timeout:
            The timeout parameter is expressed in seconds.
        :return: None
        """
        mod_conditions = get_modify_conditions(kwargs)
        try:
            response = await self._client.renew_lease(
                lease_id=self.id,
                timeout=kwargs.pop('timeout', None),
                modified_access_conditions=mod_conditions,
                cls=return_response_headers,
                **kwargs)
        except HttpResponseError as error:
            process_storage_error(error)
        self.etag = response.get('etag')  # type: str
        self.id = response.get('lease_id')  # type: str
        self.last_modified = response.get('last_modified')   # type: datetime

    @distributed_trace_async
    async def release(self, **kwargs):
        # type: (Any) -> None
        """Release the lease.

        The lease may be released if the client lease id specified matches
        that associated with the container or blob. Releasing the lease allows another client
        to immediately acquire the lease for the container or blob as soon as the release is complete.

        :keyword ~datetime.datetime if_modified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only
            if the resource has been modified since the specified time.
        :keyword ~datetime.datetime if_unmodified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only if
            the resource has not been modified since the specified date/time.
        :keyword str etag:
            An ETag value, or the wildcard character (*). Used to check if the resource has changed,
            and act according to the condition specified by the `match_condition` parameter.
        :keyword ~azure.core.MatchConditions match_condition:
            The match condition to use upon the etag.
        :keyword str if_tags_match_condition:
            Specify a SQL where clause on blob tags to operate only on blob with a matching value.
            eg. ``\"\\\"tagname\\\"='my tag'\"``

            .. versionadded:: 12.4.0

        :keyword int timeout:
            The timeout parameter is expressed in seconds.
        :return: None
        """
        mod_conditions = get_modify_conditions(kwargs)
        try:
            response = await self._client.release_lease(
                lease_id=self.id,
                timeout=kwargs.pop('timeout', None),
                modified_access_conditions=mod_conditions,
                cls=return_response_headers,
                **kwargs)
        except HttpResponseError as error:
            process_storage_error(error)
        self.etag = response.get('etag')  # type: str
        self.id = response.get('lease_id')  # type: str
        self.last_modified = response.get('last_modified')   # type: datetime

    @distributed_trace_async
    async def change(self, proposed_lease_id, **kwargs):
        # type: (str, Any) -> None
        """Change the lease ID of an active lease.

        :param str proposed_lease_id:
            Proposed lease ID, in a GUID string format. The Blob service returns 400
            (Invalid request) if the proposed lease ID is not in the correct format.
        :keyword ~datetime.datetime if_modified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only
            if the resource has been modified since the specified time.
        :keyword ~datetime.datetime if_unmodified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only if
            the resource has not been modified since the specified date/time.
        :keyword str etag:
            An ETag value, or the wildcard character (*). Used to check if the resource has changed,
            and act according to the condition specified by the `match_condition` parameter.
        :keyword ~azure.core.MatchConditions match_condition:
            The match condition to use upon the etag.
        :keyword str if_tags_match_condition:
            Specify a SQL where clause on blob tags to operate only on blob with a matching value.
            eg. ``\"\\\"tagname\\\"='my tag'\"``

            .. versionadded:: 12.4.0

        :keyword int timeout:
            The timeout parameter is expressed in seconds.
        :return: None
        """
        mod_conditions = get_modify_conditions(kwargs)
        try:
            response = await self._client.change_lease(
                lease_id=self.id,
                proposed_lease_id=proposed_lease_id,
                timeout=kwargs.pop('timeout', None),
                modified_access_conditions=mod_conditions,
                cls=return_response_headers,
                **kwargs)
        except HttpResponseError as error:
            process_storage_error(error)
        self.etag = response.get('etag')  # type: str
        self.id = response.get('lease_id')  # type: str
        self.last_modified = response.get('last_modified')   # type: datetime

    @distributed_trace_async
    async def break_lease(self, lease_break_period=None, **kwargs):
        # type: (Optional[int], Any) -> int
        """Break the lease, if the container or blob has an active lease.

        Once a lease is broken, it cannot be renewed. Any authorized request can break the lease;
        the request is not required to specify a matching lease ID. When a lease
        is broken, the lease break period is allowed to elapse, during which time
        no lease operation except break and release can be performed on the container or blob.
        When a lease is successfully broken, the response indicates the interval
        in seconds until a new lease can be acquired.

        :param int lease_break_period:
            This is the proposed duration of seconds that the lease
            should continue before it is broken, between 0 and 60 seconds. This
            break period is only used if it is shorter than the time remaining
            on the lease. If longer, the time remaining on the lease is used.
            A new lease will not be available before the break period has
            expired, but the lease may be held for longer than the break
            period. If this header does not appear with a break
            operation, a fixed-duration lease breaks after the remaining lease
            period elapses, and an infinite lease breaks immediately.
        :keyword ~datetime.datetime if_modified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only
            if the resource has been modified since the specified time.
        :keyword ~datetime.datetime if_unmodified_since:
            A DateTime value. Azure expects the date value passed in to be UTC.
            If timezone is included, any non-UTC datetimes will be converted to UTC.
            If a date is passed in without timezone info, it is assumed to be UTC.
            Specify this header to perform the operation only if
            the resource has not been modified since the specified date/time.
        :keyword str if_tags_match_condition:
            Specify a SQL where clause on blob tags to operate only on blob with a matching value.
            eg. ``\"\\\"tagname\\\"='my tag'\"``

            .. versionadded:: 12.4.0

        :keyword int timeout:
            The timeout parameter is expressed in seconds.
        :return: Approximate time remaining in the lease period, in seconds.
        :rtype: int
        """
        mod_conditions = get_modify_conditions(kwargs)
        try:
            response = await self._client.break_lease(
                timeout=kwargs.pop('timeout', None),
                break_period=lease_break_period,
                modified_access_conditions=mod_conditions,
                cls=return_response_headers,
                **kwargs)
        except HttpResponseError as error:
            process_storage_error(error)
        return response.get('lease_time') # type: ignore


text:
SavePasswordRefusalComboboxModel::SavePasswordRefusalComboboxModel() {
  items_.push_back(
      l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_CANCEL_BUTTON));
  items_.push_back(
      l10n_util::GetStringUTF16(IDS_PASSWORD_MANAGER_BLACKLIST_BUTTON));
}

SavePasswordRefusalComboboxModel::~SavePasswordRefusalComboboxModel() {}

int SavePasswordRefusalComboboxModel::GetItemCount() const {
  return items_.size();
}

base::string16 SavePasswordRefusalComboboxModel::GetItemAt(int index) {
  return items_[index];
}

bool SavePasswordRefusalComboboxModel::IsItemSeparatorAt(int index) {
  return items_[index].empty();
}

int SavePasswordRefusalComboboxModel::GetDefaultIndex() const {
  return 0;
}

redpajama_set_name: RedPajamaGithub


text:
@implementation JTCalendarScrollManager

- (void)setMenuPreviousDate:(NSDate *)previousDate
                currentDate:(NSDate *)currentDate
                   nextDate:(NSDate *)nextDate
{
    if(!_menuView){
        return;
    }

    [_menuView setPreviousDate:previousDate currentDate:currentDate nextDate:nextDate];
}

- (void)updateMenuContentOffset:(CGFloat)percentage pageMode:(NSUInteger)pageMode
{
    if(!_menuView){
        return;
    }

    [_menuView updatePageMode:pageMode];
    _menuView.scrollView.contentOffset = CGPointMake(percentage * _menuView.scrollView.contentSize.width, 0);
}

- (void)updateHorizontalContentOffset:(CGFloat)percentage
{
    if(!_horizontalContentView){
        return;
    }

    _horizontalContentView.contentOffset = CGPointMake(percentage * _horizontalContentView.contentSize.width, 0);
}

- (void)endHorizontalScrollingAnimation
{
    if(![_horizontalContentView.delegate respondsToSelector:@selector(scrollViewDidEndScrollingAnimation:)]){
        return;
    }

    [_horizontalContentView.delegate scrollViewDidEndScrollingAnimation:_horizontalContentView];
}

@end


text:
@interface addCacheTableViewController : UITableViewController

@property(nonatomic,strong) IBOutlet UILabel *nameLabel;
@property(nonatomic,strong) IBOutlet UIButton *minLabel;
@property(nonatomic,strong) IBOutlet UIButton *maxLabel;
@property(nonatomic,strong) IBOutlet UILabel *rangeLabel;
@property(nonatomic,strong) IBOutlet UITextField *textLabel;
@property(nonatomic,strong) DBCache *cache;
@property(nonatomic,strong) IBOutlet UIButton *startCache;

- (IBAction)addCache:(id)sender;

@end


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            //Sonata admin
            new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
            new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),
            new Sonata\CoreBundle\SonataCoreBundle(),
            new Sonata\BlockBundle\SonataBlockBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new Sonata\AdminBundle\SonataAdminBundle(),
            //Sonata user
            new FOS\UserBundle\FOSUserBundle(),
            new Sonata\UserBundle\SonataUserBundle('FOSUserBundle'),
            new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
            //Sonata notification
            new Sonata\NotificationBundle\SonataNotificationBundle(),
            new Application\Sonata\NotificationBundle\ApplicationSonataNotificationBundle(),
            //Sonata media
            new Sonata\MediaBundle\SonataMediaBundle(),
            new Application\Sonata\MediaBundle\ApplicationSonataMediaBundle(),
            //CalendarBundle
            new FOS\JsRoutingBundle\FOSJsRoutingBundle(),
            new ADesigns\CalendarBundle\ADesignsCalendarBundle(),
            new Success\EventBundle\SuccessEventBundle(),
            new Success\PlaceholderBundle\SuccessPlaceholderBundle(),
            new Success\NotificationBundle\SuccessNotificationBundle(),
            //new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
            new Success\SettingsBundle\SuccessSettingsBundle(),
            new JMS\SerializerBundle\JMSSerializerBundle(),
            new JMS\DiExtraBundle\JMSDiExtraBundle($this),
            new JMS\AopBundle\JMSAopBundle(),
            new Success\SiteBundle\SuccessSiteBundle(),
            new Success\MemberBundle\SuccessMemberBundle(),
            new Success\SalesGeneratorBundle\SuccessSalesGeneratorBundle(),
            new Sensio\Bundle\BuzzBundle\SensioBuzzBundle(),
            new Sonata\IntlBundle\SonataIntlBundle(),
            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
            new Success\TreasureBundle\SuccessTreasureBundle(),
            new Success\PricingBundle\SuccessPricingBundle(),
            new Snc\RedisBundle\SncRedisBundle(),
            new SmartCore\Bundle\AcceleratorCacheBundle\AcceleratorCacheBundle(),
            new Success\StaticPageBundle\SuccessStaticPageBundle(),
            new Ivory\CKEditorBundle\IvoryCKEditorBundle(),
            new JMS\JobQueueBundle\JMSJobQueueBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
            $bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle();
            $bundles[] = new Epam\CiBundle\EpamCiBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }

    public function init()
    {
        ini_set('date.timezone', 'Europe/Moscow');
    }
}


text:
package org.keycloak.events.jpa;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.logging.Logger;
import org.keycloak.events.Event;
import org.keycloak.events.EventQuery;
import org.keycloak.events.EventStoreProvider;
import org.keycloak.events.EventType;
import org.keycloak.events.admin.AdminEvent;
import org.keycloak.events.admin.AdminEventQuery;
import org.keycloak.events.admin.AuthDetails;
import org.keycloak.events.admin.OperationType;

import javax.persistence.EntityManager;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @author Stian Thorgersen
 */
public class JpaEventStoreProvider implements EventStoreProvider {

    private static final ObjectMapper mapper = new ObjectMapper();
    private static final TypeReference<Map<String, String>> mapType = new TypeReference<Map<String, String>>() {
    };
    private static final Logger logger = Logger.getLogger(JpaEventStoreProvider.class);

    private EntityManager em;

    public JpaEventStoreProvider(EntityManager em) {
        this.em = em;
    }

    @Override
    public EventQuery createQuery() {
        return new JpaEventQuery(em);
    }

    @Override
    public void clear() {
        em.createQuery("delete from EventEntity").executeUpdate();
    }

    @Override
    public void clear(String realmId) {
        em.createQuery("delete from EventEntity where realmId = :realmId").setParameter("realmId", realmId).executeUpdate();
    }

    @Override
    public void clear(String realmId, long olderThan) {
        em.createQuery("delete from EventEntity where realmId = :realmId and time < :time").setParameter("realmId", realmId).setParameter("time", olderThan).executeUpdate();
    }

    @Override
    public void onEvent(Event event) {
        em.persist(convertEvent(event));
    }

    @Override
    public AdminEventQuery createAdminQuery() {
        return new JpaAdminEventQuery(em);
    }

    @Override
    public void clearAdmin() {
        em.createQuery("delete from AdminEventEntity").executeUpdate();
    }

    @Override
    public void clearAdmin(String realmId) {
        em.createQuery("delete from AdminEventEntity where realmId = :realmId").setParameter("realmId", realmId).executeUpdate();
    }

    @Override
    public void clearAdmin(String realmId, long olderThan) {
        em.createQuery("delete from AdminEventEntity where realmId = :realmId and time < :time").setParameter("realmId", realmId).setParameter("time", olderThan).executeUpdate();
    }

    @Override
    public void onEvent(AdminEvent event, boolean includeRepresentation) {
        em.persist(convertAdminEvent(event, includeRepresentation));
    }

    @Override
    public void close() {
    }

    static EventEntity convertEvent(Event event) {
        EventEntity eventEntity = new EventEntity();
        eventEntity.setId(UUID.randomUUID().toString());
        eventEntity.setTime(event.getTime());
        eventEntity.setType(event.getType().toString());
        eventEntity.setRealmId(event.getRealmId());
        eventEntity.setClientId(event.getClientId());
        eventEntity.setUserId(event.getUserId());
        eventEntity.setSessionId(event.getSessionId());
        eventEntity.setIpAddress(event.getIpAddress());
        eventEntity.setError(event.getError());
        try {
            eventEntity.setDetailsJson(mapper.writeValueAsString(event.getDetails()));
        } catch (IOException ex) {
            logger.error("Failed to write log details", ex);
        }
        return eventEntity;
    }

    static Event convertEvent(EventEntity eventEntity) {
        Event event = new Event();
        event.setTime(eventEntity.getTime());
        event.setType(EventType.valueOf(eventEntity.getType()));
        event.setRealmId(eventEntity.getRealmId());
        event.setClientId(eventEntity.getClientId());
        event.setUserId(eventEntity.getUserId());
        event.setSessionId(eventEntity.getSessionId());
        event.setIpAddress(eventEntity.getIpAddress());
        event.setError(eventEntity.getError());
        try {
            Map<String, String> details = mapper.readValue(eventEntity.getDetailsJson(), mapType);
            event.setDetails(details);
        } catch (IOException ex) {
            logger.error("Failed to read log details", ex);
        }
        return event;
    }

    static AdminEventEntity convertAdminEvent(AdminEvent adminEvent, boolean includeRepresentation) {
        AdminEventEntity adminEventEntity = new AdminEventEntity();
        adminEventEntity.setId(UUID.randomUUID().toString());
        adminEventEntity.setTime(adminEvent.getTime());
        adminEventEntity.setRealmId(adminEvent.getRealmId());
        setAuthDetails(adminEventEntity, adminEvent.getAuthDetails());
        adminEventEntity.setOperationType(adminEvent.getOperationType().toString());

        if (adminEvent.getResourceTypeAsString() != null) {
            adminEventEntity.setResourceType(adminEvent.getResourceTypeAsString());
        }

        adminEventEntity.setResourcePath(adminEvent.getResourcePath());
        adminEventEntity.setError(adminEvent.getError());

        if(includeRepresentation) {
            adminEventEntity.setRepresentation(adminEvent.getRepresentation());
        }
        return adminEventEntity;
    }

    static AdminEvent convertAdminEvent(AdminEventEntity adminEventEntity) {
        AdminEvent adminEvent = new AdminEvent();
        adminEvent.setTime(adminEventEntity.getTime());
        adminEvent.setRealmId(adminEventEntity.getRealmId());
        setAuthDetails(adminEvent, adminEventEntity);
        adminEvent.setOperationType(OperationType.valueOf(adminEventEntity.getOperationType()));

        if (adminEventEntity.getResourceType() != null) {
            adminEvent.setResourceTypeAsString(adminEventEntity.getResourceType());
        }

        adminEvent.setResourcePath(adminEventEntity.getResourcePath());
        adminEvent.setError(adminEventEntity.getError());

        if(adminEventEntity.getRepresentation() != null) {
            adminEvent.setRepresentation(adminEventEntity.getRepresentation());
        }
        return adminEvent;
    }

    private static void setAuthDetails(AdminEventEntity adminEventEntity, AuthDetails authDetails) {
        adminEventEntity.setAuthRealmId(authDetails.getRealmId());
        adminEventEntity.setAuthClientId(authDetails.getClientId());
        adminEventEntity.setAuthUserId(authDetails.getUserId());
        adminEventEntity.setAuthIpAddress(authDetails.getIpAddress());
    }

    private static void setAuthDetails(AdminEvent adminEvent, AdminEventEntity adminEventEntity) {
        AuthDetails authDetails = new AuthDetails();
        authDetails.setRealmId(adminEventEntity.getAuthRealmId());
        authDetails.setClientId(adminEventEntity.getAuthClientId());
        authDetails.setUserId(adminEventEntity.getAuthUserId());
        authDetails.setIpAddress(adminEventEntity.getAuthIpAddress());
        adminEvent.setAuthDetails(authDetails);
    }

}


text:
title: Site-wide content report
summary: View report of all content on your site (and subsites).

# Site-wide content report user guide

## Viewing the report
To view the report, navigate to 'Reports' in the menu on the left and click on 'Site-wide content report'.
From here you can view the basic information of every page and file in the CMS. To view a specific page or file, simply click on its name.

![Finding site-wide content report](_images/finding-the-report.png)

## Using site-wide content report with subsites
By default, site-wide content report will show pages and files across all subsites. To view the pages and files from a specific subsite, simply select the 'Filter by' dropdown and click on the subsite you wish to view.

![Changing subsite](_images/changing-subsite.png)


text:
from math import *

# ==================================
# Intersect3D: provides a set of static 3D intersection functions
# ==================================
class Intersect3D:
    """ Collection of intersection functions, """
    # very small value
    epsilon = 0.000000001

    def ray_OBB(r_origin, r_dir, b_pos, b_orientation, b_halflengths):
        """ Intersects a ray with an oriented bounding box.
            r_origin = origin of the ray
            r_dir = normalized direction of the ray
            b_pos = position of the box
            b_orientation = list of normalised half length vectors of the box
            b_halflengths = list of positive half lengths of the box
            returns the distance from r_origin to the point of intersection
        """
        tmin = -10000
        tmax = 10000

        p = b_pos-r_origin
        for i in range(3):
            a = b_orientation[i]-p
            h = b_halflengths[i]
            e = a.dot(p)
            f = a.dot(r_dir)
            if abs(f)>Intersect3D.epsilon:
                t1 = (e+h)/f
                t2 = (e-h)/f
                if t1 > t2:
                    x = t1
                    t1 = t2
                    t2 = x
                if t1 > tmin: tmin = t1
                if t2 < tmax: tmax = t2
                if tmin > tmax: return 0
                if tmax < 0: return 0
            elif -e-h > 0 or -e+h < 0: return 0
        if tmin > 0: return tmin
        else: return tmax
    ray_OBB = staticmethod(ray_OBB)

    def ray_Plane(r_origin, r_dir, p_points):
        """ Intersects a ray with a plane.
            r_origin = origin of the ray
            r_dir = normalized direction of the ray
            points = list of 3 Vectors that represent non collinear points on the plane
            returns the distance from r_origin to the point of intersection
        """
        #determine the implicit equation of the plane
        p = p_points[0]
        n = (p_points[0]-p_points[2]).cross(p_points[1]-p_points[2])
        d = -n.dot(p)

        # test if the ray is parallel
        den = n.dot(r_dir)
        if abs(den)<Intersect3D.epsilon:
            return 0

        # calc distance to point of intersection
        nom = -d - n.dot(r_origin)
        return nom/den
    ray_Plane = staticmethod(ray_Plane)

    def ray_Polygon(r_origin, r_dir, p_points):
        """ Intersects a ray with a polygon.
            r_origin = origin of the ray
            r_dir = normalized direction of the ray
            points = list of Vectors that represent the points of the polygon
            returns the distance from r_origin to the point of intersection
        """
        #determine the implicit equation of the corresponding plane
        p = p_points[0]
        n = (p_points[0]-p_points[2]).cross(p_points[1]-p_points[2])
        d = -n.dot(p)

        # test if the ray is parallel
        den = n.dot(r_dir)
        if abs(den)<Intersect3D.epsilon:
            t = 0
        else:
            # calc distance to point of intersection
            nom = -d - n.dot(r_origin)
            t = nom/den

        # determine point of intersection p
        if t==0:
            return 0
        p3d = r_origin+r_dir*t

        # project points of polyon to axis plane where polygon area is maximized
        maxn = max(abs(n.x), abs(n.y), abs(n.z))
        if abs(n.x) == maxn:
            points = [[point.y, point.z] for point in p_points]
            p = [p3d.y, p3d.z]
        elif abs(n.y) == maxn:
            points = [[point.x, point.z] for point in p_points]
            p = [p3d.x, p3d.z]
        elif abs(n.z) == maxn:
            points = [[point.x, point.y] for point in p_points]
            p = [p3d.x, p3d.y]

        # do crossings test
        inside = False
        e0 = points[-1]
        e1 = points[0]
        y0 = e0[1] >= p[1]
        for i in range(1, len(points)+1):
            y1 = e1[1] >= p[1]
            if y0 != y1:
                y2 = (e1[1]-p[1])*(e0[0]-e1[0]) >= (e1[0]-p[0])*(e0[1]-e1[1])
                if y2 == y1:
                    inside = not inside
            if i < len(points):
                y0 = y1
                e0 = e1
                e1 = points[i]

        # if inside return intersection distance
        if inside:
            return t
        else: return 0
    ray_Polygon = staticmethod(ray_Polygon)

    def ray_Sphere():
        pass

    def plane_OOB():
        pass

    def OOB_OOB():
        pass


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE library PUBLIC "-//Boost//DTD BoostBook XML V1.0//EN"
"../../../tools/boostbook/dtd/boostbook.dtd">

  <title>Date Time IO Tutorial</title>
  <bridgehead renderas="sect2">Date Time IO Tutorial</bridgehead>

  <link linkend="basic_use">Basic Use</link> |
  <link linkend="format_strings">Format Strings</link> |
  <link linkend="content_strings">Content Strings</link> |
  <link linkend="tut_sv">Special Values</link> |
  <link linkend="tut_dper">Date/Time Periods</link> |
  <link linkend="tut_dgen">Date Generators</link>

  <anchor id="basic_use" />
  <bridgehead renderas="sect4">Basic Use</bridgehead>
  <para>Facets are automatically imbued when operators '>>' and '<<' are called. The list of date_time objects that can be streamed are:</para>
  <bridgehead renderas="sect5">Gregorian</bridgehead>
  <para>
    date,
    days,
    date_period,
    greg_month,
    greg_weekday,
    greg_year,
    partial_date,
    nth_day_of_the_week_in_month,
    first_day_of_the_week_in_month,
    last_day_of_the_week_in_month,
    first_day_of_the_week_after,
    first_day_of_the_week_before
  </para>
  <bridgehead renderas="sect5">Posix_time</bridgehead>
  <para>
    ptime,
    time_period,
    time_duration
  </para>
  <bridgehead renderas="sect5">Local_time</bridgehead>
  <para>
    local_date_time
  </para>

  <para>
    The following example is of the basic use of the new IO code, utilizing all the defaults. (this example can be found in the libs/date_time/example/tutorial directory)
  </para>
  <programlisting>
    <![CDATA[
  date d(2004, Feb, 29);
  time_duration td(12,34,56,789);
  stringstream ss;
  ss << d << ' ' << td;
  ptime pt(not_a_date_time);
  cout << pt << endl; // "not-a-date-time"
  ss >> pt;
  cout << pt << endl; // "2004-Feb-29 12:34:56.000789"
  ss.str("");
  ss << pt << " EDT-05EDT,M4.1.0,M10.5.0";
  local_date_time ldt(not_a_date_time);
  ss >> ldt;
  cout << ldt << endl; // "2004-Feb-29 12:34:56.000789 EDT"
    ]]>
  </programlisting>

  <para>This example used the default settings for the input and output facets. The default formats are such that interoperability like that shown in the example is possible. NOTE: Input streaming of local_date_time can only be done with a <link linkend="date_time.local_time.posix_time_zone">posix time zone string</link>. The default output format uses a time zone abbreviation. The format can be changed so out and in match (as we will see later in this tutorial).</para>

  <anchor id="format_strings" />
  <bridgehead renderas="sect4">Format Strings</bridgehead>
  <para>The format strings control the order, type, and style of the date/time elements used. The facets provide some predefined formats (iso_format_specifier, iso_format_extended_specifier, and default_date_format) but the user can easily create their own.</para>
  (continued from previous example)
  <programlisting>
    <![CDATA[
  local_time_facet* output_facet = new local_time_facet();
  local_time_input_facet* input_facet = new local_time_input_facet();
  ss.imbue(locale(locale::classic(), output_facet));
  ss.imbue(locale(ss.getloc(), input_facet));

  output_facet->format("%a %b %d, %H:%M %z");
  ss.str("");
  ss << ldt;
  cout << ss.str() << endl; // "Sun Feb 29, 12:34 EDT"

  output_facet->format(local_time_facet::iso_time_format_specifier);
  ss.str("");
  ss << ldt;
  cout << ss.str() << endl; // "20040229T123456.000789-0500"

  output_facet->format(local_time_facet::iso_time_format_extended_specifier);
  ss.str("");
  ss << ldt;
  cout << ss.str() << endl; // "2004-02-29 12:34:56.000789-05:00"
    ]]>
  </programlisting>

  <para>Format strings are not limited to date/time elements. Extra verbiage can be placed in a format string. NOTE: When extra verbiage is present in an input format, the data being input must also contain the exact verbiage.</para>
  (continued from previous example)
  <programlisting>
    <![CDATA[
  // extra words in format
  string my_format("The extended ordinal time %Y-%jT%H:%M can also be \
  represented as %A %B %d, %Y");
  output_facet->format(my_format.c_str());
  input_facet->format(my_format.c_str());
  ss.str("");
  ss << ldt;
  cout << ss.str() << endl;

  // matching extra words in input
  ss.str("The extended ordinal time 2005-128T12:15 can also be \
  represented as Sunday May 08, 2005");
  ss >> ldt;
  cout << ldt << endl;
    ]]>
  </programlisting>

  <anchor id="content_strings" />
  <bridgehead renderas="sect4">Content Strings</bridgehead>
  <para>So far we've shown how a user can achieve a great deal of customization with very little effort by using formats. Further customization can be achieved through user defined elements (ie strings). The elements that can be customized are: Special value names, month names, month abbreviations, weekday names, weekday abbreviations, delimiters of the date/time periods, and the phrase elements of the date_generators.</para>
  <para>The default values for these are as follows:</para>
  <bridgehead renderas="sect5">Special values</bridgehead>
  <para>
    not-a-date-time,
    -infinity,
    +infinity,
    minimum-date-time,
    maximum-date-time
  </para>
  <bridgehead renderas="sect5">Months</bridgehead>
  <para>
    English calendar and three letter abbreviations
  </para>
  <bridgehead renderas="sect5">Weekdays</bridgehead>
  <para>
    English calendar and three letter abbreviations
  </para>
  <bridgehead renderas="sect5">Date generator phrase elements</bridgehead>
  <para>
    first,
    second,
    third,
    fourth,
    fifth,
    last,
    before,
    after,
    of
  </para>
  <para>NOTE: We've shown earlier that the components of a date/time representation can be re-ordered via the format string. This is not the case with date_generators. The elements themselves can be customized but their order cannot be changed.</para>

  <bridgehead renderas="sect4">Content Strings</bridgehead>
  <para>To illustrate the customization possibilities we will use custom strings for months and weekdays (we will only use long names, is all lowercase, for this example).</para>
  (continued from previous example)
  <programlisting>
    <![CDATA[
  // set up the collections of custom strings.
  // only the full names are altered for the sake of brevity
  string month_names[12] = { "january", "february", "march",
                             "april", "may", "june",
                             "july", "august", "september",
                             "october", "november", "december" };
  vector<string> long_months(&month_names[0], &month_names[12]);
  string day_names[7] = { "sunday", "monday", "tuesday", "wednesday",
                          "thursday", "friday", "saturday" };
  vector<string> long_days(&day_names[0], &day_names[7]);

  //  create date_facet and date_input_facet using all defaults
  date_facet* date_output = new date_facet();
  date_input_facet* date_input = new date_input_facet();
  ss.imbue(locale(ss.getloc(), date_output));
  ss.imbue(locale(ss.getloc(), date_input));

  // replace names in the output facet
  date_output->long_month_names(long_months);
  date_output->long_weekday_names(long_days);

  // replace names in the input facet
  date_input->long_month_names(long_months);
  date_input->long_weekday_names(long_days);

  // customize month, weekday and date formats
  date_output->format("%Y-%B-%d");
  date_input->format("%Y-%B-%d");
  date_output->month_format("%B"); // full name
  date_input->month_format("%B"); // full name
  date_output->weekday_format("%A"); // full name
  date_input->weekday_format("%A"); // full name

  ss.str("");
  ss << greg_month(3);
  cout << ss.str() << endl; // "march"
  ss.str("");
  ss << greg_weekday(3);
  cout << ss.str() << endl; // "tuesday"
  ss.str("");
  ss << date(2005,Jul,4);
  cout << ss.str() << endl; // "2005-july-04"
    ]]>
  </programlisting>

  <anchor id="tut_sv" />
  <bridgehead renderas="sect4">Special Values</bridgehead>
  <para>Customizing the input and output of special values is best done by creating a new special_values_parser and special_values_formatter. The new strings can be set at construction time (as in the example below).</para>
  (continued from previous example)
  <programlisting>
    <![CDATA[
  // reset the formats to defaults
  output_facet->format(local_time_facet::default_time_format);
  input_facet->format(local_time_input_facet::default_time_input_format);

  // create custom special_values parser and formatter objects
  // and add them to the facets
  string sv[5] = {"nadt","neg_inf", "pos_inf", "min_dt", "max_dt" };
  vector<string> sv_names(&sv[0], &sv[5]);
  special_values_parser sv_parser(sv_names.begin(), sv_names.end());
  special_values_formatter sv_formatter(sv_names.begin(), sv_names.end());
  output_facet->special_values_formatter(sv_formatter);
  input_facet->special_values_parser(sv_parser);

  ss.str("");
  ldt = local_date_time(not_a_date_time);
  ss << ldt;
  cout << ss.str() << endl; // "nadt"

  ss.str("min_dt");
  ss >> ldt;
  ss.str("");
  ss << ldt;
  cout << ss.str() << endl; // "1400-Jan-01 00:00:00 UTC"
    ]]>
  </programlisting>
  <para>NOTE: even though we sent in strings for min and max to the formatter, they are ignored because those special values construct to actual dates (as shown above).</para>

  <anchor id="tut_dper" />
  <bridgehead renderas="sect4">Date/Time Periods</bridgehead>
  <para>Customizing the input and output of periods is best done by creating a new period_parser and period_formatter. The new strings can be set at construction time (as in the example below).</para>
  (continued from previous example)
  <programlisting>
    <![CDATA[
  // all formats set back to defaults (not shown for brevity)

  // create our date_period
  date_period dp(date(2005,Mar,1), days(31)); // month of march

  // custom period formatter and parser
  period_formatter per_formatter(period_formatter::AS_OPEN_RANGE,
                                 " to ", "from ", " exclusive", " inclusive" );
  period_parser per_parser(period_parser::AS_OPEN_RANGE,
                           " to ", "from ", " exclusive" , "inclusive" );

  // default output
  ss.str("");
  ss << dp;
  cout << ss.str() << endl; // "[2005-Mar-01/2005-Mar-31]"

  // add out custom parser and formatter to  the facets
  date_output->period_formatter(per_formatter);
  date_input->period_parser(per_parser);

  // custom output
  ss.str("");
  ss << dp;
  cout << ss.str() << endl; // "from 2005-Feb-01 to 2005-Apr-01 exclusive"
    ]]>
  </programlisting>

  <anchor id="tut_dgen" />
  <bridgehead renderas="sect4">Date Generators</bridgehead>
  <para>Customizing the input and output of date_generators is done by replacing the existing strings (in the facet) with new strings.</para>
  <para>NOTE: We've shown earlier that the components of a date/time representation can be re-ordered via the format string. This is not the case with date_generators. The elements themselves can be customized but their order cannot be changed.</para>
  (continued from previous example)
  <programlisting>
    <![CDATA[
  // custom date_generator phrases
  string dg_phrases[9] = { "1st", "2nd", "3rd", "4th", "5th",
                           "final", "prior to", "following", "in" };
  vector<string> phrases(&dg_phrases[0], &dg_phrases[9]);

  // create our date_generator
  first_day_of_the_week_before d_gen(Monday);

  // default output
  ss.str("");
  ss << d_gen;
  cout << ss.str() << endl; // "Mon before"

  // add our custom strings to the date facets
  date_output->date_gen_phrase_strings(phrases);
  date_input->date_gen_element_strings(phrases);

  // custom output
  ss.str("");
  ss << d_gen;
  cout << ss.str() << endl; // "Mon prior to"
    ]]>
  </programlisting>


text:
#include <Python.h>

typedef struct {
    PyObject_HEAD
    /* Type-specific fields go here. */
} CustomObject;

static PyTypeObject CustomType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    .tp_name = "custom.Custom",
    .tp_doc = "Custom objects",
    .tp_basicsize = sizeof(CustomObject),
    .tp_itemsize = 0,
    .tp_flags = Py_TPFLAGS_DEFAULT,
    .tp_new = PyType_GenericNew,
};

static PyModuleDef custommodule = {
    PyModuleDef_HEAD_INIT,
    .m_name = "custom",
    .m_doc = "Example module that creates an extension type.",
    .m_size = -1,
};

PyMODINIT_FUNC
PyInit_custom(void)
{
    PyObject *m;
    if (PyType_Ready(&CustomType) < 0)
        return NULL;

    m = PyModule_Create(&custommodule);
    if (m == NULL)
        return NULL;

    Py_INCREF(&CustomType);
    PyModule_AddObject(m, "Custom", (PyObject *) &CustomType);
    return m;
}


text:
println("Plot data for the photonreceptor model using:")
println(" pyplot_photonsequence()")
println(" pyplot_bump(timepoints,amplitude = 4.0,shape = 3.0,scale =2.5)")

### Plot the photon sequence data using the PyPlot package
function pyplot_photonsequence()

    #calculate the data
    photons = photonsequence(10:100,1000)
    timepoints = dataindex(photons)

    #plot the data
    fig = PyPlot.figure("functionality/photoreceptor")
    PyPlot.plot(timepoints,datavalues(photons))
    PyPlot.xlabel("Time (s)")
    PyPlot.ylabel("Photons")
    PyPlot.title("Photon Sequence")
    PyPlot.grid("on")

    #return the figure object
    fig
end

function pyplot_bump(timepoints,amplitude = 4.0,shape = 3.0,scale = 2.5)

    #calculate the data
    bmp = bump(collect(timepoints),amplitude,shape,scale)

    #plot the data
    fig = PyPlot.figure("functionality/bump")
    PyPlot.plot(timepoints/1000.0,bmp)
    PyPlot.xlabel("Time (s)")
    PyPlot.ylabel("Current (nA)")
    PyPlot.title("Photon-Induced Current")
    PyPlot.grid("on")
end

pyplot_photonsequence()
pyplot_bump(1.0:1.0:30.0)

# File return statement
nothing


text:
<link rel=stylesheet type=text/css href='/ishwarcom.css'>
<title>Holy Quran (Pickthall) : 84. al-Inshiqaq: The Rending </TITLE>

84. al-Inshiqaq: The Rending

1

When the heaven is split asunder

2

And attentive to her Lord in fear,

3

And when the earth is spread out

4

And hath cast out all that was in her, and is empty

5

And attentive to her Lord in fear!

6

Thou, verily, O man, art working toward thy Lord a work which thou wilt  meet (in His presence).

7

Then whoso is given his account in his right hand

8

He truly will receive an easy reckoning

9

And will return unto his folk in joy.

10

But whoso is given his account behind his back,

11

He surely will invoke destruction

12

And be thrown to scorching fire.

13

He verily lived joyous with his folk,

14

He verily deemed that he would never return (unto Allah).

15

Nay, but lo! his Lord is ever looking on him!

16

Oh, I swear by the afterglow of sunset,

17

And by the night and all that it enshroudeth,

18

And by the moon when she is at the full,

19

That ye shall journey on from plane to plane.

20

What aileth them, then, that they believe not

21

And, when the Qur'an is recited unto them, worship not (Allah) ?

22

Nay, but those who disbelieve will deny;

23

And Allah knoweth best what they are hiding.

24

So give them tidings of a painful doom,

25

Save those who believe and do good works, for theirs is a reward unfailing.

-- Sura 84 --


text:
namespace GRC {

class Poll;
class PollReference;
class PollResult;
class Vote;

using PollOption = std::optional<Poll>;
using PollResultOption = std::optional<PollResult>;

//!
//! \brief The unspent amount that a poll creator must hold in an address.
//!
constexpr CAmount POLL_REQUIRED_BALANCE = 100000 * COIN;

//!
//! \brief The maximum number of choices that a poll can contain.
//!
constexpr size_t POLL_MAX_CHOICES_SIZE = 20;

//!
//! \brief Describes the poll types.
//!
//! CONSENSUS: Do not remove or reorder items in this enumeration except for
//! OUT_OF_BOUND which must remain at the end.
//!
//! TODO: we may add additional poll types with specialized requirements, data,
//! or behavior such as project whitelist polls.
//!
enum class PollType
{
    UNKNOWN,       //!< An invalid, non-standard, or empty poll type.
    SURVEY,        //!< For casual, opinion, and legacy polls.
    OUT_OF_BOUND,  //!< Marker value for the end of the valid range.
};

//!
//! \brief Describes the methods used to weigh votes for a poll.
//!
//! CONSENSUS: Do not remove or reorder items in this enumeration except for
//! OUT_OF_BOUND which must remain at the end.
//!
enum class PollWeightType
{
    UNKNOWN,               //!< An invalid, non-standard, or empty weight type.
    MAGNITUDE,             //!< Deprecated: Weight based on magnitude of a CPID.
    BALANCE,               //!< Weight based on unspent GRC of a voting wallet.
    BALANCE_AND_MAGNITUDE, //!< Weight based on both magnitude and balance.
    CPID_COUNT,            //!< Deprecated: each CPID receives the same weight.
    PARTICIPANT_COUNT,     //!< Deprecated: each vote receives the same weight.
    OUT_OF_BOUND,          //!< Marker value for the end of the valid range.
};

//!
//! \brief Describes the methods for choosing poll answers.
//!
//! CONSENSUS: Do not remove or reorder items in this enumeration except for
//! OUT_OF_BOUND which must remain at the end.
//!
enum class PollResponseType
{
    UNKNOWN,         //!< An invalid, non-standard, or empty response type.
    YES_NO_ABSTAIN,  //!< Standard yes/no/abstain single-choice answers only.
    SINGLE_CHOICE,   //!< All vote weight applied to one answer.
    MULTIPLE_CHOICE, //!< Vote weight split equally between each chosen answer.
    OUT_OF_BOUND,    //!< Marker value for the end of the valid range.
};

//!
//! \brief Thrown when constructing a poll or vote with invalid data.
//!
class VotingError : public std::runtime_error
{
public:
    explicit VotingError(const std::string& what) : std::runtime_error(what)
    {
    }
};

//!
//! \brief Get the title of the most recent poll.
//!
//! \return The first 80 characters of the most recent poll title.
//!
std::string GetCurrentPollTitle();
}


text:
package com.digdeep.util
package iglu
package client

import java.util.concurrent.TimeUnit

import com.fasterxml.jackson.databind.JsonNode
import com.google.common.cache.CacheBuilder
import com.snowplowanalytics.iglu.client._
import org.apache.commons.logging.LogFactory

import scalaz.{Success, Failure}
import collection.JavaConverters._

/**
 * Created by denismo on 5/10/15.
 */
class ErrorCachingResolver(cacheSize: Int = 500,
                           repos: RepositoryRefs, delegate: Resolver) extends Resolver(cacheSize, repos)
{
  val log = LogFactory.getLog(classOf[ErrorCachingResolver])

  val errorCache = CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).build[SchemaKey, ValidatedNel[JsonNode]]()
  def cacheError(schemaKey: SchemaKey, res: ValidatedNel[JsonNode]): ValidatedNel[JsonNode] = {
    errorCache.put(schemaKey, res)
    res
  }

  override def lookupSchema(schemaKey: SchemaKey): ValidatedNel[JsonNode] = {
    val stored = errorCache.getIfPresent(schemaKey)
    if (stored != null) {
      return stored
    }
    val res = delegate.lookupSchema(schemaKey)
    res match {
      case Failure(e) =>
        if (e.head.getMessage.startsWith("Could not find schema with key ")) {
          cacheError(schemaKey, res)
        } else {
          res
        }
      case Success(s) => res
    }
  }
}


text:
using System.Collections.Generic;
using System.Linq;
using System;
using EAAddinFramework.Utilities;
using TSF_EA =TSF.UmlToolingFramework.Wrappers.EA;
using UML = TSF.UmlToolingFramework.UML;
using System.Diagnostics;
using System.Xml;

namespace MagicdrawMigrator
{
	/// <summary>
	///Some parts of the Activity Diagrams are missing such as classifiers from partitions,
	/// </summary>
	public class AddClassifiersToPartitions:MagicDrawCorrector
	{
		public AddClassifiersToPartitions(MagicDrawReader magicDrawReader, TSF_EA.Model model, TSF_EA.Package mdPackage):base(magicDrawReader,model,mdPackage)
		{
		}

		public override void correct()
		{
				//Log start
				EAOutputLogger.log(this.model,this.outputName
	                   ,string.Format("{0} Starting add classifiers to partitions'"
	                                  ,DateTime.Now.ToLongTimeString())
	                   ,0
	                  ,LogTypeEnum.log);

				foreach(var mdPartition in magicDrawReader.allPartitions)
				{
					//key = partition, value = represents
					//partitionID: '_17_0_2_b9402f1_1366196749027_793557_54194'
					//representsID: '_17_0_2_3_38a017f_1374238063627_212930_92600'
					KeyValuePair<string,string> objectIdGuid = this.model.getObjectIdAndGuid(@"select o.[Object_ID], o.[ea_guid]
																							from t_object o
																			    			inner join [t_objectproperties] op
																			    			on o.[Object_ID] = op.[Object_ID]
																			    			where op.[Property] = 'md_guid'
																			    			and op.[value] = '"+ mdPartition.Value +"'");

					this.model.executeSQL(@"update t_object
											set [Classifier] = '" + objectIdGuid.Key + @"',
											[Classifier_guid] = '" + objectIdGuid.Value + @"'
											where Object_ID in
											(select o.[Object_ID]
											from t_object o
											inner join [t_objectproperties] op
											on o.[Object_ID] = op.[Object_ID]
											where op.[Property] = 'md_guid'
											and op.[value] = '"+ mdPartition.Key +"')");

				//logging
				EAOutputLogger.log(this.model,this.outputName
                   	,string.Format("{0} Add the classifier '{1}' - '{2}' for partition '{3}'"
                  	,DateTime.Now.ToLongTimeString()
                  	,objectIdGuid.Key
                  	,objectIdGuid.Value
                  	,mdPartition.Key)

       			,0
      			,LogTypeEnum.log);

				}

				EAOutputLogger.log(this.model,this.outputName
                   	,string.Format("{0} Finished add classifiers to partitions'"
                  	,DateTime.Now.ToLongTimeString())
       			,0
      			,LogTypeEnum.log);

		}
	}
}


text:
package projectgoldstarsx;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Photos
{
    public Photos()
    {
        photos();
    }

    public static ProgramWindow viewPhotosFrame;
    public static JTextField photosSearchField;

    private void photos()
    {
        viewPhotosFrame = new ProgramWindow("Photos");
        viewPhotosFrame.setSize(1100 * ProjectGoldStarsX.multiplier, 600 * ProjectGoldStarsX.multiplier);
        viewPhotosFrame.setJMenuBar(menuBar());
        ArrayList<String> files = new ArrayList<String>();
        for(int i = 0; i < ProjectGoldStarsX.photoNames.size(); i++)
        {
            files.add(ProjectGoldStarsX.photoNames.get(i));
        }
        JLabel[] fileLabels = new JLabel[files.size()];
        for(int i = 0; i < ProjectGoldStarsX.photoNames.size(); i++)
        {
            fileLabels[i] = new JLabel("Photo " + (i + 1), SwingConstants.CENTER);
            fileLabels[i].addMouseListener(new FileListener(files.get(i), true));
        }
        //If no photos have been saved to Project GoldStars X yet
        if(fileLabels.length == 0)
        {
            viewPhotosFrame.add(Components.titleLabel("You haven't saved any photos to Project GoldStars X yet!"));
        }
        else
        {
            for(int i = 0; i < fileLabels.length; i++)
            {
                viewPhotosFrame.setLayout(new GridLayout(((ProjectGoldStarsX.photoNames.size() - 1) / 3) + 1, 3));
                fileLabels[i].setFont(ProjectGoldStarsX.mediumText1);
                fileLabels[i].setForeground(ProjectGoldStarsX.secondaryColor);
                viewPhotosFrame.add(fileLabels[i]);
            }
        }
        viewPhotosFrame.makeVisible();
    }

    //Returns the JMenuBar that will be added to the ProgramWindow
    private JMenuBar menuBar()
    {
        JMenuBar menuBar = new JMenuBar();
        menuBar.setBackground(ProjectGoldStarsX.mainColor);
        menuBar.add(viewPhotosFrame.getCloseButton());
        menuBar.add(viewPhotosFrame.getMaximizeButton());
        menuBar.add(viewPhotosFrame.getWindowMenu());
        menuBar.add(new StandardButton("Import Photos", new ListenersPhotos.ImportPhotosListener()));
        menuBar.add(Components.settingsButton("Photos Settings", new ListenersPhotos.PhotosSettingsListener()));
        setupSearchField();
        menuBar.add(photosSearchField);
        menuBar.add(new StandardButton("Search", new SearchPhotosListener()));
        menuBar.add(moreMenu());
        return menuBar;
    }

    private JMenu moreMenu()
    {
        StandardMenu menu = new StandardMenu("More");
        menu.add(Components.standardMenuItem("About Photos", new ListenersPhotos.AboutPhotosListener()));
        return menu.getMenu();
    }

    private void setupSearchField()
    {
        photosSearchField = new JTextField();
        photosSearchField.setText("Search Photos");
        photosSearchField.setFont(ProjectGoldStarsX.bodyText2);
        if(ProjectGoldStarsX.standardColors)
        {
            photosSearchField.setForeground(ProjectGoldStarsX.secondaryColor);
        }
        else
        {
            photosSearchField.setForeground(ProjectGoldStarsX.mainColor);
        }
        photosSearchField.addActionListener(new SearchPhotosListener());
    }

    private class FileListener implements MouseListener
    {
        String toDisplay;
        boolean picture;

        public FileListener(String name, boolean photo)
        {
            toDisplay = name;
            picture = photo;
        }

        public void mousePressed(MouseEvent e)
        {
            //If the file clicked on was not a picture
            if(!picture)
            {
                JFrame viewNoteFrame = new JFrame("Notes");
                viewNoteFrame.setSize(750, 400);
                JTextArea viewNoteTextArea = new JTextArea(toDisplay);
                viewNoteTextArea.setEditable(false);
                viewNoteTextArea.setFont(ProjectGoldStarsX.bodyText2);
                viewNoteFrame.add(viewNoteTextArea);
                viewNoteFrame.setVisible(true);
            }
            //If the file clicked on was a picture
            else
            {
                JFrame photoFrame = new JFrame("Photos");
                photoFrame.setVisible(true);
                photoFrame.setSize(1000 * ProjectGoldStarsX.multiplier, 600 * ProjectGoldStarsX.multiplier);
                ImageIcon image = new ImageIcon(toDisplay);
                JLabel photo = new JLabel(image);
                photoFrame.add(photo);
            }
        }

        @Override
        public void mouseClicked(MouseEvent e)
        {

        }

        @Override
        public void mouseReleased(MouseEvent e)
        {

        }

        @Override
        public void mouseEntered(MouseEvent e)
        {

        }

        @Override
        public void mouseExited(MouseEvent e)
        {

        }
    }

    public static class SearchPhotosListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            new PhotosSearch(photosSearchField.getText());
            photosSearchField.setText("");
        }
    }
}


text:
// SPDX-License-Identifier: Apache-2.0

#include <cstddef>
#include <gtest/gtest.h>
#include <stumpless.h>
#include <thread>
#include "test/helper/assert.hpp"
#include "test/helper/usage.hpp"

namespace {
  const int THREAD_COUNT = 16;
  const int MESSAGE_COUNT = 100;

  TEST( WelWriteConsistency, SimultaneousWrites ) {
    struct stumpless_target *target;
    size_t i;
    std::thread *threads[THREAD_COUNT];

    // set up the target to log to
    target = stumpless_open_local_wel_target("wel-target-test" );
    EXPECT_NO_ERROR;
    ASSERT_NOT_NULL( target );

    for( i = 0; i < THREAD_COUNT; i++ ) {
      threads[i] = new std::thread( add_messages, target, MESSAGE_COUNT );
    }

    for( i = 0; i < THREAD_COUNT; i++ ) {
      threads[i]->join(  );
      delete threads[i];
    }

    // cleanup after the test
    stumpless_close_wel_target( target );
    EXPECT_NO_ERROR;

    stumpless_free_all(  );
  }
}


text:
const { stringify } = require('querystring');

class Candidates {
  constructor({ client, subdomain, shortcode, id }) {
    this.client = client;
    this.subdomain = subdomain;
    this.shortcode = shortcode;
    this.id = id;
  }
  info() {
    const { client, subdomain, shortcode, id } = this;
    const endpoint = `/${subdomain}/jobs/${shortcode}/candidates/${id}`;
    return client.get({ endpoint });
  }
  list(options = {}) {
    const { client, subdomain, shortcode } = this;
    const optionsQueryString = stringify(options);
    const queryString = optionsQueryString.length ? `?${optionsQueryString}` : '';
    const endpoint = `/${subdomain}/jobs/${shortcode}/candidates${queryString}`;
    return client.get({ endpoint });
  }
  async listAll(options = {}) {
    const { client } = this;
    Object.assign(options, { limit: 100 });
    const { candidates: firstCandidates, paging: firstPaging } = await this.list(options);
    let result = firstCandidates;
    let nextUrl = firstPaging && firstPaging.next;
    while (nextUrl) {
      // eslint-disable-next-line no-await-in-loop
      const { candidates, paging } = await client.get({ url: nextUrl });
      result = result.concat(candidates);
      nextUrl = paging && paging.next;
    }
    return { candidates: result };
  }
  create(candidate, stage) {
    const { client, subdomain, shortcode } = this;
    const stageQueryString = stringify({ stage });
    const queryString = stage ? `?${stageQueryString}` : '';
    const endpoint = `/${subdomain}/jobs/${shortcode}/candidates${queryString}`;
    return client.post({ endpoint, body: candidate });
  }
}

module.exports = Candidates;


text:
import * as S from "js.spec";

const spec: S.Spec = S.spec.bool;
const c: symbol = spec.conform("water");
const waterProblems: S.Problem[] = spec.explain("water");
const name: string = spec.name;
const options: object = spec.options;

const isValid: boolean = S.valid(S.spec.boolean, true);
S.valid((value) => true, "a value");

const result = S.conform(S.spec.map("dancing", {field: S.spec.string}), "not a map");
S.conform((value) => true, "a value");

const problems: S.Problem[] = S.explainData(S.spec.int, "not a number");
S.explainData((value) => true, "a value");

const {path, via, value, predicate}: {path: string[], via: string[], value: any, predicate: S.Predicate} = problems[0];

const problemStr: string = S.problemStr(problems[0]);

const explainStr: string = S.explainStr(S.spec.even, 3);
S.explainStr((value) => true, "a value");

// $ExpectType void
S.explain(S.spec.positive, true);
// $ExpectType void
S.explain((value) => true, "a value");

// $ExpectType void
S.assert(S.spec.string, "things");
// $ExpectType void
S.assert((value) => true, "a value");

const symbols: symbol[] = [S.symbol.count, S.symbol.invalid, S.symbol.maxCount, S.symbol.minCount, S.symbol.optional];

const orSpec: S.Spec = S.spec.or("or test", { ball: (value: any) => value === "whale", fish: S.spec.number });

const nilableSpec: S.Spec = S.spec.nilable("nilable test", (value: any) => false);

const collectionSpec: S.Spec = S.spec.collection("collection test", S.spec.positive);

const collection2Spec: S.Spec = S.spec.collection("collection test", S.spec.string, {[S.symbol.count]: 3});

const tupleSpec: S.Spec = S.spec.tuple("tuple test", S.spec.bool, S.spec.date, S.spec.array);

const mapSpec: S.Spec = S.spec.map("map test", { email: S.spec.string, [S.symbol.optional]: { name: S.spec.string } });

const oneOfSpec: S.Spec = S.spec.oneOf("oneOf test", "a", "b", "c");

const predicateSpec: S.Spec = S.spec.predicate("predicate test", (value) => true);

// Predicates

const intPred: S.Predicate = S.spec.int;

const integerPred: S.Predicate = S.spec.integer;

const finitePred: S.Predicate = S.spec.finite;

const numberPred: S.Predicate = S.spec.number;

const oddPred: S.Predicate = S.spec.odd;

const evenPred: S.Predicate = S.spec.even;

const positivePred: S.Predicate = S.spec.positive;

const negativePred: S.Predicate = S.spec.negative;

const zeroPred: S.Predicate = S.spec.zero;

const strPred: S.Predicate = S.spec.str;

const stringPred: S.Predicate = S.spec.string;

const fnPred: S.Predicate = S.spec.fn;

const symPred: S.Predicate = S.spec.sym;

const symbolPred: S.Predicate = S.spec.symbol;

const nilPred: S.Predicate = S.spec.nil;

const boolPred: S.Predicate = S.spec.bool;

const booleanPred: S.Predicate = S.spec.boolean;

const datePred: S.Predicate = S.spec.date;

const objPred: S.Predicate = S.spec.obj;

const objectPred: S.Predicate = S.spec.object;

const arrayPred: S.Predicate = S.spec.array;

const setPred: S.Predicate = S.spec.set;

const collPred: S.Predicate = S.spec.coll;


text:
import htmlmin # html minifier
import slimit # js minifier
import cssutils
import bs4
import urllib2
import urlparse
import wsgiref

class WSGIMiddleware:
	def __init__(self, app, memcache=None):
		self.app = app
		self.memcache = memcache

	def __call__(self, environ, start_response):
		if self.app.debug:
			return self.app(environ, start_response)
		content_type = ['application/octet-stream']
		def new_start_response(status, headers):
			for header, value in headers:
				if header == 'Content-Type':
					content_type[0] = value
			return start_response(status, headers)
		results = self.app(environ, new_start_response)
		content = "".join(results).decode('utf-8')
		base_url = wsgiref.util.request_uri(environ)
		m = Minifier(base_url)
		m.memcache = self.memcache
		return [m.minify(content, content_type[0]).encode('utf-8')]

class Minifier(object):
	memcache = None
	cache_time = 60 * 60
	def __init__(self, base_url=''):
		self.base_url = base_url

	def minify(self, _content, content_type):
		def _minify():
			content = _content
			if content_type.startswith('text/html'):
				soup = bs4.BeautifulSoup(content)
				self.inline_and_minify_js(soup)
				self.inline_and_minify_css(soup)
				content = unicode(soup)
				content = htmlmin.minify(content, remove_comments=True, remove_empty_space=True, remove_all_empty_space=True, reduce_empty_attributes=True, reduce_boolean_attributes=True)
			elif content_type.startswith('text/javascript'):
				content = self.minified_js(content)
			elif content_type.startswith('text/css'):
				content = self.minified_css(content)
			return content
		return self.cached((_content + content_type).encode('utf-8'), _minify)

	def inline_and_minify_js(self, soup):
		for script in soup.find_all('script'):
			minify_this = not script.has_attr('no-minify')
			if script.has_attr('src'):
				if script.has_attr('no-inline'): continue
				url = urlparse.urljoin(self.base_url, script['src'])
				script_src = self.fetch_url(url).decode('utf-8')
				if url.endswith('.min.js'):
					minify_this = False
				script.clear()
				script.append(soup.new_string(script_src))
				del script['src']
			if minify_this:
				script_contents = u"".join(script.strings)
				script.clear()
				script.append(soup.new_string(self.minified_js(script_contents)))

	def minified_js(self, js):
		def _minified():
			return slimit.minify(js, mangle=False)
		return self.cached(js.encode('utf-8'), _minified)

	def inline_and_minify_css(self, soup):
		for style in soup.find_all('style'):
			if style.has_attr('no-minify'): continue
			content = u"".join(style.strings)
			content = self.minified_css(content)
			style.clear()
			style.append(soup.new_string(content))
		for link in soup.find_all('link', rel='stylesheet'):
			if link.has_attr('href') and not link.has_attr('no-inline'):
				css = self.fetch_url(urlparse.urljoin(self.base_url, link['href'])).decode('utf-8')
				content = css if link.has_key('no-minify') else self.minified_css(css)
				style_tag = soup.new_tag('style')
				style_tag.append(soup.new_string(content))
				link.replace_with(style_tag)

	def minified_css(self, css):
		def _minified():
			href = self.base_url if self.base_url != '' else None
			sheet = cssutils.parseString(css, href=href)
			sheet = cssutils.resolveImports(sheet)
			cssutils.ser.prefs.useMinified()
			return sheet.cssText
		return self.cached(css.encode('utf-8'), _minified)

	def cached(self, key, func):
		result = self.memcache.get(key) if self.memcache else None
		if not result:
			result = func()
		if self.memcache:
			try:
				self.memcache.add(key, result, self.cache_time)
			except Exception:
				pass
		return result

	def fetch_url(self, url):
		def _fetch():
			return urllib2.urlopen(url).read()
		return self.cached(url, _fetch)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Nova Hedwigia 51: 349 (1975)

#### Original name
Lactarius glutigriseus V.L. Wells & Kempton

### Remarks
null


text:
import * as React from 'react';
import * as ReactDom from 'react-dom';
import {
  IPropertyPaneConfiguration,
  DynamicDataSharedDepth,
  PropertyPaneDynamicFieldSet,
  PropertyPaneDynamicField
} from '@microsoft/sp-property-pane';
import {
  BaseClientSideWebPart,
  IWebPartPropertiesMetadata,
} from '@microsoft/sp-webpart-base';

import * as strings from 'ListSearchConsumerWebPartWebPartStrings';
import { DynamicProperty } from '@microsoft/sp-component-base';
import { IListSearchConsumerProps } from './components/IListSearchConsumerProps';
import ListSearchConsumer from './components/ListSearchConsumerWebPart';

export interface IListSearchConsumerWebPartProps {
  webUrl: DynamicProperty<string>;
  listId: DynamicProperty<string>;
  itemId: DynamicProperty<number>;
}

export default class ListSearchConsumerWebPart extends BaseClientSideWebPart<IListSearchConsumerWebPartProps> {

  public render(): void {

    const element: React.ReactElement<IListSearchConsumerProps> = React.createElement(
      ListSearchConsumer,
      {
        webUrl: this.properties.webUrl.tryGetValue(),
        listId: this.properties.listId.tryGetValue(),
        itemId: this.properties.itemId.tryGetValue(),
      }
    );

    ReactDom.render(element, this.domElement);
  }

  protected onDispose(): void {
    ReactDom.unmountComponentAtNode(this.domElement);
  }

  protected get propertiesMetadata(): IWebPartPropertiesMetadata {
    return {
      // Specify the web part properties data type to allow the address
      // information to be serialized by the SharePoint Framework.
      'webUrl': {
        dynamicPropertyType: 'string'
      },
      'listId': {
        dynamicPropertyType: 'string'
      },
      'itemId': {
        dynamicPropertyType: 'number'
      }
    };
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneDynamicFieldSet({
                  label: 'Select web Url',
                  fields: [
                    PropertyPaneDynamicField('webUrl', {
                      label: 'Web Url'
                    }),
                    PropertyPaneDynamicField('listId', {
                      label: 'List Id'
                    }),
                    PropertyPaneDynamicField('itemId', {
                      label: 'Item Id'
                    })
                  ],
                  sharedConfiguration: {
                    depth: DynamicDataSharedDepth.Property
                  }
                })
              ]
            }
          ]
        }
      ]
    };
  }
}


text:
package org.apache.cloudstack.api.command.user.nat;

import java.util.List;

import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.BaseAsyncCreateCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.FirewallRuleResponse;
import org.apache.cloudstack.api.response.IPAddressResponse;
import org.apache.cloudstack.api.response.IpForwardingRuleResponse;
import org.apache.log4j.Logger;

import com.cloud.async.AsyncJob;
import com.cloud.event.EventTypes;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.IpAddress;
import com.cloud.network.rules.FirewallRule;
import com.cloud.network.rules.StaticNatRule;
import com.cloud.user.Account;
import com.cloud.user.UserContext;

@APICommand(name = "createIpForwardingRule", description="Creates an ip forwarding rule", responseObject=FirewallRuleResponse.class)
public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements StaticNatRule {
    public static final Logger s_logger = Logger.getLogger(CreateIpForwardingRuleCmd.class.getName());

    private static final String s_name = "createipforwardingruleresponse";

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////

    @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class,
            required=true, description="the public IP address id of the forwarding rule, already associated via associateIp")
    private Long ipAddressId;

    @Parameter(name=ApiConstants.START_PORT, type=CommandType.INTEGER, required=true, description="the start port for the rule")
    private Integer startPort;

    @Parameter(name=ApiConstants.END_PORT, type=CommandType.INTEGER, description="the end port for the rule")
    private Integer endPort;

    @Parameter(name=ApiConstants.PROTOCOL, type=CommandType.STRING, required=true, description="the protocol for the rule. Valid values are TCP or UDP.")
    private String protocol;

    @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. Has value true by default")
    private Boolean openFirewall;

    @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from")
    private List<String> cidrlist;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public Long getIpAddressId() {
        return ipAddressId;
    }

    public int getStartPort() {
        return startPort;
    }

    public int getEndPort() {
        return endPort;
    }

    public Boolean getOpenFirewall() {
        if (openFirewall != null) {
            return openFirewall;
        } else {
            return true;
        }
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public void execute() throws ResourceUnavailableException{

        boolean result = true;
        FirewallRule rule = null;
        try {
            UserContext.current().setEventDetails("Rule Id: "+ getEntityId());

            if (getOpenFirewall()) {
                result = result && _firewallService.applyIngressFirewallRules(ipAddressId, UserContext.current().getCaller());
            }

            result = result && _rulesService.applyStaticNatRules(ipAddressId, UserContext.current().getCaller());
            rule = _entityMgr.findById(FirewallRule.class, getEntityId());
            StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false);
            IpForwardingRuleResponse fwResponse = _responseGenerator.createIpForwardingRuleResponse(staticNatRule);
            fwResponse.setResponseName(getCommandName());
            this.setResponseObject(fwResponse);
        } finally {
            if (!result || rule == null) {

                if (getOpenFirewall()) {
                    _firewallService.revokeRelatedFirewallRule(getEntityId(), true);
                }

                _rulesService.revokeStaticNatRule(getEntityId(), true);

                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Error in creating ip forwarding rule on the domr");
            }
        }
    }

    @Override
    public void create() {

        //cidr list parameter is deprecated
        if (cidrlist != null) {
            throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command");
        }

        try {
            StaticNatRule rule = _rulesService.createStaticNatRule(this, getOpenFirewall());
            this.setEntityId(rule.getId());
            this.setEntityUuid(rule.getUuid());
        } catch (NetworkRuleConflictException e) {
            s_logger.info("Unable to create Static Nat Rule due to ", e);
            throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, e.getMessage());
        }
    }

    @Override
    public long getEntityOwnerId() {
        Account account = UserContext.current().getCaller();

        if (account != null) {
            return account.getId();
        }

        return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
    }

    @Override
    public String getEventType() {
        return EventTypes.EVENT_NET_RULE_ADD;
    }

    @Override
    public String getEventDescription() {
        IpAddress ip = _networkService.getIp(ipAddressId);
        return  ("Applying an ipforwarding 1:1 NAT rule for Ip: "+ip.getAddress()+" with virtual machine:"+ this.getVirtualMachineId());
    }

    private long getVirtualMachineId() {
        Long vmId = _networkService.getIp(ipAddressId).getAssociatedWithVmId();

        if (vmId == null) {
            throw new InvalidParameterValueException("Ip address is not associated with any network, unable to create static nat rule");
        }
        return vmId;
    }

    @Override
    public String getDestIpAddress(){
        return null;
    }

    @Override
    public long getId() {
        throw new UnsupportedOperationException("Don't call me");
    }

    @Override
    public Long getSourceIpAddressId() {
        return ipAddressId;
    }

    @Override
    public Integer getSourcePortStart() {
        return startPort;
    }

    @Override
    public Integer getSourcePortEnd() {
        if (endPort == null) {
            return startPort;
        } else {
            return endPort;
        }
    }

    @Override
    public String getProtocol() {
        return protocol;
    }

    @Override
    public FirewallRule.Purpose getPurpose() {
        return FirewallRule.Purpose.StaticNat;
    }

    @Override
    public FirewallRule.State getState() {
        throw new UnsupportedOperationException("Don't call me");
    }

    @Override
    public long getNetworkId() {
        return -1;
    }

    @Override
    public long getDomainId() {
        IpAddress ip = _networkService.getIp(ipAddressId);
        return ip.getDomainId();
    }

    @Override
    public long getAccountId() {
        IpAddress ip = _networkService.getIp(ipAddressId);
        return ip.getAccountId();
    }

    @Override
    public String getXid() {
        // FIXME: We should allow for end user to specify Xid.
        return null;
    }

    @Override
    public String getUuid() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String getSyncObjType() {
        return BaseAsyncCmd.networkSyncObject;
    }

    @Override
    public Long getSyncObjId() {
        return getIp().getAssociatedWithNetworkId();
    }

    private IpAddress getIp() {
        IpAddress ip = _networkService.getIp(ipAddressId);
        if (ip == null) {
            throw new InvalidParameterValueException("Unable to find ip address by id " + ipAddressId);
        }
        return ip;
    }

    @Override
    public Integer getIcmpCode() {
        return null;
    }

    @Override
    public Integer getIcmpType() {
        return null;
    }

    @Override
    public List<String> getSourceCidrList() {
        return null;
    }

    @Override
    public Long getRelated() {
        return null;
    }

    @Override
    public FirewallRuleType getType() {
        return FirewallRuleType.User;
    }

    @Override
    public AsyncJob.Type getInstanceType() {
        return AsyncJob.Type.FirewallRule;
    }

    @Override
    public TrafficType getTrafficType() {
        return null;
    }

}


text:
package com.appslandia.common.validators;

import java.util.Set;

import org.junit.Assert;
import org.junit.Test;

public class ValidValuesTest {

	@Test
	public void test() {
		TestModel m = new TestModel();
		Set<?> errors = ValidationContext.getValidator().validate(m);
		Assert.assertTrue(errors.isEmpty());

		m.gender = 1;
		errors = ValidationContext.getValidator().validate(m);
		Assert.assertTrue(errors.isEmpty());

		m.gender = 2;
		errors = ValidationContext.getValidator().validate(m);
		Assert.assertTrue(errors.isEmpty());

		m.gender = 3;
		errors = ValidationContext.getValidator().validate(m);
		Assert.assertTrue(errors.isEmpty() == false);
	}

	public static class TestModel {

		@ValidValues({ 1, 2 })
		public Integer gender;
	}
}


text:
<?php
return array (
  'Created at' => 'Créé à',
  'Created by' => 'Créé par',
  'Description' => 'Description',
  'Editable' => 'Modifiable',
  'Field Type could not be changed!' => 'Le type du champ ne peut être modifié !',
  'Fieldtype' => 'Type de champ',
  'ID' => 'ID',
  'Internal Name' => 'Nom interne',
  'Internal name already in use!' => 'Ce nom interne est déjà utilisé !',
  'Internal name could not be changed!' => 'Le nom interne ne peut être modifié !',
  'Invalid field type!' => 'Type de champ invalide !',
  'LDAP Attribute' => 'Attributs LDAP',
  'Module' => 'Module',
  'Only alphanumeric characters allowed!' => 'Seuls les caractères alphanumériques sont acceptés !',
  'Profile Field Category' => 'Catégorie de champs',
  'Required' => 'Requis',
  'Searchable' => 'Interrogeable dans la recherche',
  'Show at registration' => 'Voir à l\'enregistrement',
  'Sort order' => 'Ordre de tri',
  'Title' => 'Titre',
  'Translation Category ID' => 'Identifiant de traduction de la catégorie',
  'Type Config' => 'Configuration de type',
  'Updated at' => 'Mis à jour à',
  'Updated by' => 'Mis à jour par',
  'Visible' => 'Visible',
);


text:
package org.sakaiproject.antivirus.api;

/**
 * Created by IntelliJ IDEA.
 * User: jbush
 * Date: Sep 6, 2006
 * Time: 10:17:23 AM
 * To change this template use File | Settings | File Templates.
 */
public class VirusFoundException extends RuntimeException {
   private String virusName = "unknown";

   public VirusFoundException(String message) {
      super(message);
   }

   public String getVirusName() {
      return virusName;
   }

   public void setVirusName(String virusName) {
      this.virusName = virusName;
   }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cosmos.IL2CPU;

namespace DebugCompiler
{
    public class TestCompilerExtension: CompilerExtensionBase
    {
        public override bool TryCreateAppAssembler(byte debugCom, string assemblerLog, out AppAssembler result)
        {
            return base.TryCreateAppAssembler(debugCom, assemblerLog, out result);
        }
    }
}


text:
title: Sonja van de Ven - Smits
slug: sonja-van-de-ven---smits
category: authors
date: 2017-08-10
Template: staff_page
route: 767
room_nr: 40
phone_nr: +31 24 3619061
email: sonja.vandeven-smits@radboudumc.nl
google_scholar_code:
researcher_id:
linkedin_url: /pub/sonja-van-de-ven/23/b27/680
website_lit_search_name:
group_member: Administrative Staff,,Administrative Staff,,,,

Sonja van de Ven finished her secretary education in 1982 and started working at Splendor Gloeilampenfabrieken B.V as secretary at the expedition section. One year later she changed jobs and became secretary to the export manager at the same firm and expanded her knowledge of languages. After three years she was asked for the job of Management Secretary of the board of directors, which job she fulfilled for 6 years with lots of pleasure. After an interruption of 6 years she started working in 1998 as a parttime secretary at the Clinical Physics Laboratory, Paediatrics of the UMC St Radboud, which from 01.01.2012 moved to the department of Radiology as the Medical UltraSound Imaging Centre.