text:
package com.opengamma.engine.marketdata.historical;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Set;

import org.apache.commons.lang.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.LocalDate;

import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesAdjustment;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesResolutionResult;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesResolver;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeriesSource;
import com.opengamma.core.value.MarketDataRequirementNames;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.marketdata.AbstractMarketDataProvider;
import com.opengamma.engine.marketdata.MarketDataPermissionProvider;
import com.opengamma.engine.marketdata.PermissiveMarketDataPermissionProvider;
import com.opengamma.engine.marketdata.availability.AbstractMarketDataAvailabilityProvider;
import com.opengamma.engine.marketdata.availability.MarketDataAvailabilityProvider;
import com.opengamma.engine.marketdata.spec.HistoricalMarketDataSpecification;
import com.opengamma.engine.marketdata.spec.MarketDataSpecification;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.UniqueId;
import com.opengamma.util.ArgumentChecker;

/**
 * Market data provider that sources data from historical time-series.
 */
public abstract class AbstractHistoricalMarketDataProvider extends AbstractMarketDataProvider {

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

  /**
   * The property put onto the value specifications created.
   */
  protected static final String NORMALIZATION_PROPERTY = "Normalization";

  private final HistoricalTimeSeriesSource _historicalTimeSeriesSource;
  private final HistoricalTimeSeriesResolver _historicalTimeSeriesResolver;
  private final String _timeSeriesResolverKey;
  private final MarketDataPermissionProvider _permissionProvider;

  /**
   * Creates a new market data provider.
   *
   * @param historicalTimeSeriesSource the underlying source of historical data, not null
   * @param historicalTimeSeriesResolver the resolver to identifier historical data, not null
   * @param timeSeriesResolverKey the source resolver key, or null to use the source default
   */
  public AbstractHistoricalMarketDataProvider(final HistoricalTimeSeriesSource historicalTimeSeriesSource,
      final HistoricalTimeSeriesResolver historicalTimeSeriesResolver,
      final String timeSeriesResolverKey) {
    ArgumentChecker.notNull(historicalTimeSeriesSource, "historicalTimeSeriesSource");
    ArgumentChecker.notNull(historicalTimeSeriesResolver, "historicalTimeSeriesResolver");
    _historicalTimeSeriesSource = historicalTimeSeriesSource;
    _historicalTimeSeriesResolver = historicalTimeSeriesResolver;
    _timeSeriesResolverKey = timeSeriesResolverKey;
    _permissionProvider = new PermissiveMarketDataPermissionProvider();
  }

  public AbstractHistoricalMarketDataProvider(final HistoricalTimeSeriesSource historicalTimeSeriesSource,
      final HistoricalTimeSeriesResolver historicalTimeSeriesResolver) {
    this(historicalTimeSeriesSource, historicalTimeSeriesResolver, null);
  }

  @Override
  public void subscribe(final ValueSpecification valueSpecification) {
    LOGGER.debug("Added subscriptions to {}", valueSpecification);
    subscriptionSucceeded(valueSpecification);
  }

  @Override
  public void subscribe(final Set<ValueSpecification> valueSpecifications) {
    LOGGER.debug("Added subscriptions to {}", valueSpecifications);
    subscriptionsSucceeded(valueSpecifications);
  }

  @Override
  public void unsubscribe(final ValueSpecification valueSpecification) {
    LOGGER.debug("Removed subscription from {}", valueSpecification);
  }

  @Override
  public void unsubscribe(final Set<ValueSpecification> valueSpecifications) {
    LOGGER.debug("Removed subscriptions from {}", valueSpecifications);
  }

  protected abstract LocalDate getHistoricalResolutionDate(MarketDataSpecification marketDataSpec);

  @Override
  public MarketDataAvailabilityProvider getAvailabilityProvider(final MarketDataSpecification marketDataSpec) {
    final LocalDate date = getHistoricalResolutionDate(marketDataSpec);
    return new AbstractMarketDataAvailabilityProvider() {

      @Override
      protected ValueSpecification getAvailability(final ComputationTargetSpecification targetSpec, final ExternalId identifier,
          final ValueRequirement desiredValue) {
        return getAvailability(targetSpec, identifier.toBundle(), desiredValue);
      }

      @Override
      protected ValueSpecification getAvailability(final ComputationTargetSpecification targetSpec, final ExternalIdBundle identifiers,
          final ValueRequirement desiredValue) {
        final HistoricalTimeSeriesResolutionResult resolved =
            getTimeSeriesResolver().resolve(identifiers, date, null, null, desiredValue.getValueName(), getTimeSeriesResolverKey());
        if (resolved == null) {
          if (LOGGER.isDebugEnabled() && desiredValue.getValueName().equals(MarketDataRequirementNames.MARKET_VALUE)) {
            LOGGER.debug("Missing market data {}", desiredValue);
          }
          return null;
        }
        final ValueProperties.Builder properties = ValueProperties.with(ValuePropertyNames.FUNCTION, getSyntheticFunctionName());
        if (resolved.getAdjuster() != null) {
          final ExternalIdBundle resolvedIdentifiers = resolved.getHistoricalTimeSeriesInfo().getExternalIdBundle().toBundle(date);
          final HistoricalTimeSeriesAdjustment adjustment = resolved.getAdjuster().getAdjustment(resolvedIdentifiers);
          properties.with(NORMALIZATION_PROPERTY, adjustment.toString());
        }
        return new ValueSpecification(desiredValue.getValueName(),
            ComputationTargetSpecification.of(resolved.getHistoricalTimeSeriesInfo().getUniqueId()), properties.get());
      }

      @Override
      protected ValueSpecification getAvailability(final ComputationTargetSpecification targetSpec, final UniqueId identifier,
          final ValueRequirement desiredValue) {
        return null;
      }

      @Override
      protected ValueSpecification getAvailability(final ComputationTargetSpecification targetSpec, final ValueRequirement desiredValue) {
        return null;
      }

      @Override
      public Serializable getAvailabilityHintKey() {
        final ArrayList<Serializable> key = new ArrayList<>(3);
        key.add(AbstractHistoricalMarketDataProvider.this.getClass().getName());
        key.add(date);
        key.add(getTimeSeriesResolverKey());
        return key;
      }

    };
  }

  @Override
  public MarketDataPermissionProvider getPermissionProvider() {
    return _permissionProvider;
  }

  //-------------------------------------------------------------------------
  @Override
  public boolean isCompatible(final MarketDataSpecification marketDataSpec) {
    if (!(marketDataSpec instanceof HistoricalMarketDataSpecification)) {
      return false;
    }
    final HistoricalMarketDataSpecification historicalSpec = (HistoricalMarketDataSpecification) marketDataSpec;
    return ObjectUtils.equals(getTimeSeriesResolverKey(), historicalSpec.getTimeSeriesResolverKey());
  }

  protected HistoricalTimeSeriesSource getTimeSeriesSource() {
    return _historicalTimeSeriesSource;
  }

  protected HistoricalTimeSeriesResolver getTimeSeriesResolver() {
    return _historicalTimeSeriesResolver;
  }

  protected String getTimeSeriesResolverKey() {
    return _timeSeriesResolverKey;
  }

  /**
   * The function name used in value specifications describing items sourced by this provider. This is only used for
   * diagnostics when browsing the dependency graph.
   *
   * @return the function name
   */
  protected String getSyntheticFunctionName() {
    return getClass().getSimpleName();
  }

}


text:
package org.ioicompanies.lang.iOI;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'Employee'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link org.ioicompanies.lang.iOI.Employee#getName Name}

 *
{@link org.ioicompanies.lang.iOI.Employee#getSalary Salary}

 *
{@link org.ioicompanies.lang.iOI.Employee#getWorks_on Works on}

 *

 *

 *
 * @see org.ioicompanies.lang.iOI.IOIPackage#getEmployee()
 * @model
 * @generated
 */
public interface Employee extends EObject
{
  /**
   * Returns the value of the 'Name' attribute.
   *
   *

   * If the meaning of the 'Name' attribute isn't clear,
   * there really should be more of a description here...
   *

   *
   * @return the value of the 'Name' attribute.
   * @see #setName(String)
   * @see org.ioicompanies.lang.iOI.IOIPackage#getEmployee_Name()
   * @model
   * @generated
   */
  String getName();

  /**
   * Sets the value of the '{@link org.ioicompanies.lang.iOI.Employee#getName Name}' attribute.
   *
   *
   * @param value the new value of the 'Name' attribute.
   * @see #getName()
   * @generated
   */
  void setName(String value);

  /**
   * Returns the value of the 'Salary' attribute.
   *
   *

   * If the meaning of the 'Salary' attribute isn't clear,
   * there really should be more of a description here...
   *

   *
   * @return the value of the 'Salary' attribute.
   * @see #setSalary(int)
   * @see org.ioicompanies.lang.iOI.IOIPackage#getEmployee_Salary()
   * @model
   * @generated
   */
  int getSalary();

  /**
   * Sets the value of the '{@link org.ioicompanies.lang.iOI.Employee#getSalary Salary}' attribute.
   *
   *
   * @param value the new value of the 'Salary' attribute.
   * @see #getSalary()
   * @generated
   */
  void setSalary(int value);

  /**
   * Returns the value of the 'Works on' reference.
   *
   *

   * If the meaning of the 'Works on' reference isn't clear,
   * there really should be more of a description here...
   *

   *
   * @return the value of the 'Works on' reference.
   * @see #setWorks_on(Position)
   * @see org.ioicompanies.lang.iOI.IOIPackage#getEmployee_Works_on()
   * @model
   * @generated
   */
  Position getWorks_on();

  /**
   * Sets the value of the '{@link org.ioicompanies.lang.iOI.Employee#getWorks_on Works on}' reference.
   *
   *
   * @param value the new value of the 'Works on' reference.
   * @see #getWorks_on()
   * @generated
   */
  void setWorks_on(Position value);

} // Employee

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Greg\Orm\Clause;

use Greg\Orm\Conditions;

interface JoinClauseStrategy
{
    /**
     * @param $table
     * @param string|null $on
     * @param string[]    ...$params
     *
     * @return $this
     */
    public function leftJoin($table, string $on = null, string ...$params);

    /**
     * @param $table
     * @param callable|Conditions $on
     *
     * @return $this
     */
    public function leftJoinOn($table, $on);

    /**
     * @param $table
     * @param string|null $on
     * @param string[]    ...$params
     *
     * @return $this
     */
    public function rightJoin($table, string $on = null, string ...$params);

    /**
     * @param $table
     * @param callable|Conditions $on
     *
     * @return $this
     */
    public function rightJoinOn($table, $on);

    /**
     * @param $table
     * @param string|null $on
     * @param string[]    ...$params
     *
     * @return $this
     */
    public function innerJoin($table, string $on = null, string ...$params);

    /**
     * @param $table
     * @param callable|Conditions $on
     *
     * @return $this
     */
    public function innerJoinOn($table, $on);

    /**
     * @param $table
     *
     * @return $this
     */
    public function crossJoin($table);

    /**
     * @param $source
     * @param $table
     * @param string|null $on
     * @param string[]    ...$params
     *
     * @return $this
     */
    public function leftJoinTo($source, $table, string $on = null, string ...$params);

    /**
     * @param $source
     * @param $table
     * @param callable|Conditions $on
     *
     * @return $this
     */
    public function leftJoinOnTo($source, $table, $on);

    /**
     * @param $source
     * @param $table
     * @param string|null $on
     * @param string[]    ...$params
     *
     * @return $this
     */
    public function rightJoinTo($source, $table, string $on = null, string ...$params);

    /**
     * @param $source
     * @param $table
     * @param callable|Conditions $on
     *
     * @return $this
     */
    public function rightJoinOnTo($source, $table, $on);

    /**
     * @param $source
     * @param $table
     * @param string|null $on
     * @param string[]    ...$params
     *
     * @return $this
     */
    public function innerJoinTo($source, $table, string $on = null, string ...$params);

    /**
     * @param $source
     * @param $table
     * @param callable|Conditions $on
     *
     * @return $this
     */
    public function innerJoinOnTo($source, $table, $on);

    /**
     * @param $source
     * @param $table
     *
     * @return $this
     */
    public function crossJoinTo($source, $table);

    /**
     * @param string      $tableKey
     * @param string      $type
     * @param null|string $source
     * @param $table
     * @param null|string $alias
     * @param $on
     * @param array $params
     *
     * @return $this
     */
    public function addJoin(string $tableKey, string $type, ?string $source, $table, ?string $alias, $on = null, array $params = []);

    /**
     * @return string
     */
    public function hasJoin();

    /**
     * @return array
     */
    public function getJoin();

    /**
     * @return $this
     */
    public function clearJoin();

    public function joinToSql(string $source = null): array;

    public function joinToString(string $source = null): string;
}


text:
			<input type="text" data-id="hostName" class="form-control"
				placeholder="Search Hosts">
				<button class="btn btn-info btn-search" data-id="searchHost" type="button">

				</button>

			 <input id="mainCheck" checked ="checked" type="checkbox"> Select / Deselect All


text:
<?php

namespace Phuria\Pipolino;

/**
 * @author Beniamin Jonatan Šimko <contact@simko.it>
 */
class Pipolino
{
    /**
     * @var array
     */
    private $stages;

    /**
     * @var callable
     */
    private $defaultStage;

    /**
     * @param array    $stages
     * @param callable $defaultStage
     *
     * @throws InvalidStageException
     */
    public function __construct(array $stages = [], callable $defaultStage = null)
    {
        foreach ($stages as $stage) {
            if (false === is_callable($stage)) {
                throw InvalidStageException::create($stage);
            }
        }

        $this->stages = $stages;
        $this->defaultStage = $defaultStage ?: new DefaultStage();
    }

    /**
     * @param callable $next
     * @param array    ...$args
     *
     * @return mixed
     */
    public function __invoke(callable $next, ...$args)
    {
        return $this->process(...$args);
    }

    /**
     * @param array ...$args
     *
     * @return mixed
     */
    public function process(...$args)
    {
        if (0 === count($this->stages)) {
            return call_user_func($this->defaultStage, ...$args);
        }

        $stages = $this->stages;
        $currentStage = array_shift($stages);

        $next = function (...$args) use ($stages) {
            return (new Pipolino($stages, $this->defaultStage))->process(...$args);
        };

        return call_user_func($currentStage, $next, ...$args);
    }

    /**
     * @param callable $stage
     *
     * @return Pipolino
     */
    public function addStage(callable $stage)
    {
        $stages = $this->stages;
        $stages[] = $stage;

        return new self($stages, $this->defaultStage);
    }

    /**
     * @param callable $stage
     *
     * @return Pipolino
     */
    public function withDefaultStage(callable $stage)
    {
        return new self($this->stages, $stage);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
All Classes
</TITLE>

<META NAME="date" CONTENT="2010-02-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

ActivitiesService

Activity

Album

AlbumsService

AppData

AppDataService

AuthScheme

Client

Comment

FCAuthScheme

FriendConnectProvider

GoogleProvider

Group

GroupsService

Hi5Provider

HttpClient

HttpResponseMessage

JsonParser

MediaItem

MediaItemsService

Model

MySpaceProvider

Notification

NotificationsService

OAuth2LeggedScheme

OAuth3LeggedScheme

OAuth3LeggedScheme.Token

OrkutProvider

OrkutSandboxProvider

Parser

PartuzaProvider

PeopleService

Person

PlaxoProvider

ProfileCommentsService

Provider

Request

RequestException

Response

SecurityTokenScheme

Service

ShindigProvider

StatusMood

StatusMoodsService

YahooProvider


text:
using System;
using System.Reflection;

namespace SolutionInspector.Api.ObjectModel
{
  /// <summary>
  ///   Represents a DLL reference via NuGet.
  /// </summary>
  public interface INuGetReference : IDllReference
  {
    /// <summary>
    ///   The NuGet package that created the reference.
    /// </summary>
    INuGetPackage Package { get; }

    /// <summary>
    ///   <c>True</c> if the reference is private, <c>false</c> otherwise.
    /// </summary>
    bool IsPrivate { get; }
  }

  internal class NuGetReference : DllReferenceBase, INuGetReference
  {
    public INuGetPackage Package { get; }

    public bool IsPrivate { get; }

    public NuGetReference (INuGetPackage package, AssemblyName assemblyName, bool isPrivate, string hintPath, string projectDirectory)
        : base(assemblyName, projectDirectory, hintPath)
    {
      Package = package;
      IsPrivate = isPrivate;
    }
  }
}


text:
package org.gradoop.flink.algorithms.fsm.dimspan.comparison;

import org.gradoop.flink.model.impl.tuples.WithCount;

/**
 * Frequency-based label comparator where higher frequency is smaller.
 */
public class InverseProportionalLabelComparator implements LabelComparator {

  @Override
  public int compare(WithCount<String> a, WithCount<String> b) {
    int comparison;

    if (a.getCount() > b.getCount()) {
      comparison = -1;
    } else if (a.getCount() < b.getCount()) {
      comparison = 1;
    } else {
      comparison = a.getObject().compareTo(b.getObject());
    }

    return comparison;
  }
}


text:
namespace cc {

scoped_refptr<PicturePileImpl> PicturePileImpl::Create() {
  return make_scoped_refptr(new PicturePileImpl());
}

PicturePileImpl::PicturePileImpl()
    : slow_down_raster_scale_factor_for_debug_(0) {
}

PicturePileImpl::~PicturePileImpl() {
}

PicturePileImpl* PicturePileImpl::GetCloneForDrawingOnThread(
    base::Thread* thread) {
  // Do we have a clone for this thread yet?
  CloneMap::iterator it = clones_.find(thread->thread_id());
  if (it != clones_.end())
    return it->second;

  // Create clone for this thread.
  scoped_refptr<PicturePileImpl> clone = CloneForDrawing();
  clones_[thread->thread_id()] = clone;
  return clone;
}

scoped_refptr<PicturePileImpl> PicturePileImpl::CloneForDrawing() const {
  TRACE_EVENT0("cc", "PicturePileImpl::CloneForDrawing");
  scoped_refptr<PicturePileImpl> clone = Create();
  clone->tiling_ = tiling_;
  for (PictureListMap::const_iterator map_iter = picture_list_map_.begin();
       map_iter != picture_list_map_.end(); ++map_iter) {
    const PictureList& this_pic_list = map_iter->second;
    PictureList& clone_pic_list = clone->picture_list_map_[map_iter->first];
    for (PictureList::const_iterator pic_iter = this_pic_list.begin();
         pic_iter != this_pic_list.end(); ++pic_iter) {
      clone_pic_list.push_back((*pic_iter)->Clone());
    }
  }
  clone->min_contents_scale_ = min_contents_scale_;
  clone->set_slow_down_raster_scale_factor(
      slow_down_raster_scale_factor_for_debug_);

  return clone;
}

void PicturePileImpl::Raster(
    SkCanvas* canvas,
    gfx::Rect content_rect,
    float contents_scale,
    int64* total_pixels_rasterized) {

  DCHECK(contents_scale >= min_contents_scale_);

#ifndef NDEBUG
  // Any non-painted areas will be left in this color.
  canvas->clear(DebugColors::NonPaintedFillColor());
#endif  // NDEBUG

  canvas->save();
  canvas->translate(-content_rect.x(), -content_rect.y());
  canvas->clipRect(gfx::RectToSkRect(content_rect));

  gfx::Rect layer_rect = gfx::ToEnclosingRect(
      gfx::ScaleRect(content_rect, 1.f / contents_scale));

  Region unclipped(content_rect);
  for (TilingData::Iterator tile_iter(&tiling_, layer_rect);
       tile_iter; ++tile_iter) {
    PictureListMap::iterator map_iter =
        picture_list_map_.find(tile_iter.index());
    if (map_iter == picture_list_map_.end())
      continue;
    PictureList& pic_list= map_iter->second;
    if (pic_list.empty())
      continue;

    // Raster through the picture list top down, using clips to make sure that
    // pictures on top are not overdrawn by pictures on the bottom.
    for (PictureList::reverse_iterator i = pic_list.rbegin();
         i != pic_list.rend(); ++i) {
      // This is intentionally *enclosed* rect, so that the clip is aligned on
      // integral post-scale content pixels and does not extend past the edges
      // of the picture's layer rect.  The min_contents_scale enforces that
      // enough buffer pixels have been added such that the enclosed rect
      // encompasses all invalidated pixels at any larger scale level.
      gfx::Rect content_clip = gfx::ToEnclosedRect(
          gfx::ScaleRect((*i)->LayerRect(), contents_scale));
      if (!unclipped.Intersects(content_clip))
        continue;

      if (slow_down_raster_scale_factor_for_debug_) {
        for (int j = 0; j < slow_down_raster_scale_factor_for_debug_; ++j)
          (*i)->Raster(canvas, content_clip, contents_scale);
      } else {
        (*i)->Raster(canvas, content_clip, contents_scale);
      }

      // Don't allow pictures underneath to draw where this picture did.
      canvas->clipRect(
          gfx::RectToSkRect(content_clip),
          SkRegion::kDifference_Op);
      unclipped.Subtract(content_clip);

      total_pixels_rasterized +=
          content_clip.width() * content_clip.height();
    }
  }

#ifndef NDEBUG
  // Fill the remaining clip with debug color. This allows us to
  // distinguish between non painted areas and problems with missing
  // pictures.
  SkPaint paint;
  paint.setColor(DebugColors::MissingPictureFillColor());
  paint.setXfermodeMode(SkXfermode::kSrc_Mode);
  canvas->drawPaint(paint);
#endif  // NDEBUG

  // We should always paint some part of |content_rect|.
  DCHECK(!unclipped.Contains(content_rect));

  canvas->restore();
}

void PicturePileImpl::GatherPixelRefs(
    gfx::Rect content_rect,
    float contents_scale,
    std::list<skia::LazyPixelRef*>& pixel_refs) {
  std::list<skia::LazyPixelRef*> result;

  gfx::Rect layer_rect = gfx::ToEnclosingRect(
      gfx::ScaleRect(content_rect, 1.f / contents_scale));

  for (TilingData::Iterator tile_iter(&tiling_, layer_rect);
       tile_iter; ++tile_iter) {
    PictureListMap::iterator map_iter =
        picture_list_map_.find(tile_iter.index());
    if (map_iter == picture_list_map_.end())
      continue;

    PictureList& pic_list = map_iter->second;
    for (PictureList::const_iterator i = pic_list.begin();
         i != pic_list.end(); ++i) {
      (*i)->GatherPixelRefs(layer_rect, result);
      pixel_refs.splice(pixel_refs.end(), result);
    }
  }
}

void PicturePileImpl::PushPropertiesTo(PicturePileImpl* other) {
  PicturePileBase::PushPropertiesTo(other);
  other->clones_ = clones_;
}

skia::RefPtr<SkPicture> PicturePileImpl::GetFlattenedPicture() {
  TRACE_EVENT0("cc", "PicturePileImpl::GetFlattenedPicture");

  gfx::Rect layer_rect(tiling_.total_size());
  skia::RefPtr<SkPicture> picture = skia::AdoptRef(new SkPicture);
  if (layer_rect.IsEmpty())
    return picture;

  SkCanvas* canvas = picture->beginRecording(
      layer_rect.width(),
      layer_rect.height(),
      SkPicture::kUsePathBoundsForClip_RecordingFlag);

  int64 total_pixels_rasterized = 0;
  Raster(canvas, layer_rect, 1.0, &total_pixels_rasterized);
  picture->endRecording();

  return picture;
}

bool PicturePileImpl::IsCheapInRect(
    gfx::Rect content_rect, float contents_scale) const {
  gfx::Rect layer_rect = gfx::ToEnclosingRect(
      gfx::ScaleRect(content_rect, 1.f / contents_scale));

  for (TilingData::Iterator tile_iter(&tiling_, layer_rect);
       tile_iter; ++tile_iter) {
    PictureListMap::const_iterator map_iter =
        picture_list_map_.find(tile_iter.index());
    if (map_iter == picture_list_map_.end())
      continue;

    const PictureList& pic_list = map_iter->second;
    for (PictureList::const_iterator i = pic_list.begin();
         i != pic_list.end(); ++i) {
      if (!(*i)->LayerRect().Intersects(layer_rect) || !(*i)->HasRecording())
        continue;
      if (!(*i)->IsCheapInRect(layer_rect))
        return false;
    }
  }
  return true;
}

}  // namespace cc


text:
class AddPerAssessmentLatePenalty < ActiveRecord::Migration
  def self.up
    add_column :assessments, :late_penalty, :float
  end

  def self.down
    remove_column :assessments, :late_penalty
  end
end


text:
namespace Microsoft.DocAsCode.MarkdigEngine.Extensions
{
    using System;
    using Markdig.Syntax;

    public class MarkdownContext
    {
        /// <summary>
        /// Logs an error or warning message.
        /// </summary>
        public delegate void LogActionDelegate(string code, string message, MarkdownObject origin, int? line = null);

        /// <summary>
        /// Reads a file as text based on path relative to an existing file.
        /// </summary>
        /// <param name="path">Path to the file being opened.</param>
        /// <param name="origin">The original markdown element that triggered the read request.</param>
        /// <returns>An stream and the opened file, or default if such file does not exists.</returns>
        public delegate (string content, object file) ReadFileDelegate(string path, MarkdownObject origin);

        /// <summary>
        /// Allows late binding of urls.
        /// </summary>
        /// <param name="path">Path of the link</param>
        /// <param name="origin">The original markdown element that triggered the read request.</param>
        /// <returns>Url bound to the path</returns>
        public delegate string GetLinkDelegate(string path, MarkdownObject origin);

        /// <summary>
        /// Allows late binding of image urls.
        /// </summary>
        /// <param name="path">Path of the link</param>
        /// <param name="origin">The original markdown element that triggered the read request.</param>
        /// <returns>Image url bound to the path</returns>
        public delegate string GetImageLinkDelegate(string path, MarkdownObject origin, string altText);

        /// <summary>
        /// Reads a file as text.
        /// </summary>
        public ReadFileDelegate ReadFile { get; }

        /// <summary>
        /// Get the link for a given url.
        /// </summary>
        public GetLinkDelegate GetLink { get; }

        /// <summary>
        /// Get the image link for a given image url
        /// </summary>
        public GetImageLinkDelegate GetImageLink { get; }

        /// <summary>
        /// Log info
        /// </summary>
        public LogActionDelegate LogInfo{ get; }

        /// <summary>
        /// Log suggestion
        /// </summary>
        public LogActionDelegate LogSuggestion { get; }

        /// <summary>
        /// Log warning
        /// </summary>
        public LogActionDelegate LogWarning { get; }

        /// <summary>
        /// Log error
        /// </summary>
        public LogActionDelegate LogError { get; }

        /// <summary>
        /// Gets the localizable text tokens used for rendering notes.
        /// </summary>
        public string GetToken(string key) => _getToken(key);

        private readonly Func<string, string> _getToken;

        public MarkdownContext(
            Func<string, string> getToken = null,
            LogActionDelegate logInfo = null,
            LogActionDelegate logSuggestion = null,
            LogActionDelegate logWarning = null,
            LogActionDelegate logError = null,
            ReadFileDelegate readFile = null,
            GetLinkDelegate getLink = null,
            GetImageLinkDelegate getImageLink = null)
        {
            _getToken = getToken ?? (_ => null);
            ReadFile = readFile ?? ((a, b) => (a, a));
            GetLink = getLink ?? ((a, b) => a);
            GetImageLink = getImageLink ?? ((a, b, c) => a);
            LogInfo = logInfo ?? ((a, b, c, d) => { });
            LogSuggestion = logSuggestion ?? ((a, b, c, d) => { });
            LogWarning = logWarning ?? ((a, b, c, d) => { });
            LogError = logError ?? ((a, b, c, d) => { });
        }
    }
}


text:
#ifndef __AVR_LCD_PROJECT_ENGINE_ALARM_H__
#define __AVR_LCD_PROJECT_ENGINE_ALARM_H__

#include "types.h"

/**
 * Initialize the Alarm engine state
 */
void engine_state_alarm_init (void);
#ifndef M_NO_DEINIT
/**
 * Deinitialize the Alarm engine state
 */
void engine_state_alarm_deinit (void);
#endif /* !M_NO_DEINIT */

#endif /* __AVR_LCD_PROJECT_ENGINE_ALARM_H__ */


text:
namespace TankLib.STU.Types
{
    [STU(0x39B590A9, 32)]
    public class STURayCastReceiver : STUInstance
    {
        [STUField(0x6228373E, 8, ReaderType = typeof(InlineInstanceFieldReader))] // size: 16
        public STURayCastReceiverOverride[] m_6228373E;

        [STUField(0xDC35ABD3, 24, ReaderType = typeof(InlineInstanceFieldReader))] // size: 4
        public STURayCastReceiverResult m_DC35ABD3;

        [STUField(0xDE3392C3, 28, ReaderType = typeof(InlineInstanceFieldReader))] // size: 4
        public STURayCastReceiverResult m_DE3392C3;
    }
}


text:
layout: default
title: Components
slug: components
lead: "Dozens of reusable components built to provide iconography, dropdowns, navigation, alerts, popovers, and much more."
---

Dropdown menus

Toggleable, contextual menu for displaying lists of links. Made interactive with the dropdown JavaScript plugin.

Example

Wrap the dropdown's trigger and the dropdown menu within .dropdown, or another element that declares position: relative;. Then add the menu's HTML.

Action

Another action

Something else here

Separated link

{% highlight html %}

Action

Another action

Something else here

Separated link

{% endhighlight %}

Aligning the menus

Add .pull-right to a .dropdown-menu to right align the dropdown menu.

{% highlight html %}

  ...

{% endhighlight %}

Dropdown headers

Add a header to break up label sections of actions in any dropdown menu.

Dropdown header

Action

Another action

Something else here

Dropdown header

Separated link

{% highlight html %}

Dropdown header

  ...

Dropdown header

  ...

{% endhighlight %}

Disabled menu options

Add .disabled to a <li> in the dropdown to disable the link.

Regular link

Disabled link

Another link

{% highlight html %}

Regular link

Disabled link

Another link

{% endhighlight %}

Button groups

Group a series of buttons together on a single line with the button group. Add on optional JavaScript radio and checkbox style behavior with our buttons plugin.

Tooltips & popovers in button groups require special setting

When using tooltips or popovers on elements within a .btn-group, you'll have to specify the option container: 'body' to avoid unwanted side effects (such as the element growing wider and/or losing its rounded corners when the tooltip or popover is triggered).

Basic button group

Wrap a series of buttons with .btn in .btn-group.

        <button type="button" class="btn btn-default">Left</button>
        <button type="button" class="btn btn-default">Middle</button>
        <button type="button" class="btn btn-default">Right</button>

{% highlight html %}

  <button type="button" class="btn btn-default">Left</button>
  <button type="button" class="btn btn-default">Middle</button>
  <button type="button" class="btn btn-default">Right</button>

{% endhighlight %}

Multiple button groups

Combine sets of <div class="btn-group"> into a <div class="btn-toolbar"> for more complex components.

          <button type="button" class="btn btn-default">1</button>
          <button type="button" class="btn btn-default">2</button>
          <button type="button" class="btn btn-default">3</button>
          <button type="button" class="btn btn-default">4</button>

          <button type="button" class="btn btn-default">5</button>
          <button type="button" class="btn btn-default">6</button>
          <button type="button" class="btn btn-default">7</button>

          <button type="button" class="btn btn-default">8</button>

{% highlight html %}

...

...

...

{% endhighlight %}

Nested button groups

Place buttons groups within button groups when you want dropdown menus mixed with a series of buttons.

        <button type="button" class="btn btn-default">1</button>
        <button type="button" class="btn btn-default">2</button>
        <button type="button" class="btn btn-default">3</button>

          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            Dropdown

          </button>

Dropdown link

Dropdown link

Dropdown link

Vertical button groups

Make a set of buttons appear vertically stacked rather than horizontally.

        <button type="button" class="btn btn-default">Button</button>
        <button type="button" class="btn btn-default">Button</button>
        <button type="button" class="btn btn-default">Button</button>
        <button type="button" class="btn btn-default">Button</button>

{% highlight html %}

  ...

{% endhighlight %}

Justified button groups

Make a group of buttons stretch at the same size to span the entire width of its parent.

Element-specific usage

This only works with <a> elements as the <button> doesn't pick up these styles.

        Left
        Right
        Middle

{% highlight html %}

  ...

{% endhighlight %}

Button dropdown menus

Use any button to trigger a dropdown menu by placing it within a .btn-group and providing the proper menu markup.

Plugin dependency

Button dropdowns require the dropdown plugin to be included in your version of Bootstrap.

Single button dropdowns

Turn a button into dropdown toggle with some basic markup changes.

          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Action </button>

Action

Another action

Something else here

Separated link

          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Action </button>

Action

Another action

Something else here

Separated link

          <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown">Danger </button>

Action

Another action

Something else here

Separated link

          <button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown">Warning </button>

Action

Another action

Something else here

Separated link

          <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">Success </button>

Action

Another action

Something else here

Separated link

{% highlight html %}

  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    Action
  </button>

Action

Another action

Something else here

Separated link

{% endhighlight %}

Split button dropdowns

Similarly, create split button dropdowns with the same markup changes, only with a separate button.

          <button type="button" class="btn btn-default">Action</button>
          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated link

          <button type="button" class="btn btn-primary">Action</button>
          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated link

          <button type="button" class="btn btn-danger">Danger</button>
          <button type="button" class="btn btn-danger dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated link

          <button type="button" class="btn btn-warning">Warning</button>
          <button type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated link

          <button type="button" class="btn btn-success">Success</button>
          <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated link

{% highlight html %}

  <button type="button" class="btn btn-default">Action</button>
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

  </button>

Action

Another action

Something else here

Separated link

{% endhighlight %}

Works with all button sizes

Button dropdowns work with buttons of all sizes.

          <button class="btn btn-default btn-large dropdown-toggle" type="button" data-toggle="dropdown">
            Large button
          </button>

Action

Another action

Something else here

Separated link

          <button class="btn btn-default btn-small dropdown-toggle" type="button" data-toggle="dropdown">
            Small button
          </button>

Action

Another action

Something else here

Separated link

{% highlight html %}

  <button class="btn btn-default btn-large dropdown-toggle" type="button" data-toggle="dropdown">
    Large button
  </button>

    ...

  <button class="btn btn-default btn-small dropdown-toggle" type="button" data-toggle="dropdown">
    Small button
  </button>

    ...

{% endhighlight %}

Dropup buttons

Trigger dropdown menus above elements by adding .dropup to the parent.

          <button type="button" class="btn btn-default">Dropup</button>
          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated link

          <button type="button" class="btn btn-primary">Right dropup</button>
          <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"></button>

Action

Another action

Something else here

Separated link

{% highlight html %}

  <button type="button" class="btn btn-default">Dropup</button>
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

  </button>

{% endhighlight %}

Navs

Navs available in Bootstrap have shared markup, starting with the base .nav class, as well as shared states. Swap modifier classes to switch between each style.

Tabs

Note the .nav-tabs class requires the .nav base class.

Home

Profile

Messages

{% highlight html %}

Home

Profile

Messages

{% endhighlight %}

Pills

Take that same HTML, but use .nav-pills instead:

Home

Profile

Messages

{% highlight html %}

Home

Profile

Messages

{% endhighlight %}

Pills are also vertically stackable. Just add .nav-stacked.

Home

Profile

Messages

{% highlight html %}

  ...

{% endhighlight %}

Options

Justified links

Easily make tabs or pills equal widths of their parent with .nav-justified.

Home

Profile

Messages

Home

Profile

Messages

{% highlight html %}

  ...

  ...

{% endhighlight %}

Disabled state

For any nav component (tabs, pills, or list), add .disabled for gray links and no hover effects.

Link functionality not impacted

This class will only change the <a>'s appearance, not its functionality. Use custom JavaScript to disable links here.

Clickable link

Clickable link

Disabled link

{% highlight html %}

  ...

Disabled link

  ...

{% endhighlight %}

Component alignment

To align nav links, use the .pull-left or .pull-right utility classes. Both classes will add a CSS float in the specified direction.

Dropdowns

Add dropdown menus with a little extra HTML and the dropdowns JavaScript plugin.

Tabs with dropdowns

Home

Help

            Dropdown

Action

Another action

Something else here

Separated link

{% highlight html %}

  ...

      Dropdown

      ...

  ...

{% endhighlight %}

Pills with dropdowns

Home

Help

            Dropdown

Action

Another action

Something else here

Separated link

{% highlight html %}

  ...

      Dropdown

      ...

  ...

{% endhighlight %}

Navbar

Basic navbar

To start, navbars are static (not fixed to the top) and include support for a project name and basic navigation. Place one anywhere within a .container, which sets the width of your site and content.

        Title

Home

Link

Link

{% highlight html %}

  Title

Home

Link

Link

{% endhighlight %}

Navbar components

Brand

A simple link to show your brand or project name only requires an anchor tag.

        Title

{% highlight html %}
Title
{% endhighlight %}

Nav links

Nav items are simple to add via unordered lists.

Home

Link

Disabled

{% highlight html %}

Home

Link

Disabled

{% endhighlight %}

Forms

To properly style and position a form within the navbar, add the appropriate classes as shown below. For a default form, include .navbar-form and either .pull-left or .pull-right to properly align it.

        <form class="navbar-form pull-left">
          <input type="text" style="width: 200px;">
          <button type="submit" class="btn btn-default">Submit</button>
        </form>

        <form class="navbar-form pull-left">
          <select name="" id="" style="width: 200px;">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
          </select>
          <button type="submit" class="btn btn-default">Submit</button>
        </form>

        <form class="navbar-form pull-left">
          <input type="text" style="width: 200px;">
          <input type="checkbox">
          <button type="submit" class="btn btn-default">Submit</button>
        </form>

        <form class="navbar-form pull-left">
          <input type="text" style="width: 200px;">

            <input type="checkbox"> Remember me

          <button type="submit" class="btn btn-default">Submit</button>
        </form>

{% highlight html %}
<form class="navbar-form pull-left">
  <input type="text" style="width: 200px;">
  <button type="submit" class="btn btn-default">Submit</button>
</form>
{% endhighlight %}

Buttons

For buttons not residing in a <form>, add this class to vertically center buttons within a navbar.

        Brand
        <button type="button" class="btn btn-default navbar-btn">Sign in</button>

{% highlight html %}
<button type="button" class="btn btn-default navbar-btn">Sign in</button>
{% endhighlight %}

Text

Wrap strings of text in an element with .navbar-text, usually on a <p> tag for proper leading and color.

        Brand

Signed in as Mark Otto

{% highlight html %}

  Brand

Signed in as Mark Otto

{% endhighlight %}

Links

For folks using standard links that are not within the regular navbar navigation component, use the .navbar-link class to add the proper colors for the default and inverse navbar options.

        Brand

Signed in as Mark Otto

{% highlight html %}

  Brand

Signed in as Mark Otto

{% endhighlight %}

Component alignment

Align nav links, forms, buttons, or text, using the .pull-left or .pull-right utility classes. Both classes will add a CSS float in the specified direction. To align nav links, put them in a separate <ul> with the respective utility class applied.

Optional display variations

Fix the navbar to the top or bottom of the viewport with an additional class on the outermost div, .navbar. These will also remove rounded corners.

Fixed to top

Add .navbar-fixed-top.

          Title

Home

Link

Link

{% highlight html %}

  ...

{% endhighlight %}

Body padding required

The fixed navbar will overlay your other content, unless you add padding to the top of the <body>. Try out your own values or use our snippet below. Tip: By default, the navbar is 50px high.

{% highlight css %}
body { padding-top: 70px; }
{% endhighlight %}

Make sure to include this after the core Bootstrap CSS.

Fixed to bottom

Add .navbar-fixed-bottom instead.

          Title

Home

Link

Link

{% highlight html %}

  ...

{% endhighlight %}

Body padding required

The fixed navbar will overlay your other content, unless you add padding to the bottom of the <body>. Try out your own values or use our snippet below. Tip: By default, the navbar is 50px high.

{% highlight css %}
body { padding-bottom: 70px; }
{% endhighlight %}

Make sure to include this after the core Bootstrap CSS.

Static top navbar

Create a full-width navbar that scrolls away with the page by adding .navbar-static-top. Unlike the .navbar-fixed-* classes, you do not need to change any padding on the body.

          Title

Home

Link

Link

{% highlight html %}

  ...

{% endhighlight %}

Responsive navbar

To implement a collapsing responsive navbar, wrap your navbar content in a containing div, .nav-collapse.collapse, and add the navbar toggle button, .navbar-toggle.

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">

          </button>
          Title

Home

Link

Link

                Dropdown

Action

Another action

Something else here

Dropdown header

Separated link

One more separated link

            <form class="navbar-form pull-left" action="">
              <input type="text" class="col-lg-8" placeholder="Search">
            </form>

Link

                Dropdown

Action

Another action

Something else here

Separated link

{% highlight html %}

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-responsive-collapse">

    </button>

    Title

      ...

{% endhighlight %}

Plugin dependency

The responsive navbar requires the collapse plugin to be included in your version of Bootstrap.

Inverted variation

Modify the look of the navbar by adding .navbar-inverse.

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-inverse-collapse">

          </button>
          Title

Home

Link

Link

                Dropdown

Action

Another action

Something else here

Dropdown header

Separated link

One more separated link

            <form class="navbar-form pull-left" action="">
              <input type="text" class="col-lg-8" placeholder="Search">
            </form>

Link

                Dropdown

Action

Another action

Something else here

Separated link

{% highlight html %}

  ...

{% endhighlight %}

Breadcrumbs

Indicate the current page's location within a navigational hierarchy.

Separators are automatically added in CSS through :before and content.

Home

Home

Library

Home

Library

Data

{% highlight html %}

Home

Library

Data

{% endhighlight %}

Pagination

Provide pagination links for your site or app with the multi-page pagination component, or the simpler pager alternative.

Standard pagination

Simple pagination inspired by Rdio, great for apps and search results. The large block is hard to miss, easily scalable, and provides large click areas.

«

1

2

3

4

5

»

{% highlight html %}

«

1

2

3

4

5

»

{% endhighlight %}

Disabled and active states

Links are customizable for different circumstances. Use .disabled for unclickable links and .active to indicate the current page.

«

1

2

3

4

5

»

{% highlight html %}

«

1

  ...

{% endhighlight %}

You can optionally swap out active or disabled anchors for <span> to remove click functionality while retaining intended styles.

{% highlight html %}

«

1

  ...

{% endhighlight %}

Sizes

Fancy larger or smaller pagination? Add .pagination-large or .pagination-small  for additional sizes.

«

1

2

3

4

5

»

«

1

2

3

4

5

»

«

1

2

3

4

5

»

{% highlight html %}

...

...

...

{% endhighlight %}

Pager

Quick previous and next links for simple pagination implementations with light markup and styles. It's great for simple sites like blogs or magazines.

Default example

By default, the pager centers links.

Previous

Next

{% highlight html %}

Previous

Next

{% endhighlight %}

Aligned links

Alternatively, you can align each link to the sides:

← Older

Newer →

{% highlight html %}

← Older

Newer →

{% endhighlight %}

Optional disabled state

Pager links also use the general .disabled utility class from the pagination.

← Older

Newer →

{% highlight html %}

← Older

Newer →

{% endhighlight %}

Labels

Example

Example heading New

Example heading New

Example heading New

Example heading New

Example heading New

Example heading New

{% highlight html %}

Example heading New

{% endhighlight %}

Available variations

Add any of the below mentioned modifier classes to change the appearance of a label.

      Default
      Success
      Warning
      Danger
      Info

{% highlight html %}
Default
Success
Warning
Danger
Info
{% endhighlight %}

Badges

Easily highlight new or unread items by adding a <span class="badge"> to links, Bootstrap navs, and more.

      Inbox 42

{% highlight html %}
Inbox 42
{% endhighlight %}

Self collapsing

When there are no new or unread items, badges will simply collapse (via CSS's :empty selector) provided no content exists within.

Cross-browser compatibility

Badges won't self collapse in Internet Explorer 8 because it lacks support for the :empty selector.

Adapts to active nav states

Built-in styles are included for placing badges in active states in pill and list navigations.

Home 42

Profile

Messages 3

            42
            Home

Profile

            3
            Messages

{% highlight html %}

      42
      Home

  ...

{% endhighlight %}

Typographic components

Jumbotron

A lightweight, flexible component to showcase key content on your site. It works well on marketing and content-heavy sites.

Hello, world!

This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.

Learn more

{% highlight html %}

Hello, world!

...

Learn more

{% endhighlight %}

Page header

A simple shell for an h1 to appropriately space out and segment sections of content on a page. It can utilize the h1's default small element, as well as most other components (with additional styles).

Example page header Subtext for header

{% highlight html %}

Example page header Subtext for header

{% endhighlight %}

Thumbnails

Extend Bootstrap's grid system with the thumbnail component to easily display grids of images, videos, text, and more.

Default thumbnails

By default, Bootstrap's thumbnails are designed to showcase linked images with minimal required markup.

{% highlight html %}

  ...

{% endhighlight %}

Custom content thumbnails

With a bit of extra markup, it's possible to add any kind of HTML content like headings, paragraphs, or buttons into thumbnails.

Thumbnail label

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Action Action

Thumbnail label

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Action Action

Thumbnail label

Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.

Action Action

{% highlight html %}

Thumbnail label

...

Action Action

{% endhighlight %}

Alerts

Provide contextual feedback messages for typical user actions with the handful of available and flexible alert messages. For inline dismissal, use the alerts jQuery plugin.

Default alert

Wrap any text and an optional dismiss button in .alert for a basic warning alert message.

Ensure proper behavior across all devices

Be sure to use the <button> element with the data-dismiss="alert" data attribute.

        <button type="button" class="close" data-dismiss="alert">×</button>
        Warning! Best check yo self, you're not looking too good.

{% highlight html %}

  <button type="button" class="close" data-dismiss="alert">×</button>
  Warning! Best check yo self, you're not looking too good.

{% endhighlight %}

Block alerts

For longer messages, increase the padding on the top and bottom of the alert wrapper by adding .alert-block.

        <button type="button" class="close" data-dismiss="alert">×</button>

Warning!

Best check yo self, you're not looking too good. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

{% highlight html %}

  <button type="button" class="close" data-dismiss="alert">×</button>

Warning!

...

{% endhighlight %}

Contextual alternatives

Add optional classes to change an alert's connotation.

        <button type="button" class="close" data-dismiss="alert">×</button>
        Oh snap! Change a few things up and try submitting again.

        <button type="button" class="close" data-dismiss="alert">×</button>
        Well done! You successfully read this important alert message.

        <button type="button" class="close" data-dismiss="alert">×</button>
        Heads up! This alert needs your attention, but it's not super important.

{% highlight html %}

...

...

...

{% endhighlight %}

Links in alerts

Use the .alert-link utility class to quickly provide matching colored links within any alert.

        <button type="button" class="close" data-dismiss="alert">×</button>
        Oh snap! Change a few things up and try submitting again.

        <button type="button" class="close" data-dismiss="alert">×</button>
        Well done! You successfully read this important alert message.

        <button type="button" class="close" data-dismiss="alert">×</button>
        Heads up! This alert needs your attention, but it's not super important.

{% highlight html %}

  ...

  ...

  ...

{% endhighlight %}

Progress bars

Provide up-to-date feedback on the progress of a workflow or action with simple yet flexible progress bars.

Cross-browser compatibility

Progress bars use CSS3 transitions and animations to achieve some of their effects. These features are not supported in Internet Explorer 9 and below or older versions of Firefox. Opera 12 does not support animations.

Basic

Default progress bar with a vertical gradient.

{% highlight html %}

{% endhighlight %}

Contextual alternatives

Progress bars use some of the same button and alert classes for consistent styles.

{% highlight html %}

{% endhighlight %}

Striped

Uses a gradient to create a striped effect. Not available in IE8.

{% highlight html %}

{% endhighlight %}

Animated

Add .active to .progress-striped to animate the stripes right to left. Not available in all versions of IE.

{% highlight html %}

{% endhighlight %}

Stacked

Place multiple bars into the same .progress to stack them.

{% highlight html %}

{% endhighlight %}

Media object

Abstract object styles for building various types of components (like blog comments, Tweets, etc) that feature a left- or right-aligned image alongside textual content.

Default example

The default media allow to float a media object (images, video, audio) to the left or right of a content block.

Media heading

          Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Media heading

          Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Media heading

              Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

{% highlight html %}

Media heading

    ...

{% endhighlight %}

Media list

With a bit of extra markup, you can use media inside list (useful for comment threads or articles lists).

Media heading

Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.

Nested media heading

                Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.

Nested media heading

                    Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.

Nested media heading

                Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.

Media heading

            Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.

{% highlight html %}

Media heading

      ...

{% endhighlight %}

List group

List groups are a flexible and powerful component for displaying not only simple lists of elements, but complex ones with custom content.

Basic list group

The most basic list group is simply an unordered list with list items, and the proper classes. Build upon it with the options that follow, or your own CSS as needed.

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

{% highlight html %}

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

{% endhighlight %}

With badges

Add the badges component to any list group item and it will automatically be positioned on the right.

          14
          Cras justo odio

          2
          Dapibus ac facilisis in

          1
          Morbi leo risus

{% highlight html %}

    14
    Cras justo odio

{% endhighlight %}

Linked list group

Linkify list group items by using anchor tags instead of list items (that also means a parent <div> instead of an <ul>). No need for individual parents around each element.

          Cras justo odio

        Dapibus ac facilisis in

        Morbi leo risus

        Porta ac consectetur ac

        Vestibulum at eros

{% highlight html %}

    Cras justo odio

  Dapibus ac facilisis in

  Morbi leo risus

  Porta ac consectetur ac

  Vestibulum at eros

{% endhighlight %}

Custom content

Add nearly any HTML within, even for linked list groups like the one below.

List group item heading

Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.

List group item heading

Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.

List group item heading

Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.

{% highlight html %}

List group item heading

...

{% endhighlight %}

Panels

While not always necessary, sometimes you need to put your DOM in a box. For those situations, try the panel component.

Basic panel

By default, all the .panel does is apply some basic border and padding to contain some content.

        Basic panel example

{% highlight html %}

  Basic panel example

{% endhighlight %}

Panel with heading

Easily add a heading to your panel with .panel-heading. Use it on a <div> or any heading element (e.g., <h3>).

Panel heading

        Panel content

{% highlight html %}

Panel heading

  Panel content

{% endhighlight %}

Panel with footer

Wrap buttons or secondary text in .panel-footer.

        Panel content

Panel footer

{% highlight html %}

  Panel content

Panel footer

{% endhighlight %}

Contextual alternatives

Like other components, easily make a panel more meaningful to a particular context by adding any of the contextual state classes.

Panel heading

        Panel content

Panel heading

        Panel content

Panel heading

        Panel content

Panel heading

        Panel content

Panel heading

        Panel content

{% highlight html %}

...

...

...

...

...

{% endhighlight %}

With list groups

Easily include full-width list groups within any panel.

Panel heading

Some default panel content here. Nulla vitae elit libero, a pharetra augue. Aenean lacinia bibendum nulla sed consectetur. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Nullam id dolor id nibh ultricies vehicula ut id elit.

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

{% highlight html %}

Panel heading

...

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

{% endhighlight %}

Wells

Default well

Use the well as a simple effect on an element to give it an inset effect.

        Look, I'm in a well!

{% highlight html %}

...

{% endhighlight %}

Optional classes

Control padding and rounded corners with two optional modifier classes.

        Look, I'm in a well!

{% highlight html %}

...

{% endhighlight %}

        Look, I'm in a well!

{% highlight html %}

...

{% endhighlight %}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html

module Stratosphere.ResourceProperties.EC2InstancePrivateIpAddressSpecification where

import Stratosphere.ResourceImports

-- | Full data type definition for EC2InstancePrivateIpAddressSpecification.
-- See 'ec2InstancePrivateIpAddressSpecification' for a more convenient
-- constructor.
data EC2InstancePrivateIpAddressSpecification =
  EC2InstancePrivateIpAddressSpecification
  { _eC2InstancePrivateIpAddressSpecificationPrimary :: Val Bool
  , _eC2InstancePrivateIpAddressSpecificationPrivateIpAddress :: Val Text
  } deriving (Show, Eq)

instance ToJSON EC2InstancePrivateIpAddressSpecification where
  toJSON EC2InstancePrivateIpAddressSpecification{..} =
    object $
    catMaybes
    [ (Just . ("Primary",) . toJSON) _eC2InstancePrivateIpAddressSpecificationPrimary
    , (Just . ("PrivateIpAddress",) . toJSON) _eC2InstancePrivateIpAddressSpecificationPrivateIpAddress
    ]

-- | Constructor for 'EC2InstancePrivateIpAddressSpecification' containing
-- required fields as arguments.
ec2InstancePrivateIpAddressSpecification
  :: Val Bool -- ^ 'ecipiasPrimary'
  -> Val Text -- ^ 'ecipiasPrivateIpAddress'
  -> EC2InstancePrivateIpAddressSpecification
ec2InstancePrivateIpAddressSpecification primaryarg privateIpAddressarg =
  EC2InstancePrivateIpAddressSpecification
  { _eC2InstancePrivateIpAddressSpecificationPrimary = primaryarg
  , _eC2InstancePrivateIpAddressSpecificationPrivateIpAddress = privateIpAddressarg
  }

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-primary
ecipiasPrimary :: Lens' EC2InstancePrivateIpAddressSpecification (Val Bool)
ecipiasPrimary = lens _eC2InstancePrivateIpAddressSpecificationPrimary (\s a -> s { _eC2InstancePrivateIpAddressSpecificationPrimary = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-privateipaddress
ecipiasPrivateIpAddress :: Lens' EC2InstancePrivateIpAddressSpecification (Val Text)
ecipiasPrivateIpAddress = lens _eC2InstancePrivateIpAddressSpecificationPrivateIpAddress (\s a -> s { _eC2InstancePrivateIpAddressSpecificationPrivateIpAddress = a })


text:
"""
:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""

from decimal import Decimal

import pytest
from pytest import raises

from byceps.database import generate_uuid
from byceps.services.shop.article.transfer.models import (
    Article,
    ArticleID,
    ArticleNumber,
    ArticleType,
)
from byceps.services.shop.cart.models import CartItem
from byceps.services.shop.shop.transfer.models import ShopID

@pytest.mark.parametrize(
    'quantity, expected_line_amount',
    [
        (1, Decimal('1.99')),
        (2, Decimal('3.98')),
        (6, Decimal('11.94')),
    ],
)
def test_init_with_positive_quantity(
    quantity: int, expected_line_amount: Decimal
):
    item = create_item(quantity)

    assert item.quantity == quantity
    assert item.line_amount == expected_line_amount

def test_init_with_zero_quantity():
    with raises(ValueError):
        create_item(0)

def test_init_with_negative_quantity():
    with raises(ValueError):
        create_item(-1)

# helpers

def create_item(quantity: int) -> CartItem:
    article = create_article()
    return CartItem(article, quantity)

def create_article() -> Article:
    return Article(
        id=ArticleID(generate_uuid()),
        shop_id=ShopID('any-shop'),
        item_number=ArticleNumber('article-123'),
        type_=ArticleType.other,
        type_params={},
        description='Cool thing',
        price=Decimal('1.99'),
        tax_rate=Decimal('0.19'),
        available_from=None,
        available_until=None,
        total_quantity=1,
        quantity=1,
        max_quantity_per_order=1,
        not_directly_orderable=False,
        separate_order_required=False,
        processing_required=False,
    )


text:
package org.apache.cassandra.auth;

import java.util.*;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.cassandra.concurrent.ScheduledExecutors;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.cql3.*;
import org.apache.cassandra.cql3.statements.BatchStatement;
import org.apache.cassandra.cql3.statements.ModificationStatement;
import org.apache.cassandra.cql3.statements.SelectStatement;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.exceptions.*;
import org.apache.cassandra.serializers.SetSerializer;
import org.apache.cassandra.serializers.UTF8Serializer;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.transport.messages.ResultMessage;
import org.apache.cassandra.utils.ByteBufferUtil;

/**
 * CassandraAuthorizer is an IAuthorizer implementation that keeps
 * user permissions internally in C* using the system_auth.role_permissions
 * table.
 */
public class CassandraAuthorizer implements IAuthorizer
{
    private static final Logger logger = LoggerFactory.getLogger(CassandraAuthorizer.class);

    private static final String ROLE = "role";
    private static final String RESOURCE = "resource";
    private static final String PERMISSIONS = "permissions";

    // used during upgrades to perform authz on mixed clusters
    public static final String USERNAME = "username";
    public static final String USER_PERMISSIONS = "permissions";

    private SelectStatement authorizeRoleStatement;
    private SelectStatement legacyAuthorizeRoleStatement;

    public CassandraAuthorizer()
    {
    }

    // Returns every permission on the resource granted to the user either directly
    // or indirectly via roles granted to the user.
    public Set<Permission> authorize(AuthenticatedUser user, IResource resource)
    {
        if (user.isSuper())
            return resource.applicablePermissions();

        Set<Permission> permissions = EnumSet.noneOf(Permission.class);
        try
        {
            for (RoleResource role: user.getRoles())
                addPermissionsForRole(permissions, resource, role);
        }
        catch (RequestValidationException e)
        {
            throw new AssertionError(e); // not supposed to happen
        }
        catch (RequestExecutionException e)
        {
            logger.warn("CassandraAuthorizer failed to authorize {} for {}", user, resource);
            return Permission.NONE;
        }

        return permissions;
    }

    public void grant(AuthenticatedUser performer, Set<Permission> permissions, IResource resource, RoleResource grantee)
    throws RequestValidationException, RequestExecutionException
    {
        modifyRolePermissions(permissions, resource, grantee, "+");
        addLookupEntry(resource, grantee);
    }

    public void revoke(AuthenticatedUser performer, Set<Permission> permissions, IResource resource, RoleResource revokee)
    throws RequestValidationException, RequestExecutionException
    {
        modifyRolePermissions(permissions, resource, revokee, "-");
        removeLookupEntry(resource, revokee);
    }

    // Called when deleting a role with DROP ROLE query.
    // Internal hook, so no permission checks are needed here.
    // Executes a logged batch removing the granted premissions
    // for the role as well as the entries from the reverse index
    // table
    public void revokeAllFrom(RoleResource revokee)
    {
        try
        {
            UntypedResultSet rows = process(String.format("SELECT resource FROM %s.%s WHERE role = '%s'",
                                                          AuthKeyspace.NAME,
                                                          AuthKeyspace.ROLE_PERMISSIONS,
                                                          escape(revokee.getRoleName())));

            List<CQLStatement> statements = new ArrayList<>();
            for (UntypedResultSet.Row row : rows)
            {
                statements.add(
                    QueryProcessor.getStatement(String.format("DELETE FROM %s.%s WHERE resource = '%s' AND role = '%s'",
                                                              AuthKeyspace.NAME,
                                                              AuthKeyspace.RESOURCE_ROLE_INDEX,
                                                              escape(row.getString("resource")),
                                                              escape(revokee.getRoleName())),
                                                ClientState.forInternalCalls()).statement);

            }

            statements.add(QueryProcessor.getStatement(String.format("DELETE FROM %s.%s WHERE role = '%s'",
                                                                     AuthKeyspace.NAME,
                                                                     AuthKeyspace.ROLE_PERMISSIONS,
                                                                     escape(revokee.getRoleName())),
                                                       ClientState.forInternalCalls()).statement);

            executeLoggedBatch(statements);
        }
        catch (RequestExecutionException | RequestValidationException e)
        {
            logger.warn("CassandraAuthorizer failed to revoke all permissions of {}: {}",  revokee.getRoleName(), e);
        }
    }

    // Called after a resource is removed (DROP KEYSPACE, DROP TABLE, etc.).
    // Execute a logged batch removing all the permissions for the resource
    // as well as the index table entry
    public void revokeAllOn(IResource droppedResource)
    {
        try
        {
            UntypedResultSet rows = process(String.format("SELECT role FROM %s.%s WHERE resource = '%s'",
                                                          AuthKeyspace.NAME,
                                                          AuthKeyspace.RESOURCE_ROLE_INDEX,
                                                          escape(droppedResource.getName())));

            List<CQLStatement> statements = new ArrayList<>();
            for (UntypedResultSet.Row row : rows)
            {
                statements.add(QueryProcessor.getStatement(String.format("DELETE FROM %s.%s WHERE role = '%s' AND resource = '%s'",
                                                                         AuthKeyspace.NAME,
                                                                         AuthKeyspace.ROLE_PERMISSIONS,
                                                                         escape(row.getString("role")),
                                                                         escape(droppedResource.getName())),
                                                           ClientState.forInternalCalls()).statement);
            }

            statements.add(QueryProcessor.getStatement(String.format("DELETE FROM %s.%s WHERE resource = '%s'",
                                                                                AuthKeyspace.NAME,
                                                                                AuthKeyspace.RESOURCE_ROLE_INDEX,
                                                                                escape(droppedResource.getName())),
                                                                               ClientState.forInternalCalls()).statement);

            executeLoggedBatch(statements);
        }
        catch (RequestExecutionException | RequestValidationException e)
        {
            logger.warn("CassandraAuthorizer failed to revoke all permissions on {}: {}", droppedResource, e);
            return;
        }
    }

    private void executeLoggedBatch(List<CQLStatement> statements)
    throws RequestExecutionException, RequestValidationException
    {
        BatchStatement batch = new BatchStatement(0,
                                                  BatchStatement.Type.LOGGED,
                                                  Lists.newArrayList(Iterables.filter(statements, ModificationStatement.class)),
                                                  Attributes.none());
        QueryProcessor.instance.processBatch(batch,
                                             QueryState.forInternalCalls(),
                                             BatchQueryOptions.withoutPerStatementVariables(QueryOptions.DEFAULT));

    }

    // Add every permission on the resource granted to the role
    private void addPermissionsForRole(Set<Permission> permissions, IResource resource, RoleResource role)
    throws RequestExecutionException, RequestValidationException
    {
        QueryOptions options = QueryOptions.forInternalCalls(ConsistencyLevel.LOCAL_ONE,
                                                             Lists.newArrayList(ByteBufferUtil.bytes(role.getRoleName()),
                                                                                ByteBufferUtil.bytes(resource.getName())));

        // If it exists, read from the legacy user permissions table to handle the case where the cluster
        // is being upgraded and so is running with mixed versions of the authz schema
        SelectStatement statement = Schema.instance.getCFMetaData(AuthKeyspace.NAME, USER_PERMISSIONS) == null
                                    ? authorizeRoleStatement
                                    : legacyAuthorizeRoleStatement;
        ResultMessage.Rows rows = statement.execute(QueryState.forInternalCalls(), options) ;
        UntypedResultSet result = UntypedResultSet.create(rows.result);

        if (!result.isEmpty() && result.one().has(PERMISSIONS))
        {
            for (String perm : result.one().getSet(PERMISSIONS, UTF8Type.instance))
            {
                permissions.add(Permission.valueOf(perm));
            }
        }
    }

    // Adds or removes permissions from a role_permissions table (adds if op is "+", removes if op is "-")
    private void modifyRolePermissions(Set<Permission> permissions, IResource resource, RoleResource role, String op)
            throws RequestExecutionException
    {
        process(String.format("UPDATE %s.%s SET permissions = permissions %s {%s} WHERE role = '%s' AND resource = '%s'",
                              AuthKeyspace.NAME,
                              AuthKeyspace.ROLE_PERMISSIONS,
                              op,
                              "'" + StringUtils.join(permissions, "','") + "'",
                              escape(role.getRoleName()),
                              escape(resource.getName())));
    }

    // Removes an entry from the inverted index table (from resource -> role with defined permissions)
    private void removeLookupEntry(IResource resource, RoleResource role) throws RequestExecutionException
    {
        process(String.format("DELETE FROM %s.%s WHERE resource = '%s' and role = '%s'",
                AuthKeyspace.NAME,
                AuthKeyspace.RESOURCE_ROLE_INDEX,
                escape(resource.getName()),
                escape(role.getRoleName())));
    }

    // Adds an entry to the inverted index table (from resource -> role with defined permissions)
    private void addLookupEntry(IResource resource, RoleResource role) throws RequestExecutionException
    {
        process(String.format("INSERT INTO %s.%s (resource, role) VALUES ('%s','%s')",
                              AuthKeyspace.NAME,
                              AuthKeyspace.RESOURCE_ROLE_INDEX,
                              escape(resource.getName()),
                              escape(role.getRoleName())));
    }

    // 'of' can be null - in that case everyone's permissions have been requested. Otherwise only single user's.
    // If the user requesting 'LIST PERMISSIONS' is not a superuser OR their username doesn't match 'of', we
    // throw UnauthorizedException. So only a superuser can view everybody's permissions. Regular users are only
    // allowed to see their own permissions.
    public Set<PermissionDetails> list(AuthenticatedUser performer,
                                       Set<Permission> permissions,
                                       IResource resource,
                                       RoleResource grantee)
    throws RequestValidationException, RequestExecutionException
    {
        if (!performer.isSuper() && !performer.getRoles().contains(grantee))
            throw new UnauthorizedException(String.format("You are not authorized to view %s's permissions",
                                                          grantee == null ? "everyone" : grantee.getRoleName()));

        if (null == grantee)
            return listPermissionsForRole(permissions, resource, grantee);

        Set<RoleResource> roles = DatabaseDescriptor.getRoleManager().getRoles(grantee, true);
        Set<PermissionDetails> details = new HashSet<>();
        for (RoleResource role : roles)
            details.addAll(listPermissionsForRole(permissions, resource, role));

        return details;
    }

    private Set<PermissionDetails> listPermissionsForRole(Set<Permission> permissions,
                                                          IResource resource,
                                                          RoleResource role)
    throws RequestExecutionException
    {
        Set<PermissionDetails> details = new HashSet<>();
        // If it exists, try the legacy user permissions table first. This is to handle the case
        // where the cluster is being upgraded and so is running with mixed versions of the perms table
        boolean useLegacyTable = Schema.instance.getCFMetaData(AuthKeyspace.NAME, USER_PERMISSIONS) != null;
        String entityColumnName = useLegacyTable ? USERNAME : ROLE;
        for (UntypedResultSet.Row row : process(buildListQuery(resource, role, useLegacyTable)))
        {
            if (row.has(PERMISSIONS))
            {
                for (String p : row.getSet(PERMISSIONS, UTF8Type.instance))
                {
                    Permission permission = Permission.valueOf(p);
                    if (permissions.contains(permission))
                        details.add(new PermissionDetails(row.getString(entityColumnName),
                                                          Resources.fromName(row.getString(RESOURCE)),
                                                          permission));
                }
            }
        }
        return details;
    }

    private String buildListQuery(IResource resource, RoleResource grantee, boolean useLegacyTable)
    {
        String tableName = useLegacyTable ? USER_PERMISSIONS : AuthKeyspace.ROLE_PERMISSIONS;
        String entityName = useLegacyTable ? USERNAME : ROLE;
        List<String> vars = Lists.newArrayList(AuthKeyspace.NAME, tableName);
        List<String> conditions = new ArrayList<>();

        if (resource != null)
        {
            conditions.add("resource = '%s'");
            vars.add(escape(resource.getName()));
        }

        if (grantee != null)
        {
            conditions.add(entityName + " = '%s'");
            vars.add(escape(grantee.getRoleName()));
        }

        String query = "SELECT " + entityName + ", resource, permissions FROM %s.%s";

        if (!conditions.isEmpty())
            query += " WHERE " + StringUtils.join(conditions, " AND ");

        if (resource != null && grantee == null)
            query += " ALLOW FILTERING";

        return String.format(query, vars.toArray());
    }

    public Set<DataResource> protectedResources()
    {
        return ImmutableSet.of(DataResource.table(AuthKeyspace.NAME, AuthKeyspace.ROLE_PERMISSIONS));
    }

    public void validateConfiguration() throws ConfigurationException
    {
    }

    public void setup()
    {
        authorizeRoleStatement = prepare(ROLE, AuthKeyspace.ROLE_PERMISSIONS);

        // If old user permissions table exists, migrate the legacy authz data to the new table
        // The delay is to give the node a chance to see its peers before attempting the conversion
        if (Schema.instance.getCFMetaData(AuthKeyspace.NAME, "permissions") != null)
        {
            legacyAuthorizeRoleStatement = prepare(USERNAME, USER_PERMISSIONS);

            ScheduledExecutors.optionalTasks.schedule(new Runnable()
            {
                public void run()
                {
                    convertLegacyData();
                }
            }, AuthKeyspace.SUPERUSER_SETUP_DELAY, TimeUnit.MILLISECONDS);
        }
    }

    private SelectStatement prepare(String entityname, String permissionsTable)
    {
        String query = String.format("SELECT permissions FROM %s.%s WHERE %s = ? AND resource = ?",
                                     AuthKeyspace.NAME,
                                     permissionsTable,
                                     entityname);
        return (SelectStatement) QueryProcessor.getStatement(query, ClientState.forInternalCalls()).statement;
    }

    /**
     * Copy legacy authz data from the system_auth.permissions table to the new system_auth.role_permissions table and
     * also insert entries into the reverse lookup table.
     * In theory, we could simply rename the existing table as the schema is structurally the same, but this would
     * break mixed clusters during a rolling upgrade.
     * This setup is not performed if AllowAllAuthenticator is configured (see Auth#setup).
     */
    private void convertLegacyData()
    {
        try
        {
            if (Schema.instance.getCFMetaData("system_auth", "permissions") != null)
            {
                logger.info("Converting legacy permissions data");
                CQLStatement insertStatement =
                    QueryProcessor.getStatement(String.format("INSERT INTO %s.%s (role, resource, permissions) " +
                                                              "VALUES (?, ?, ?)",
                                                              AuthKeyspace.NAME,
                                                              AuthKeyspace.ROLE_PERMISSIONS),
                                                ClientState.forInternalCalls()).statement;
                CQLStatement indexStatement =
                    QueryProcessor.getStatement(String.format("INSERT INTO %s.%s (resource, role) VALUES (?,?)",
                                                              AuthKeyspace.NAME,
                                                              AuthKeyspace.RESOURCE_ROLE_INDEX),
                                                ClientState.forInternalCalls()).statement;

                UntypedResultSet permissions = process("SELECT * FROM system_auth.permissions");
                for (UntypedResultSet.Row row : permissions)
                {
                    final IResource resource = Resources.fromName(row.getString("resource"));
                    Predicate<String> isApplicable = new Predicate<String>()
                    {
                        public boolean apply(String s)
                        {
                            return resource.applicablePermissions().contains(Permission.valueOf(s));
                        }
                    };
                    SetSerializer<String> serializer = SetSerializer.getInstance(UTF8Serializer.instance);
                    Set<String> originalPerms = serializer.deserialize(row.getBytes("permissions"));
                    Set<String> filteredPerms = ImmutableSet.copyOf(Iterables.filter(originalPerms, isApplicable));
                    insertStatement.execute(QueryState.forInternalCalls(),
                                            QueryOptions.forInternalCalls(ConsistencyLevel.ONE,
                                                                          Lists.newArrayList(row.getBytes("username"),
                                                                                row.getBytes("resource"),
                                                                                serializer.serialize(filteredPerms))));

                    indexStatement.execute(QueryState.forInternalCalls(),
                                           QueryOptions.forInternalCalls(ConsistencyLevel.ONE,
                                                                         Lists.newArrayList(row.getBytes("resource"),
                                                                                row.getBytes("username"))));

                }
                logger.info("Completed conversion of legacy permissions");
            }
        }
        catch (Exception e)
        {
            logger.info("Unable to complete conversion of legacy permissions data (perhaps not enough nodes are upgraded yet). " +
                        "Conversion should not be considered complete");
            logger.debug("Conversion error", e);
        }
    }

    // We only worry about one character ('). Make sure it's properly escaped.
    private String escape(String name)
    {
        return StringUtils.replace(name, "'", "''");
    }

    private UntypedResultSet process(String query) throws RequestExecutionException
    {
        return QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
    }
}


text:
<?php

namespace Ice\Domain\Jobs;

class WorkerDirector implements WorkerDirectorInterface
{
    /**
     * @var WorkerProviderInterface[]|array
     */
    private $factories = array();

    /**
     * @param WorkerProviderInterface $jobFactory
     * @return \Ice\Domain\Jobs\WorkerDirectorInterface
     */
    public function addWorkerProvider(WorkerProviderInterface $jobFactory)
    {
        $this->factories[] = $jobFactory;
        return $this;
    }

    /**
     * @param string $jobName
     * @return WorkerProviderInterface|null
     * @throws UnsupportedJobException
     */
    public function getWorkerProviderFor($jobName)
    {
        if ($factory = $this->findWorkerFactoryFor($jobName)) {
            return $factory;
        }
        throw new UnsupportedJobException("No factory available for {$jobName}");
    }

    /**
     * @param $jobName
     * @return bool
     */
    public function hasWorkerProviderFor($jobName)
    {
        return $this->findWorkerFactoryFor($jobName) !== null;
    }

    /**
     * @param $jobName
     * @return WorkerProviderInterface|null
     */
    protected function findWorkerFactoryFor($jobName)
    {
        foreach ($this->factories as $factory) {
            if ($factory->hasWorkerFor($jobName)) {
                return $factory;
            }
        }
        return null;
    }
}


text:
SPEC_BEGIN(CYRDispatchUntilSpec)

describe(@"dispatch_until", ^{

    context(@"while using dispatch_until", ^{

        context(@"when executing a valid task with no error", ^{

            __block NSError *theError = nil;
            __block NSArray *theResults = nil;
            __block BOOL completionBlockCalled = NO;

            NSTimeInterval testLength = 1;
            __block NSTimeInterval start = [NSDate date].timeIntervalSince1970;
            __block NSTimeInterval duration = 0;

            beforeAll(^{
                CYRTask task1 = dispatch_task_create(^(CYRCallback callback, void *context) {
                    return callback(nil, @"one");
                });

                dispatch_until(^BOOL{
                    static BOOL pass = NO;
                    static dispatch_once_t onceToken;
                    dispatch_once(&onceToken, ^{
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(testLength * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            pass = YES;
                        });

                    });

                    return pass;
                }, task1, ^(NSError *error, NSArray *results) {
                    completionBlockCalled = YES;
                    theError = error;
                    theResults = results;
                    duration = [NSDate date].timeIntervalSince1970 - start;
                });
            });

            it(@"should call the completion block", ^{
                [[expectFutureValue(theValue(completionBlockCalled)) shouldEventuallyBeforeTimingOutAfter(5)] equal:theValue(YES)];
            });

            it(@"duration should be greater tha or equal to the test length", ^{
                [[expectFutureValue(theValue(duration)) shouldEventuallyBeforeTimingOutAfter(5)] beGreaterThanOrEqualTo:theValue(1)];
            });

            it(@"should have one item in the results array", ^{
                [[expectFutureValue(theValue(theResults.count)) shouldEventuallyBeforeTimingOutAfter(5)] equal:theValue(1)];
            });
        });

        context(@"when executing a valid task that throws an error", ^{

            __block NSError *theError = nil;
            __block NSArray *theResults = nil;
            __block BOOL completionBlockCalled = NO;

            __block NSError *error = [NSError errorWithDomain:@"kTestDomain" code:100 userInfo:@{}];

            beforeAll(^{
                CYRTask task1 = dispatch_task_create(^(CYRCallback callback, void *context) {

                    return callback(error, @"one");
                });

                dispatch_until(^BOOL{
                    static BOOL pass = NO;

                    return pass;
                }, task1, ^(NSError *error, NSArray *results) {
                    completionBlockCalled = YES;
                    theError = error;
                    theResults = results;
                });
            });

            it(@"should call the completion block", ^{
                [[expectFutureValue(theValue(completionBlockCalled)) shouldEventuallyBeforeTimingOutAfter(5)] equal:theValue(YES)];
            });

            it(@"should have a valid error object", ^{
                [[expectFutureValue(theError) shouldEventually] equal:error];
            });

            it(@"should have one item in the results array", ^{
                [[expectFutureValue(theValue(theResults.count)) shouldEventuallyBeforeTimingOutAfter(5)] equal:theValue(1)];
            });
        });
    });
});

SPEC_END


text:
module Jobs
  class DashboardStats < Jobs::Scheduled
    every 30.minutes

    def execute(args)
      problems_started_at = AdminDashboardData.problems_started_at
      if problems_started_at && problems_started_at < 2.days.ago
        # If there have been problems reported on the dashboard for a while,
        # send a message to admins no more often than once per week.
        GroupMessage.create(Group[:admins].name, :dashboard_problems, {limit_once_per: 7.days.to_i})
      end

      AdminDashboardData.refresh_stats
    end
  end
end


text:
package com.gentics.mesh.shared;

/**
 * Set of various shared keys which are used to store data in various areas. (e.g. in the context data).
 */
public final class SharedKeys {

	public static final String TOKEN_COOKIE_KEY = "mesh.token";

	public static final String PROJECT_CONTEXT_KEY = "mesh.project";

	public static final String API_VERSION_CONTEXT_KEY = "apiversion";
}


text:
<?php

namespace ZendTest\Mvc\Service\TestAsset;

use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerInterface;

class EventManagerAwareObject implements EventManagerAwareInterface
{
    public static $defaultEvents;

    protected $events;

    /**
     * @param EventManagerInterface $events
     */
    public function setEventManager(EventManagerInterface $events)
    {
        $this->events = $events;
    }

    /**
     * @return EventManagerInterface
     */
    public function getEventManager()
    {
        if (!$this->events instanceof EventManagerInterface
            && static::$defaultEvents instanceof EventManagerInterface
        ) {
            $this->setEventManager(static::$defaultEvents);
        }
        return $this->events;
    }
}


text:
/*
 * Powered By wufuwei
 */

package com.osp.biz.service;

import java.util.*;

import javacommon.base.*;

import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

/**
 * @author David Wu email:oradb(a)163.com
 * @version 1.0
 * @since 1.0
 */

import com.osp.biz.model.OspTraderesult;

public interface IOspTraderesultService {

	 public OspTraderesult getById(java.lang.Integer id);

	public void save(OspTraderesult entity);

	public void removeById(java.lang.Integer id);

	public void update(OspTraderesult entity);

	public boolean isUnique(OspTraderesult entity, String uniquePropertyNames) ;

	public Long pageSelectCount(OspTraderesult entity);

	public Page findByPageRequest(PageRequest pr);

	public List<OspTraderesult> findAll();

	public void updateDynamic(OspTraderesult entity);

	public List<OspTraderesult> findByDynamicWhere(OspTraderesult entity);

	public void saveOrUpdate(OspTraderesult entity);

}


text:
package esa.obeos.metadataeditor.model.api;

public enum ModelType
{
    GMD,
    GMI,
    Invalid
}