text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../" />

		<link type="text/css" rel="stylesheet" href="page.css" />

[name]

Represents a boundary box in 3d space.

Constructor

[name]([page:Vector3 min], [page:Vector3 max])

		min -- Lower (x, y, z) boundary of the box.

		max -- Upper (x, y, z) boundary of the box.

		Creates a box bounded by min and max.

Properties

[property:Vector3 min]

		Lower (x, y, z) boundary of this box.

[property:Vector3 max]

		Upper (x, y, z) boundary of this box.

Methods

[method:Box3 set]([page:Vector3 min], [page:Vector3 max]) [page:Box3 this]

		min -- Lower (x, y, z) boundary of the box.

		max -- Upper (x, y, z) boundary of the box.

		Sets the lower and upper (x, y, z) boundaries of this box.

[method:Box3 applyMatrix4]([page:Matrix4 matrix]) [page:Box3 this]

		matrix -- The [page:Matrix4] to apply

		Transforms this Box3 with the supplied matrix.

[method:Vector3 clampPoint]([page:Vector3 point], [page:Vector3 optionalTarget])

		point -- Position to clamp.

		optionalTarget -- If specified, the clamped result will be copied here.

		Clamps *point* within the bounds of this box.

[method:Boolean intersectsBox]([page:Box3 box])

		box -- Box to check for intersection against.

		Determines whether or not this box intersects *box*.

[method:Box3 setFromPoints]([page:Array points]) [page:Box3 this]

		points -- Set of points that the resulting box will envelop.

		Sets the upper and lower bounds of this box to include all of the points in *points*.

[method:Box3 setFromObject]([page:Object3D object]) [page:Box3 this]

		object -- [page:Object3D] to compute the bounding box for.

		Computes the world-axis-aligned bounding box of an object (including its children),
		accounting for both the object's, and childrens', world transforms

[method:Vector3 size]([page:Vector3 optionalTarget])

		optionalTarget -- If specified, the result will be copied here.

		Returns the width, height, and depth of this box.

[method:Box3 union]([page:Box3 box])

		box -- Box that will be unioned with this box.

		Unions this box with *box* setting the upper bound of this box to the greater of the
		two boxes' upper bounds and the lower bound of this box to the lesser of the two boxes'
		lower bounds.

[method:Vector3 getParameter]([page:Vector3 point], [page:Vector3 optionalTarget])

		point -- Point to parametrize.
		optionalTarget -- If specified, the result will be copied here.

		Returns point as a proportion of this box's width and height.

[method:Box3 intersect]([page:Box3 box]) [page:Box3 this]

		box -- Box to intersect with.

		Returns the intersection of this and *box*, setting the upper bound of this box to the lesser

		of the two boxes' upper bounds and the lower bound of this box to the greater of the two boxes'

		lower bounds.

[method:Boolean containsBox]([page:Box3 box])

		box -- Box to test for inclusion.

		Returns true if this box includes the entirety of *box*. If this and *box* overlap exactly,

		this function also returns true.

[method:Boolean containsPoint]([page:Vector3 point])

		point -- [page:Vector3] to check for inclusion.

		Returns true if the specified point lies within the boundaries of this box.

[method:Box3 translate]([page:Vector3 offset]) [page:Box3 this]

		offset -- Direction and distance of offset.

		Adds *offset* to both the upper and lower bounds of this box, effectively moving this box

		*offset* units in 3D space.

[method:Boolean empty]()

		Returns true if this box includes zero points within its bounds.

		Note that a box with equal lower and upper bounds still includes one point, the
		one both bounds share.

[method:Box3 clone]()

		Returns a copy of this box.

[method:Boolean equals]([page:Box3 box])

		box -- Box to compare.

		Returns true if this box and *box* share the same lower and upper bounds.

[method:Box3 expandByPoint]([page:Vector3 point]) [page:Box3 this]

		point -- Point that should be included in the box.

		Expands the boundaries of this box to include *point*.

[method:Box3 expandByScalar]([page:float scalar]) [page:Box3 this]

		scalar -- Distance to expand.

		Expands each dimension of the box by *scalar*. If negative, the dimensions of the box

		will be contracted.

[method:Box3 expandByVector]([page:Vector3 vector]) [page:Box3 this]

		vector -- Amount to expand this box in each dimension.

		Expands this box equilaterally by *vector*. The width of this box will be
		expanded by the x component of *vector* in both directions. The height of
		this box will be expanded by the y component of *vector* in both directions.
		The depth of this box will be expanded by the z component of *vector* in
		both directions.

[method:Box3 copy]([page:Box3 box]) [page:Box3 this]

		box -- Box to copy.

		Copies the values of *box* to this box.

[method:Box3 makeEmpty]() [page:Box3 this]

		Makes this box empty.

[method:Vector3 center]([page:Vector3 optionalTarget])

		optionalTarget -- If specified, the result will be copied here.

		Returns the center point of this box.

[method:Sphere getBoundingSphere]([page:Sphere optionalTarget])

		optionalTarget -- [page:Sphere] to optionally set the result to.

		Gets a sphere that bounds the box.

[method:Float distanceToPoint]([page:Vector3 point])

		point -- Point to measure distance to.

		Returns the distance from any edge of this box to the specified point.

		If the point lies inside of this box, the distance will be 0.

[method:Box3 setFromCenterAndSize]([page:Vector3 center], [page:Vector3 size]) [page:Box3 this]

		center -- Desired center position of the box.

		size -- Desired x and y dimensions of the box.

		Centers this box on *center* and sets this box's width and height to the values specified
		in *size*.

Source

		[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]


text:
module WitBot
  class EntityModelProxy < HashWithIndifferentAccess
    attr_reader :raw

    def initialize(raw_entities)
      @raw = raw_entities

      super Hash[raw_entities.map do |(role, all)|
        all = all.map do |data|
          entity_name = data[:entity] || role
          entity = WitModel::Entity.find(entity_name, create: false)
          entity.model role, data
        end

        data = all.length == 1 ? all.first : all

        create_getter role

        [role, data]
      end]
    end

    def method_missing(*_)
      nil
    end

    private
    def create_getter(var)
      self.class.send(:define_method, var, -> { self[var] })
    end
  end
  class EntityModel
    attr_accessor :all
    attr_reader :entity, :role, :raw, :value

    def initialize(entity, role, raw)
      @entity = entity
      @role = role
      @raw = raw.with_indifferent_access

      @value = case @raw[:type] && @raw[:type].to_sym
               when :value
                 @raw[:value].to_s
               else
                 @raw[:value]
               end

      @others = []
    end

    def others
      all - [self]
    end

    def ==(other)
      self.entity == other.entity && self.value == other.value
    end

    def to_s
      value.to_s
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
Roslyn-Overview
===============

Overview of the .NET Compiler Platform


text:
namespace ash {

namespace {

// Size of black border at bottom (or side) of shelf.
const int kNumBlackPixels = 3;

}  // namespace

// The contents view of the Shelf. This view contains ShelfView and
// sizes it to the width of the shelf minus the size of the status area.
class ShelfWidget::DelegateView : public views::WidgetDelegate,
                                  public views::AccessiblePaneView,
                                  public ShelfBackgroundAnimatorObserver {
 public:
  DelegateView(WmShelf* wm_shelf, ShelfWidget* shelf);
  ~DelegateView() override;

  void set_focus_cycler(FocusCycler* focus_cycler) {
    focus_cycler_ = focus_cycler;
  }
  FocusCycler* focus_cycler() { return focus_cycler_; }

  ui::Layer* opaque_background() { return &opaque_background_; }
  ui::Layer* opaque_foreground() { return &opaque_foreground_; }

  void SetParentLayer(ui::Layer* layer);

  // views::View overrides:
  void OnPaintBackground(gfx::Canvas* canvas) override;

  // views::WidgetDelegateView overrides:
  views::Widget* GetWidget() override { return View::GetWidget(); }
  const views::Widget* GetWidget() const override { return View::GetWidget(); }

  bool CanActivate() const override;
  void ReorderChildLayers(ui::Layer* parent_layer) override;
  // This will be called when the parent local bounds change.
  void OnBoundsChanged(const gfx::Rect& old_bounds) override;

  // ShelfBackgroundAnimatorObserver:
  void UpdateShelfOpaqueBackground(int alpha) override;
  void UpdateShelfAssetBackground(int alpha) override;

 private:
  WmShelf* wm_shelf_;
  ShelfWidget* shelf_widget_;
  FocusCycler* focus_cycler_;
  int asset_background_alpha_;
  // TODO(bruthig): Remove opaque_background_ (see https://crbug.com/621551).
  // A black background layer which is shown when a maximized window is visible.
  ui::Layer opaque_background_;
  // A black foreground layer which is shown while transitioning between users.
  // Note: Since the back- and foreground layers have different functions they
  // can be used simultaneously - so no repurposing possible.
  ui::Layer opaque_foreground_;

  DISALLOW_COPY_AND_ASSIGN(DelegateView);
};

ShelfWidget::DelegateView::DelegateView(WmShelf* wm_shelf,
                                        ShelfWidget* shelf_widget)
    : wm_shelf_(wm_shelf),
      shelf_widget_(shelf_widget),
      focus_cycler_(nullptr),
      asset_background_alpha_(0),
      opaque_background_(ui::LAYER_SOLID_COLOR),
      opaque_foreground_(ui::LAYER_SOLID_COLOR) {
  DCHECK(wm_shelf_);
  DCHECK(shelf_widget_);
  SetLayoutManager(new views::FillLayout());
  set_allow_deactivate_on_esc(true);
  opaque_background_.SetColor(SK_ColorBLACK);
  opaque_background_.SetBounds(GetLocalBounds());
  opaque_background_.SetOpacity(0.0f);
  opaque_foreground_.SetColor(SK_ColorBLACK);
  opaque_foreground_.SetBounds(GetLocalBounds());
  opaque_foreground_.SetOpacity(0.0f);
}

ShelfWidget::DelegateView::~DelegateView() {}

void ShelfWidget::DelegateView::SetParentLayer(ui::Layer* layer) {
  layer->Add(&opaque_background_);
  layer->Add(&opaque_foreground_);
  ReorderLayers();
}

void ShelfWidget::DelegateView::OnPaintBackground(gfx::Canvas* canvas) {
  if (MaterialDesignController::IsShelfMaterial())
    return;

  ui::ResourceBundle* rb = &ui::ResourceBundle::GetSharedInstance();
  gfx::ImageSkia shelf_background =
      *rb->GetImageSkiaNamed(IDR_ASH_SHELF_BACKGROUND);
  const bool horizontal = wm_shelf_->IsHorizontalAlignment();
  if (!horizontal) {
    shelf_background = gfx::ImageSkiaOperations::CreateRotatedImage(
        shelf_background, wm_shelf_->GetAlignment() == SHELF_ALIGNMENT_LEFT
                              ? SkBitmapOperations::ROTATION_90_CW
                              : SkBitmapOperations::ROTATION_270_CW);
  }
  const gfx::Rect dock_bounds(
      shelf_widget_->shelf_layout_manager()->dock_bounds());
  SkPaint paint;
  paint.setAlpha(asset_background_alpha_);
  canvas->DrawImageInt(
      shelf_background, 0, 0, shelf_background.width(),
      shelf_background.height(),
      (horizontal && dock_bounds.x() == 0 && dock_bounds.width() > 0)
          ? dock_bounds.width()
          : 0,
      0, horizontal ? width() - dock_bounds.width() : width(), height(), false,
      paint);
  if (horizontal && dock_bounds.width() > 0) {
    // The part of the shelf background that is in the corner below the docked
    // windows close to the work area is an arched gradient that blends
    // vertically oriented docked background and horizontal shelf.
    gfx::ImageSkia shelf_corner = *rb->GetImageSkiaNamed(IDR_ASH_SHELF_CORNER);
    if (dock_bounds.x() == 0) {
      shelf_corner = gfx::ImageSkiaOperations::CreateRotatedImage(
          shelf_corner, SkBitmapOperations::ROTATION_90_CW);
    }
    canvas->DrawImageInt(
        shelf_corner, 0, 0, shelf_corner.width(), shelf_corner.height(),
        dock_bounds.x() > 0 ? dock_bounds.x() : dock_bounds.width() - height(),
        0, height(), height(), false, paint);
    // The part of the shelf background that is just below the docked windows
    // is drawn using the last (lowest) 1-pixel tall strip of the image asset.
    // This avoids showing the border 3D shadow between the shelf and the
    // dock.
    canvas->DrawImageInt(shelf_background, 0, shelf_background.height() - 1,
                         shelf_background.width(), 1,
                         dock_bounds.x() > 0 ? dock_bounds.x() + height() : 0,
                         0, dock_bounds.width() - height(), height(), false,
                         paint);
  }
  gfx::Rect black_rect =
      shelf_widget_->shelf_layout_manager()->SelectValueForShelfAlignment(
          gfx::Rect(0, height() - kNumBlackPixels, width(), kNumBlackPixels),
          gfx::Rect(0, 0, kNumBlackPixels, height()),
          gfx::Rect(width() - kNumBlackPixels, 0, kNumBlackPixels, height()));
  canvas->FillRect(black_rect, SK_ColorBLACK);
}

bool ShelfWidget::DelegateView::CanActivate() const {
  // Allow to activate as fallback.
  if (shelf_widget_->activating_as_fallback_)
    return true;
  // Allow to activate from the focus cycler.
  if (focus_cycler_ && focus_cycler_->widget_activating() == GetWidget())
    return true;
  // Disallow activating in other cases, especially when using mouse.
  return false;
}

void ShelfWidget::DelegateView::ReorderChildLayers(ui::Layer* parent_layer) {
  views::View::ReorderChildLayers(parent_layer);
  parent_layer->StackAtBottom(&opaque_background_);
  parent_layer->StackAtTop(&opaque_foreground_);
}

void ShelfWidget::DelegateView::OnBoundsChanged(const gfx::Rect& old_bounds) {
  opaque_background_.SetBounds(GetLocalBounds());
  opaque_foreground_.SetBounds(GetLocalBounds());
}

void ShelfWidget::DelegateView::UpdateShelfOpaqueBackground(int alpha) {
  const float kMaxAlpha = 255.0f;
  opaque_background_.SetOpacity(alpha / kMaxAlpha);
}

void ShelfWidget::DelegateView::UpdateShelfAssetBackground(int alpha) {
  asset_background_alpha_ = alpha;
  SchedulePaint();
}

ShelfWidget::ShelfWidget(WmWindow* shelf_container, WmShelf* wm_shelf)
    : wm_shelf_(wm_shelf),
      status_area_widget_(nullptr),
      delegate_view_(new DelegateView(wm_shelf, this)),
      shelf_view_(nullptr),
      background_animator_(SHELF_BACKGROUND_DEFAULT, wm_shelf_),
      activating_as_fallback_(false) {
  background_animator_.AddObserver(this);
  background_animator_.AddObserver(delegate_view_);

  views::Widget::InitParams params(
      views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  params.name = "ShelfWidget";
  params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
  params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  params.delegate = delegate_view_;
  shelf_container->GetRootWindowController()
      ->ConfigureWidgetInitParamsForContainer(
          this, shelf_container->GetShellWindowId(), &params);
  Init(params);

  // The shelf should not take focus when initially shown.
  set_focus_on_creation(false);
  SetContentsView(delegate_view_);
  delegate_view_->SetParentLayer(GetLayer());

  shelf_layout_manager_ = new ShelfLayoutManager(this, wm_shelf_);
  shelf_layout_manager_->AddObserver(this);
  shelf_container->SetLayoutManager(base::WrapUnique(shelf_layout_manager_));
  background_animator_.PaintBackground(
      shelf_layout_manager_->GetShelfBackgroundType(),
      BACKGROUND_CHANGE_IMMEDIATE);

  views::Widget::AddObserver(this);
}

ShelfWidget::~ShelfWidget() {
  // Must call Shutdown() before destruction.
  DCHECK(!status_area_widget_);
  WmShell::Get()->focus_cycler()->RemoveWidget(this);
  SetFocusCycler(nullptr);
  RemoveObserver(this);
  background_animator_.RemoveObserver(delegate_view_);
  background_animator_.RemoveObserver(this);
}

void ShelfWidget::CreateStatusAreaWidget(WmWindow* status_container) {
  DCHECK(status_container);
  DCHECK(!status_area_widget_);
  // TODO(jamescook): Move ownership to RootWindowController.
  status_area_widget_ = new StatusAreaWidget(status_container, wm_shelf_);
  status_area_widget_->CreateTrayViews();
  if (WmShell::Get()->GetSessionStateDelegate()->IsActiveUserSessionStarted())
    status_area_widget_->Show();
  WmShell::Get()->focus_cycler()->AddWidget(status_area_widget_);
  background_animator_.AddObserver(status_area_widget_);
  status_container->SetLayoutManager(
      base::MakeUnique<StatusAreaLayoutManager>(this));
}

void ShelfWidget::SetPaintsBackground(
    ShelfBackgroundType background_type,
    BackgroundAnimatorChangeType change_type) {
  background_animator_.PaintBackground(background_type, change_type);
}

ShelfBackgroundType ShelfWidget::GetBackgroundType() const {
  return background_animator_.target_background_type();
}

void ShelfWidget::HideShelfBehindBlackBar(bool hide, int animation_time_ms) {
  if (IsShelfHiddenBehindBlackBar() == hide)
    return;

  ui::Layer* opaque_foreground = delegate_view_->opaque_foreground();
  float target_opacity = hide ? 1.0f : 0.0f;
  std::unique_ptr<ui::ScopedLayerAnimationSettings> opaque_foreground_animation;
  opaque_foreground_animation.reset(
      new ui::ScopedLayerAnimationSettings(opaque_foreground->GetAnimator()));
  opaque_foreground_animation->SetTransitionDuration(
      base::TimeDelta::FromMilliseconds(animation_time_ms));
  opaque_foreground_animation->SetPreemptionStrategy(
      ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS);

  opaque_foreground->SetOpacity(target_opacity);
}

bool ShelfWidget::IsShelfHiddenBehindBlackBar() const {
  return delegate_view_->opaque_foreground()->GetTargetOpacity() != 0.0f;
}

ShelfAlignment ShelfWidget::GetAlignment() const {
  return wm_shelf_->GetAlignment();
}

void ShelfWidget::OnShelfAlignmentChanged() {
  shelf_view_->OnShelfAlignmentChanged();
  status_area_widget_->SetShelfAlignment(GetAlignment());
  delegate_view_->SchedulePaint();
}

ShelfView* ShelfWidget::CreateShelfView() {
  DCHECK(!shelf_view_);

  shelf_view_ =
      new ShelfView(WmShell::Get()->shelf_model(),
                    WmShell::Get()->shelf_delegate(), wm_shelf_, this);
  shelf_view_->Init();
  GetContentsView()->AddChildView(shelf_view_);
  return shelf_view_;
}

void ShelfWidget::PostCreateShelf() {
  SetFocusCycler(WmShell::Get()->focus_cycler());

  // Ensure the newly created |shelf_| gets current values.
  background_animator_.Initialize(this);

  // TODO(jamescook): The IsActiveUserSessionStarted() check may not be needed
  // because the shelf is only created after the first user session is active.
  // The ShelfView seems to always be visible after login. At the lock screen
  // the shelf is hidden because its container is hidden. During auto-hide it is
  // hidden because ShelfWidget is transparent. Some of the ShelfView visibility
  // code could be simplified. http://crbug.com/674773
  shelf_view_->SetVisible(
      WmShell::Get()->GetSessionStateDelegate()->IsActiveUserSessionStarted());
  shelf_layout_manager_->LayoutShelf();
  shelf_layout_manager_->UpdateAutoHideState();
  Show();
}

bool ShelfWidget::IsShelfVisible() const {
  return shelf_view_ && shelf_view_->visible();
}

bool ShelfWidget::IsShowingAppList() const {
  return GetAppListButton() && GetAppListButton()->is_showing_app_list();
}

bool ShelfWidget::IsShowingContextMenu() const {
  return shelf_view_ && shelf_view_->IsShowingMenu();
}

bool ShelfWidget::IsShowingOverflowBubble() const {
  return shelf_view_ && shelf_view_->IsShowingOverflowBubble();
}

void ShelfWidget::SetFocusCycler(FocusCycler* focus_cycler) {
  delegate_view_->set_focus_cycler(focus_cycler);
  if (focus_cycler)
    focus_cycler->AddWidget(this);
}

FocusCycler* ShelfWidget::GetFocusCycler() {
  return delegate_view_->focus_cycler();
}

void ShelfWidget::Shutdown() {
  // Shutting down the status area widget may cause some widgets (e.g. bubbles)
  // to close, so uninstall the ShelfLayoutManager event filters first. Don't
  // reset the pointer until later because other widgets (e.g. app list) may
  // access it later in shutdown.
  if (shelf_layout_manager_)
    shelf_layout_manager_->PrepareForShutdown();

  if (status_area_widget_) {
    background_animator_.RemoveObserver(status_area_widget_);
    WmShell::Get()->focus_cycler()->RemoveWidget(status_area_widget_);
    status_area_widget_->Shutdown();
    status_area_widget_ = nullptr;
  }

  CloseNow();
}

void ShelfWidget::UpdateIconPositionForPanel(WmWindow* panel) {
  if (!shelf_view_)
    return;

  WmWindow* shelf_window = WmLookup::Get()->GetWindowForWidget(this);
  shelf_view_->UpdatePanelIconPosition(
      panel->GetIntProperty(WmWindowProperty::SHELF_ID),
      shelf_window->ConvertRectFromScreen(panel->GetBoundsInScreen())
          .CenterPoint());
}

gfx::Rect ShelfWidget::GetScreenBoundsOfItemIconForWindow(WmWindow* window) {
  // Window animations can be triggered during session restore before the shelf
  // view is created. In that case, return default empty bounds.
  if (!shelf_view_)
    return gfx::Rect();

  ShelfID id = window->GetIntProperty(WmWindowProperty::SHELF_ID);
  gfx::Rect bounds(shelf_view_->GetIdealBoundsOfItemIcon(id));
  gfx::Point screen_origin;
  views::View::ConvertPointToScreen(shelf_view_, &screen_origin);
  return gfx::Rect(screen_origin.x() + bounds.x(),
                   screen_origin.y() + bounds.y(), bounds.width(),
                   bounds.height());
}

AppListButton* ShelfWidget::GetAppListButton() const {
  return shelf_view_ ? shelf_view_->GetAppListButton() : nullptr;
}

app_list::ApplicationDragAndDropHost*
ShelfWidget::GetDragAndDropHostForAppList() {
  return shelf_view_;
}

void ShelfWidget::OnWidgetActivationChanged(views::Widget* widget,
                                            bool active) {
  activating_as_fallback_ = false;
  if (active)
    delegate_view_->SetPaneFocusAndFocusDefault();
  else
    delegate_view_->GetFocusManager()->ClearFocus();
}

void ShelfWidget::UpdateShelfItemBackground(int alpha) {
  if (shelf_view_)
    shelf_view_->UpdateShelfItemBackground(alpha);
}

void ShelfWidget::WillDeleteShelfLayoutManager() {
  shelf_layout_manager_->RemoveObserver(this);
  shelf_layout_manager_ = nullptr;
}

}  // namespace ash


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('periodicals', '0033_periodical_ordering'),
    ]

    operations = [
        migrations.AddField(
            model_name='publication',
            name='title_image',
            field=models.ImageField(null=True, upload_to=''),
        ),
    ]


text:
Rapport d'activité
==================

Un rapport d'activité permet d'enregistrer des informations durant l'exécution du code à différents niveaux. C'est-à-dire que l'on peut enregistrer tout ce qui se passe, le déroulement du programme et ainsi mieux comprendre ce qu'il se passe. Les niveaux sont une façon de dissocier les simples messages d'information des messages d'erreurs en passant par les alertes.

## Implémentation

Le rapport d'activités de Beluga est un objet contenant seulement des méthodes statiques. Il existe une méthode pour afficher le contenu du log ainsi que plusieurs méthodes permettant l'enregistrement d'un message.

Ci-dessous la liste des méthodes permettant d'enregistrer un message :

 * `public static function warn(msg : String)` : Enregistre un message d'alerte.
 * `public static function error(msg : String)` : Enregitre un message d'erreur.
 * `public static function info(msg : String)` : Enregistre un message d'information.
 * `public static function debug(msg : String)` : Enregistre un message de débogage.

### Exemple

Voici comment nous pouvons utiliser les rapports d'activité :

```haxe
	Log.warn("Message d'alerte");
	Log.flush(); //Écrit une ligne contenant "Message d'alerte"
```

## Limitations

La version actuelle du Log ne permet pas de filtrer les niveaux des logs à afficher. Normalement, on devrait pouvoir par exemple ignorer les messages peu important d'information si l'on rencontre un bug critique.


text:
time liquid -v -i . Data/Vector/Algorithms/Common.hs       > log.Common        2>&1
time liquid -v -i . Data/Vector/Algorithms/Radix.hs        > log.Radix         2>&1
time liquid -v -i . Data/Vector/Algorithms/Search.hs       > log.Search        2>&1
time liquid -v -i . Data/Vector/Algorithms/Optimal.hs      > log.Optimal       2>&1
time liquid -v -i . Data/Vector/Algorithms/Insertion.hs    > log.Insertion     2>&1
time liquid -v -i . Data/Vector/Algorithms/Heap.hs         > log.Heap          2>&1
time liquid -v -i . Data/Vector/Algorithms/Merge.hs        > log.Merge         2>&1
time liquid -v -i . Data/Vector/Algorithms/AmericanFlag.hs > log.AmericanFlag  2>&1
time liquid -v -i . Data/Vector/Algorithms/Intro.hs        > log.Intro         2>&1


text:
struct NetworkConditions {
  bool offline;
  double latency;
  double download_throughput;
  double upload_throughput;
};

#endif  // CHROME_TEST_CHROMEDRIVER_CHROME_NETWORK_CONDITIONS_H_


text:
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'home-container',
  styleUrls: [ './home.style.css' ],
  template: require('./home.tpl.html')
  //templateUrl: `./home.tpl.html`
})
export class Home {
  user = {
    password: '',
    email: ''
  };
  //The time to show the next photo
  private NextPhotoInterval:number = 5000;
  //Looping or not
  private noLoopSlides:boolean = false;

	images: Array<any> = [
    { "title": "We are covered", "url": "https://raw.githubusercontent.com/christiannwamba/angular2-carousel-component/master/images/covered.jpg" },
    { "title": "Generation Gap", "url": "https://raw.githubusercontent.com/christiannwamba/angular2-carousel-component/master/images/generation.jpg" },
    { "title": "Potter Me", "url": "https://raw.githubusercontent.com/christiannwamba/angular2-carousel-component/master/images/potter.jpg" },
    { "title": "Pre-School Kids", "url": "https://raw.githubusercontent.com/christiannwamba/angular2-carousel-component/master/images/preschool.jpg" },
    { "title": "Young Peter Cech", "url": "https://raw.githubusercontent.com/christiannwamba/angular2-carousel-component/master/images/soccer.jpg" }
  ];
  constructor( private router: Router) {}

   folders = [
    {
      name: 'Photos',
      updated: new Date('1/1/16'),
    },
    {
      name: 'Recipes',
      updated: new Date('1/17/16'),
    },
    {
      name: 'Work',
      updated: new Date('1/28/16'),
    }
  ];
  notes = [
    {
      name: 'Vacation Itinerary',
      updated: new Date('2/20/16'),
    },
    {
      name: 'Kitchen Remodel',
      updated: new Date('1/18/16'),
    }
  ];

}


text:
MySQL SQL Database Server Container Image
=========================================
MySQL 8.0 status: [![Docker Repository on Quay](https://quay.io/repository/centos7/mysql-80-centos7/status "Docker Repository on Quay")](https://quay.io/repository/centos7/mysql-80-centos7)

This repository contains Dockerfiles for MySQL images for OpenShift and general usage.
Users can choose between RHEL, Fedora and CentOS based images.

For more information about using these images with OpenShift, please see the
official [OpenShift Documentation](https://docs.okd.io/latest/using_images/db_images/mysql.html).

For more information about contributing, see
[the Contribution Guidelines](https://github.com/sclorg/welcome/blob/master/contribution.md).
For more information about concepts used in these container images, see the
[Landing page](https://github.com/sclorg/welcome).

Versions
--------
MySQL versions currently provided are:
* [MySQL 8.0](8.0)

RHEL versions currently supported are:
* RHEL7
* RHEL8

CentOS versions currently supported are:
* CentOS7

Installation
------------
Choose either the CentOS7 or RHEL7 based image:

*  **RHEL7 based image**

    These images are available in the [Red Hat Container Catalog](https://access.redhat.com/containers/#/registry.access.redhat.com/rhscl/mysql-80-rhel7).
    To download it run:

    ```
    $ podman pull registry.access.redhat.com/rhscl/mysql-80-rhel7
    ```

    To build a RHEL7 based MySQL image, you need to run Docker build on a properly
    subscribed RHEL machine.

    ```
    $ git clone --recursive https://github.com/sclorg/mysql-container.git
    $ cd mysql-container
    $ git submodule update --init
    $ make build TARGET=rhel7 VERSIONS=8.0
    ```

*  **CentOS7 based image**

    This image is available on DockerHub. To download it run:

    ```
    $ podman pull quay.io/centos7/mysql-80-centos7
    ```

    To build a CentOS based MySQL image from scratch, run:

    ```
    $ git clone --recursive https://github.com/sclorg/mysql-container.git
    $ cd mysql-container
    $ git submodule update --init
    $ make build TARGET=centos7 VERSIONS=8.0
    ```

For using other versions of MySQL, just replace the `8.0` value by particular version
in the commands above.

Note: while the installation steps are calling `podman`, you can replace any such calls by `docker` with the same arguments.

**Notice: By omitting the `VERSIONS` parameter, the build/test action will be performed
on all provided versions of MySQL, which must be specified in  `VERSIONS` variable.
This variable must be set to a list with possible versions (subdirectories).**

Usage
-----

For information about usage of Dockerfile for MySQL 8.0,
see [usage documentation](8.0).

Test
----

This repository also provides a test framework, which checks basic functionality
of the MySQL image.

Users can choose between testing MySQL based on a RHEL or CentOS image.

*  **RHEL based image**

    To test a RHEL7 based MySQL image, you need to run the test on a properly
    subscribed RHEL machine.

    ```
    $ cd mysql-container
    $ git submodule update --init
    $ make test TARGET=rhel7 VERSIONS=8.0
    ```

*  **CentOS based image**

    ```
    $ cd mysql-container
    $ git submodule update --init
    $ make test TARGET=centos7 VERSIONS=8.0
    ```

For using other versions of MySQL, just replace the `8.0` value by particular version
in the commands above.

**Notice: By omitting the `VERSIONS` parameter, the build/test action will be performed
on all provided versions of MySQL, which must be specified in  `VERSIONS` variable.
This variable must be set to a list with possible versions (subdirectories).**


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
    <appenders>
        <Console name="Console" target="SYSTEM_ERR">
            <PatternLayout pattern="[%d{DATE}][%-5p][%-25c][%t] %m%n"/>
        </Console>
        <RollingFile name="RollingFile" fileName="${sys:log4j.path}/${sys:webapp.profile}.log" filePattern="${sys:log4j.path}/${sys:webapp.profile}-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="[%d{DATE}][%-5p][%-25c][%t] %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            </Policies>
        </RollingFile>
        <RollingFile name="ErrorRollingFile" fileName="${sys:log4j.path}/error.log" filePattern="${sys:log4j.path}/error-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="[%d{DATE}][%-5p][%-25c][%t] %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            </Policies>
        </RollingFile>
        <RollingFile name="AccessRollingFile" fileName="${sys:log4j.path}/access.log" filePattern="${sys:log4j.path}/access-%d{yyyy-MM-dd}-%i.log.gz">
            <PatternLayout pattern="[%d{DATE}][%-5p][%-25c][%t] %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            </Policies>
        </RollingFile>
    </appenders>
    <Loggers>
        <Root level="${sys:log4j.level}">
            <AppenderRef ref="RollingFile" level="${sys:log4j.level}"/>
            <AppenderRef ref="Console" level="error"/>
        </Root>
        <Logger name="stderr" level="all">
            <AppenderRef ref="ErrorRollingFile"/>
        </Logger>
        <Logger name="stdout" level="all">
            <AppenderRef ref="ErrorRollingFile"/>
        </Logger>
        <Logger name="webapp.error" level="info">
            <AppenderRef ref="ErrorRollingFile"/>
        </Logger>
        <Logger name="webapp.access" level="info">
            <AppenderRef ref="AccessRollingFile"/>
        </Logger>
        <Logger name="com.google.inject" level="info">
            <AppenderRef ref="Console" />
        </Logger>
    </Loggers>
</configuration>


text:
package com.banadiga.concurrent.execute;

public interface IExecutor {
  void run();
}


text:
package org.apache.kerby.has.common;

import org.apache.kerby.config.ConfigKey;

public enum HasConfigKey implements ConfigKey {
    HTTP_HOST,
    HTTP_PORT,
    HTTPS_HOST,
    HTTPS_PORT,
    AUTH_TYPE("MySQL"),
    REALM,
    ENABLE_CONF,
    SSL_SERVER_CONF("/etc/has/ssl-server.conf"),
    SSL_CLIENT_CONF("/etc/has/ssl-client.conf"),
    SSL_CLIENT_CERT("/etc/has/cert-signed"),
    FILTER_AUTH_TYPE("kerberos"),
    KERBEROS_PRINCIPAL,
    KERBEROS_KEYTAB,
    KERBEROS_NAME_RULES,
    ADMIN_KEYTAB,
    ADMIN_KEYTAB_PRINCIPAL;

    private Object defaultValue;

    HasConfigKey() {
        this.defaultValue = null;
    }

    HasConfigKey(Object defaultValue) {
        this.defaultValue = defaultValue;
    }

    @Override
    public String getPropertyKey() {
        return name().toLowerCase();
    }

    @Override
    public Object getDefaultValue() {
        return this.defaultValue;
    }
}


text:
package code;

public class ConditionConstants {
	public static final String CHOOSE = "Choose";
	public enum Condition {

		ACCEPTABLE("A", "Used-Acceptable"),
		GOOD("G","Used-Good"),
		VERY_GOOD("VG","Used-VeryGood"),
		LIKE_NEW("LN", "Used-LikeNew"),
		NEW("N","New");

		private String readableName;
		private String fileName;

		Condition(String readableName, String fileName) {
			this.readableName = readableName;
			this.fileName = fileName;
		}

		public String getReadableName() {
			return readableName;
		}

		public String getFileName(){
			return fileName;
		}
	}
	public static String[] getReadableConditionsList(){
		String[] conditionsList = new String[Condition.values().length+1];
		for(int i=0; i<Condition.values().length; i++){
			conditionsList[i+1] = Condition.values()[i].readableName;
		}
		conditionsList[0] = CHOOSE;
		return conditionsList;
	}

	public static String getFileFromReadable(String readableName){
		for(Condition condition : Condition.values()){
			if(condition.getReadableName().equals(readableName))
				return condition.getFileName();
		}
		return "";
	}

	public static String getReadableFromFile(String fileName){
		for(Condition condition : Condition.values()){
			if(condition.getFileName().equals(fileName))
				return condition.getReadableName();
		}
		return "";
	}
}


text:
package org.kie.workbench.common.stunner.core.registry.impl;

import java.util.Collection;
import java.util.List;

import org.kie.workbench.common.stunner.core.diagram.Diagram;
import org.kie.workbench.common.stunner.core.registry.diagram.DiagramRegistry;

public abstract class AbstractDiagramListRegistry<D extends Diagram>
        extends AbstractDynamicRegistryWrapper<D, ListRegistry<D>>
        implements DiagramRegistry<D> {

    public AbstractDiagramListRegistry(final List<D> items) {
        super(new ListRegistry<>(Diagram::getName,
                                 items));
    }

    @Override
    public D getDiagramByUUID(final String uuid) {
        return getWrapped().getItemByKey(uuid);
    }

    @Override
    public void update(final D diagram) {
        final int index = getWrapped().indexOf(diagram);
        if (index != -1) {
            final boolean isRemoved = remove(diagram);
            if (isRemoved) {
                getWrapped().add(index,
                                 diagram);
            }
        } else {
            throw new RuntimeException("Diagram with uuid [" + diagram.getName() + "] cannot be updated as it does not exist.");
        }
    }

    public Collection<D> getItems() {
        return getWrapped().getItems();
    }

    public void clear() {
        getWrapped().clear();
    }
}


text:
#ifndef POST_EFFECTS_HPP_
#define POST_EFFECTS_HPP_

#include "internal.hpp"
#include "effect.hpp"

//! Render post effects
class post_effects {
public:

	post_effects(int width, int height, glm::vec4 clear_color);

	void bindAndClear() {
		mp_fbo_off->bind();
		::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	}

	void draw();

	inline int width() {
		return m_width;
	}

	inline int height() {
		return m_height;
	}

	effect * set_effects(effect * pfx) {
		mp_effects = pfx;
		mp_effects->build();
		mp_effects->get_program().get_global_uniform("screenMap")->set1i(15);
		return mp_effects;
	}

	effect *  get_effects() {
		return mp_effects;
	}

	void reshape(int width, int height);

protected:

	int m_width;

	int m_height;

	glpp::shared_texture_t mp_texture;

	glpp::frame_buffer * mp_fbo_off;

	effect * mp_effects;;

	glpp::shared_render_buffer_t mp_depth_renderbuffer;

	glpp::vertex_array * mp_tex_vao;

	glpp::buffer  * mp_tex_vbo;

	glm::vec4 m_clear_color;
};

#endif


text:
package org.dspace.app.xmlui.wing.element;

import java.util.ArrayList;
import java.util.List;

import org.dspace.app.xmlui.wing.AttributeMap;
import org.dspace.app.xmlui.wing.WingConstants;
import org.dspace.app.xmlui.wing.WingContext;
import org.dspace.app.xmlui.wing.WingException;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.ext.LexicalHandler;
import org.xml.sax.helpers.AttributesImpl;
import org.xml.sax.helpers.NamespaceSupport;

/**
 * A class representing a set of metadata about the user generating this page.
 *
 * @author Scott Phillips
 */
public class UserMeta extends AbstractWingElement implements
        WingMergeableElement, MetadataElement
{
    /** The name of the userMeta element */
    public static final String E_USER_META = "userMeta";

    /** The name of the authenticated attribute */
    public static final String A_AUTHENTICATED = "authenticated";

    /** Has this UserMeta element been merged? */
    private boolean merged = false;

    /** Has this user been authenticated? */
    private boolean authenticated = false;

    /** The metadata contents of this UserMeta element */
    private List<Metadata> metadatum = new ArrayList<Metadata>();

    /**
     * Construct a new userMeta
     *
     * @param context
     *            (Required) The context this element is contained in, such as
     *            where to route SAX events and what i18n catalogue to use.
     */
    protected UserMeta(WingContext context) throws WingException
    {
        super(context);
    }

    /**
     * Set the user described in the meta object as authenticated.
     *
     * @param authenticated
     *            (Required) True if the user is authenticated, false otherwise.
     */
    public void setAuthenticated(boolean authenticated)
    {
        this.authenticated = authenticated;
    }

    /**
	 * Add metadata about the requesting user to the document.
	 *
	 * @param element
	 *            (Required) The metadata element.
	 * @param qualifier
	 *            (May be null) The metadata qualifier.
	 * @param language
	 *            (May be null) The metadata's language
	 * @param allowMultiple
	 *            (Required) determine if multiple metadata elements with the same
	 *            element, qualifier and language are allowed.
	 * @return A new metadata
	 */
    public Metadata addMetadata(String element, String qualifier,
            String language, boolean allowMultiple) throws WingException
    {
        Metadata metadata = new Metadata(context, element, qualifier, language, allowMultiple);
        metadatum.add(metadata);
        return metadata;
    }

    /**
     * Add metadata about the requesting user to the document.
     *
     * @param element
     *            (Required) The metadata element.
     * @param qualifier
     *            (May be null) The metadata qualifier.
     * @param language
     *            (May be null) The metadata's language
     * @return A new metadata
     */
    public Metadata addMetadata(String element, String qualifier,
            String language) throws WingException
    {
    	 return addMetadata(element, qualifier, null, false);
    }

    /**
     * Add metadata about the requesting user to the document.
     *
     * @param element
     *            (Required) The metadata element.
     * @param qualifier
     *            (May be null) The metadata qualifier.
     * @return A new metadata
     */
    public Metadata addMetadata(String element, String qualifier)
            throws WingException
    {
        return addMetadata(element, qualifier, null, false);
    }

    /**
     * Add metadata about the requesting user to the document.
     *
     * @param element
     *            (Required) The metadata element.
     * @return A new metadata
     */
    public Metadata addMetadata(String element) throws WingException
    {
        return addMetadata(element, null, null, false);
    }

    /**
     * Determine if the given SAX event is a UserMeta element.
     *
     * @param namespace
     *            The element's name space
     * @param localName
     *            The local, unqualified, name for this element
     * @param qName
     *            The qualified name for this element
     * @param attributes
     *            The element's attributes
     * @return True if this WingElement is equivalent to the given SAX Event.
     */
    public boolean mergeEqual(String namespace, String localName, String qName,
            Attributes attributes) throws SAXException, WingException
    {

        if (!WingConstants.DRI.URI.equals(namespace))
        {
            return false;
        }

        if (!E_USER_META.equals(localName))
        {
            return false;
        }
        return true;
    }

    /**
     * Since metadata can not be merged there are no mergeable children. This
     * just return's null.
     *
     * @param namespace
     *            The element's name space
     * @param localName
     *            The local, unqualified, name for this element *
     * @param qName
     *            The qualified name for this element
     * @param attributes
     *            The element's attributes
     * @return The child element
     */
    public WingMergeableElement mergeChild(String namespace, String localName,
            String qName, Attributes attributes) throws SAXException,
            WingException
    {
    	// We don't merge our children but we do have one special optimization:
    	// if a metadata is already in the document and it is tagged as not allowing
    	// multiples then we do not add the new metadata to the document.

    	if (WingConstants.DRI.URI.equals(namespace) && Metadata.E_METADATA.equals(localName))
    	{
    		String element = attributes.getValue(Metadata.A_ELEMENT);
    		String qualifier = attributes.getValue(Metadata.A_QUALIFIER);
    		String language = attributes.getValue(Metadata.A_LANGUAGE);

    		List<Metadata> remove = new ArrayList<Metadata>();
    		for (Metadata metadata : metadatum)
    		{
    			if (metadata.equals(element,qualifier,language) && !metadata.allowMultiple())
    			{
    				remove.add(metadata);
    			}
    		}

    		// Remove all the metadata elements we found.
    		for (Metadata metadata : remove)
    		{
    			metadata.dispose();
    			metadatum.remove(metadata);
    		}
    	}

        return null;
    }

    /**
     * Inform this element that it is being merged with an existing element.
     */
    public Attributes merge(Attributes attributes) throws SAXException,
            WingException
    {
        this.merged = true;

        String mergedAuthenticated = attributes.getValue(A_AUTHENTICATED);

        if ("yes".equals(mergedAuthenticated))
        {
            // The user has already been set to authenticated.
            // Do nothing.
        }
        else if ("no".equals(mergedAuthenticated))
        {
            // No authenticated user yet.
            if (this.authenticated)
            {
                // Original no, but we've been told that the user is
                // authenticated.
                AttributesImpl attributesImpl = new AttributesImpl(attributes);
                int index = attributesImpl.getIndex(A_AUTHENTICATED);
                if (index >= 0)
                {
                	attributesImpl.setValue(index,"yes");
                }
                else
                {
	                attributesImpl.addAttribute("",
	                        A_AUTHENTICATED, A_AUTHENTICATED, "CDATA", "yes");
                }
                attributes = attributesImpl;
            }
        }
        else
        {
            // Authenticated value does not conform to the schema.
            AttributesImpl attributesImpl = new AttributesImpl(attributes);
            attributesImpl.addAttribute("", A_AUTHENTICATED,
                    A_AUTHENTICATED, "CDATA", (this.authenticated ? "yes" : "no"));
            attributes = attributesImpl;

        }

        return attributes;
    }

    /**
     * Translate this element into SAX events.
     *
     * @param contentHandler
     *            (Required) The registered contentHandler where SAX events
     *            should be routed too.
     * @param lexicalHandler
     *            (Required) The registered lexicalHandler where lexical
     *            events (such as CDATA, DTD, etc) should be routed too.
     * @param namespaces
     *            (Required) SAX Helper class to keep track of namespaces able
     *            to determine the correct prefix for a given namespace URI.
     */
    public void toSAX(ContentHandler contentHandler, LexicalHandler lexicalHandler,
            NamespaceSupport namespaces) throws SAXException
    {
        if (!merged)
        {
            AttributeMap attributes = new AttributeMap();
            if (authenticated)
            {
                attributes.put(A_AUTHENTICATED, "yes");
            }
            else
            {
                attributes.put(A_AUTHENTICATED, "no");
            }
            startElement(contentHandler, namespaces, E_USER_META, attributes);
        }

        for (Metadata metadata : metadatum)
        {
            metadata.toSAX(contentHandler, lexicalHandler, namespaces);
        }

        if (!merged)
        {
            endElement(contentHandler, namespaces, E_USER_META);
        }
    }

    /**
     * dispose
     */
    public void dispose()
    {
        for (AbstractWingElement content : metadatum)
        {
            content.dispose();
        }
        metadatum.clear();
        metadatum = null;
        super.dispose();
    }
}


text:
package com.hp.hpl.jena.rdf.listeners;

import com.hp.hpl.jena.rdf.model.*;

import java.util.*;

/**
    A listener that filters all its listening down to the single-statement level. Users of this
    class override addedStatement(Statement) and
    removedStatement(Statement).
 	@author kers
*/
public class StatementListener implements ModelChangedListener
    {
    /**
        Override this to listen to all incoming added statements
    */
    @Override
    public void addedStatement( Statement s ) {}
    /**
        Override this to listen to all incoming removed statements
    */
    @Override
    public void removedStatement( Statement s ) {}
/* */
    @Override
    public void addedStatements( Statement [] statements )
        { for (int i = 0; i < statements.length; i += 1) addedStatement( statements[i] ); }
    @Override
    public void addedStatements( List<Statement> statements )
        { for (int i = 0; i < statements.size(); i += 1) addedStatement( statements.get(i) ); }
    @Override
    public void addedStatements( StmtIterator statements )
        { while (statements.hasNext()) addedStatement( statements.nextStatement() ); }
    @Override
    public void addedStatements( Model m )
        { addedStatements( m.listStatements() ); }
    @Override
    public void removedStatements( Statement [] statements )
        { for (int i = 0; i < statements.length; i += 1) removedStatement( statements[i] ); }
    @Override
    public void removedStatements( List<Statement> statements )
        { for (int i = 0; i < statements.size(); i += 1) removedStatement( statements.get(i) ); }
    @Override
    public void removedStatements( StmtIterator statements )
        { while (statements.hasNext()) removedStatement( statements.nextStatement() ); }
    @Override
    public void removedStatements( Model m )
        { removedStatements( m.listStatements() ); }
    @Override
    public void notifyEvent( Model m, Object event )
        {}
    }


text:
Title: Setting up your development environment
Added: v3.0.0
Last reviewed: 2019-10-18
---
# Setting up your development environment

The Maven Alfresco SDK is designed to work well with [Eclipse](https://www.eclipse.org/) and [IntelliJ IDEA](https://www.jetbrains.com/idea/).


text:
.. yadawia documentation master file, created by
   sphinx-quickstart on Sat Apr 29 01:10:02 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Yadawia
=======

.. toctree::
   :maxdepth: 2
   :caption: Contents:

.. _intro:

Introduction
------------
Built for CCIT's E-Business Fundementals course (IS371). Its idea is simple: customer-to-customer buying and selling of goods and services, if and only if those goods and services in question are handmade.

This documentation focuses on the technical side of things rather than the business side.

Quick summary of what people should be able to do with this platform:

    - Create, edit, and deactivate accounts.
    - Sell handmade products.
    - Buy handmade products.
    - Communicate special requests to sellers.
    - Search for products by their attributes.

The difference between this and a regular e-commerce platform to the user is the flexibility in making and receiving orders regarding schedules, requests, etc.

`Logo Credit`_.

Tools
-----
This project uses:

    - Flask (Python) for the back-end.
    - AWS S3 for image uploads.
    - PostgreSQL for the database.

Installation
------------
1. Clone the github repo.
::
  $ git clone https://github.com/blaringsilence/yadawia.git
  $ cd yadawia

2. Install virtualenv and activate it.
::
  $ pip install virtualenv
  $ virtualenv -p python3 venv
  $ . venv/bin/activate

3. Install requirements.
::
  $ pip install -r requirements.txt

4. Install PostgreSQL (see `download page`_) and create a user and a database.
::
  $ sudo -u postgres createuser -s $USER -P
  $ createdb -U $USER snowdonia

5. Set environment variables (if running locally, add them to your venv/bin/activate script as follows):
::
  export DATABASE_URL="postgresql+psycopg2://USER:PASSWORD@localhost/yadawia"
  export AWS_ACCESS_KEY_ID="YOUR/YOUR IAM USER'S AWS ACCESS KEY"
  export AWS_SECRET_ACCESS_KEY="YOUR/YOUR IAM USER'S SECRET ACCESS KEY"
  export S3_BUCKET="YOUR BUCKET NAME HERE"

6. Create the tables, then populate them with the initial values (chmod a+x FILENAME before executing if file does not have execution permissions).
::
  $ ./create_db.py
  $ ./populate_countries.py
  $ ./populate_currencies.py
  $ ./populate_reasons.py
  $ ./populate_categories.py
  $ ./populate_methods.py

7. Run the app.
::
  $ gunicorn yadawia:app

.. _docs:

Docs
----
.. automodule:: yadawia
  :members:

.. automodule:: yadawia.views
  :members:

.. automodule:: yadawia.classes
  :members:

.. automodule:: yadawia.helpers
  :members:

.. automodule:: yadawia.errorhandlers
  :members:

.. _Logo Credit: http://www.freepik.com
.. _download page: http://www.postgresql.org/download/


text:
require 'compo'

RSpec.shared_examples 'a URL finding' do
  let(:target) { Compo::Branches::Leaf.new }

  context 'when given a nil URL' do
    specify { expect { |b| proc.call(nil, &b) }.to raise_error }
  end

  shared_examples 'a successful finding' do
    it 'returns the correct resource' do
      expect { |b| proc.call(url, &b) }.to yield_with_args(target)
    end
  end

  shared_examples 'an unsuccessful finding' do
    specify do
      expect { |b| proc.call(url, &b) }.to raise_error(
        "Could not find resource: #{url}"
      )
    end
  end

  shared_examples 'an unsuccessful finding with custom error' do
    specify do
      mp = ->(_) { :a }
      expect { |b| proc.call(url, missing_proc: mp,  &b) }
        .to yield_with_args(:a)
    end
  end

  context 'when given a correct root but incorrect URL' do
    context 'using the default missing resource handler' do
      context 'when the URL has a leading slash' do
        it_behaves_like 'an unsuccessful finding' do
          let(:url) { "/#{incorrect_url}" }
        end
      end
      context 'when the URL has a trailing slash' do
        it_behaves_like 'an unsuccessful finding' do
          let(:url) { "#{incorrect_url}/" }
        end
      end
      context 'when the URL has a leading and trailing slash' do
        it_behaves_like 'an unsuccessful finding' do
          let(:url) { "/#{incorrect_url}/" }
        end
      end
      context 'when the URL has neither leading nor trailing slash' do
        it_behaves_like 'an unsuccessful finding' do
          let(:url) { "#{incorrect_url}" }
        end
      end
    end

    context 'using a custom error handler' do
      context 'when the URL has a leading slash' do
        it_behaves_like 'an unsuccessful finding with custom error' do
          let(:url) { "/#{incorrect_url}" }
        end
      end
      context 'when the URL has a trailing slash' do
        it_behaves_like 'an unsuccessful finding with custom error' do
          let(:url) { "#{incorrect_url}/" }
        end
      end
      context 'when the URL has a leading and trailing slash' do
        it_behaves_like 'an unsuccessful finding with custom error' do
          let(:url) { "/#{incorrect_url}/" }
        end
      end
      context 'when the URL has neither leading nor trailing slash' do
        it_behaves_like 'an unsuccessful finding with custom error' do
          let(:url) { "#{incorrect_url}" }
        end
      end
    end
  end

  context 'when given a correct root and URL' do
    context 'when the URL leads to a resource' do
      context 'when the URL has a leading slash' do
        it_behaves_like 'a successful finding' do
          let(:url) { "/#{correct_url}" }
        end
      end
      context 'when the URL has a trailing slash' do
        it_behaves_like 'a successful finding' do
          let(:url) { "#{correct_url}/" }
        end
      end
      context 'when the URL has a leading and trailing slash' do
        it_behaves_like 'a successful finding' do
          let(:url) { "/#{correct_url}/" }
        end
      end
      context 'when the URL has neither leading nor trailing slash' do
        it_behaves_like 'a successful finding' do
          let(:url) { "#{correct_url}" }
        end
      end
    end
  end
end


text:
package reignOfDKE;

import battlecode.common.GameActionException;
import battlecode.common.MapLocation;
import battlecode.common.RobotController;

public class Pastr extends AbstractRobotType {

	private double dHealth; // delta of health
	private double lastHealth;
	private boolean amIDead = false;

	public Pastr(RobotController rc) {
		super(rc);
	}

	@Override
	protected void act() throws GameActionException {
		double health = rc.getHealth();
		dHealth = lastHealth - health;
		lastHealth = health;
		if (dHealth > 0) {
			// health is decreasing
			if (!amIDead) {
				amIDead = true;
				Channel.announcePastrDeath(rc);
				Channel.broadcastSelfDestruction(rc, rc.getLocation());
				// rc.setIndicatorString(0, "I'm dead");
			}
		} else if (dHealth < 0) {
			// health is increasing
			if (amIDead) {
				amIDead = false;
				Channel.announceNewPastr(rc);
				Channel.broadcastSelfDestruction(rc, new MapLocation(-1, -1));
				// rc.setIndicatorString(0, "I'm alive");
			}
		}
	}

	@Override
	protected void init() throws GameActionException {
		lastHealth = rc.getHealth();

	}
}


text:
from http.server import BaseHTTPRequestHandler, HTTPServer
from http import cookies
from socketserver import ThreadingMixIn
import dataManagement
import time
import math

dataStor = None
_timeP = 0

def start(port, data):
    global dataStor
    dataStor = data
    serverAddress = ('', port)
    httpd = HTTPServerThread(serverAddress, HTTPHandler)
    httpd.serve_forever()

def timeF(lable):
    global _timeP
    timeR = math.floor(((time.perf_counter() - _timeP) * 1000000))
    print(lable + ": " + str(timeR))
    _timeP = time.perf_counter()
    return timeR

def timeCalibrate():
    global _timeP
    _timeP = time.perf_counter()

class HTTPHandler(BaseHTTPRequestHandler):

    content = "Server/Website/"
    defaultTitle = "Day of Sagittarius III"
    paths = {"home": "cHome", "user":None, "static":"cStatic", "sagittarius":"cSag"}
    mimes = {
        "jpg": "image/jpeg",
        "jpeg": "image/jpeg",
        "html": "text/html",
        "htm": "text/html",
        "txt": "text/plain",
        "png": "image/png",
        "gif": "image/gif",
        "css": "text/css",
        "js": "application/javascript",
        "json": "application/json",
        "mp4": "video/mp4",
        "ico": "image/x-icon",
        "ts": "application/typescript"}

    def do_HEAD(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.handleCookies()
        self.end_headers()
    def do_GET(self):
        #self.totalTime = 0
        #timeCalibrate()
        self.statusCode = 200
        self.mime = "text/html"
        self.sendCookies = True
        body = bytes(self.route(), "utf8")
        #self.totalTime += timeF("Body")
        self.send_response(self.statusCode)
        self.send_header("Content-type", self.mime)
        if self.sendCookies: self.handleCookies()
        #self.totalTime += timeF("Cookies")
        self.end_headers()
        self.wfile.write(body)
        #self.totalTime += timeF("Write")
        #print("Total: " + str(self.totalTime))
        #print()

    def handleCookies(self):
        global dataStor
        cook = cookies.SimpleCookie()
        if "Cookie" in self.headers:
            cook.load(self.headers["Cookie"])
            if "session" in cook:
                print("session")
                self.user = dataStor.getUser(cook["session"].value)
                if self.user != None:
                    print(self.user)
                    return
        user = dataStor.makeUser()
        cook["session"] = user.getSession()
        cook["session"]["path"] = "/"
        cook["session"]["max-age"] = 259200
        self.send_header("Set-Cookie", str(cook["session"])[12:])
        self.user = user

    def log_message(self, format, *args):
        return

    def route(self):
        path = self.path.split('/')
        if self.path == "/":
            return self.cHome()
        elif path[1] in self.paths:
            if len(path) == 2 or path[2] == "":
                return getattr(self, self.paths[path[1]])()
            else:
                return getattr(self, self.paths[path[1]])(path[2])
        else:
            self.statusCode = 404
            return self.cHome("error")

    def cHome(self, view = "index"):
        if view == "index":
            return self.layout(self.readFile("home/index.html"))
        elif view == "about":
            return self.layout(self.readFile("home/about.html"))
        else:
            fContent = self.readFile("home/error.html")
            if(self.statusCode == 200):
                self.statusCode = 403
            fContent = fContent.format(error = self.statusCode)
            return self.layout(fContent)

    def cSag(self, view = "game"):
        if view == "game":
            return self.layout(self.readFile("sagittarius/game.html"))
        else:
            return self.cHome("error")

    def cStatic(self, unused):
        self.sendCookies = False
        path = self.path[len("/"):]
        try:
            print(path + str(path.rindex(".") + 1))
            fContent = self.readFile(path)
            self.mime = self.mimes[path[path.rindex(".") + 1:]]
            return fContent
        except (IOError, KeyError) as e:
            print("error: " + path)
            return self.cHome("error")

    def readFile(self, fPath):
        with open(self.content + fPath) as f:
            fContent = f.read()
            f.close()
            return fContent

    def layout(self, pContent = None, pTitle = None):
        pTitle = pTitle or self.defaultTitle
        with open(self.content + "layout.html") as f:
                fLayout = f.read()
                f.close()
                fLayout = fLayout.format(title = pTitle, content = pContent)
                return fLayout

class HTTPServerThread(ThreadingMixIn, HTTPServer):
    '''Use this to handle concurent connections for now'''


text:
name: Bug report
about: Found a bug in our project? Create a report to help us improve.
labels: bug
---

<!-- Add enough information so we can understand your problem -->

```php
// Please add code examples if possible, so we can reproduce your steps
```


text:
<?php
namespace SubjectivePHP\Spl\Exceptions;

/**
 * Exception thrown if a resource such as a database record or file is not found.
 */
class NotFoundException extends \RuntimeException
{
}


text:
Tilecache API's
***************

You can also view the `NeuroData Tile API's <http://docs.neurodata.io/ndstore/api/tile_api.html>`_ which work similarly for `ndstore <http://docs.neurodata.io/ndstore/index.html>`_.

getSimpleTile
-------------

.. http:get:: (string:server_name)/ndtilecache/tilecache/(string:token_name)/(string:channel_name)/(string:slice_type)/(int:time)/(int:zvalue)/(int:ytile)_(int:xtile)_(int:resolution).png

   :synopsis: Get a 512x512 tile from the tilecache

   :param server_name: Server Name in NeuroData. In the general case this is ocp.me.
   :type server_name: string
   :param token_name: Token Name in NeuroData.
   :type token_name: string
   :param channel_name: Channel Name in NeuroData.
   :type channel_name: string
   :param slice_type: Type of Slice cutout. Can be xy/yz/xz
   :type slice_type: string
   :param time: Time value. *Optional*. Only possible in timeseries datasets.
   :type time: int
   :param zvalue: Zslice value.
   :type zvalue: int
   :param ytile: Y-Tile value. Each tile is 512x512.
   :type ytile: int
   :param xtile: X-Tile value. Each tile is 512x512.
   :type xtile: int
   :param resolution: Resolution value.
   :type resolution: int

   :statuscode 200: No error
   :statuscode 404: Error in the syntax or file format

   **Example Request**:

   .. sourcecode:: http

      GET  /ndtilecache/tilecache/kasthuri11/image/xy/1/1_1_4.png HTTP/1.1
      Host: openconnecto.me

   **Example Response**:

   .. sourcecode:: http

      HTTP/1.1 200 OK
      Content-Type: application/png

.. figure:: ../images/simple_image_tile.png
    :align: center
    :width: 512px
    :height: 512px

getMcfcTile
-----------

.. http:get:: (string:server_name)/ndtilecache/tilecache/mcfc/(string:token_name)/(string:channel_name):(string:color_name)/(string:slice_type)/(int:time)/(int:zvalue)/(int:ytile)_(int:xtile)_(int:resolution).png

   :synopsis: Get a 512x512 tile from the tilecache

   :param server_name: Server Name in NeuroData. In the general case this is ocp.me.
   :type server_name: string
   :param token_name: Token Name in NeuroData.
   :type token_name: string
   :param channel_name: Channel Name in NeuroData.
   :type channel_name: string
   :param color_name: Color Name. Can be 'C/M/Y/R/G/B'. *Optional* If Missing will default to "CMYRGB".
   :type color_name: string
   :param slice_type: Type of Slice cutout. Can be xy/yz/xz
   :type slice_type: string
   :param time: Time value. *Optional*. Only possible in timeseries datasets.
   :type time: int
   :param zvalue: Zslice value.
   :type zvalue: int
   :param ytile: Y-Tile value. Each tile is 512x512.
   :type ytile: int
   :param xtile: X-Tile value. Each tile is 512x512.
   :type xtile: int
   :param resolution: Resolution value.
   :type resolution: int

   :statuscode 200: No error
   :statuscode 404: Error in the syntax or file format

   **Example Request**:

   .. sourcecode:: http

      GET  /ndtilecache/tilecache/mcfc/Thy1eYFPBrain10/Grayscale/xy/500/0_0_3.png HTTP/1.1
      Host: openconnecto.me

   **Example Response**:

   .. sourcecode:: http

      HTTP/1.1 200 OK
      Content-Type: application/png

.. figure:: ../images/mcfc_image_tile.png
    :align: center
    :width: 512px
    :height: 512px

getVikingTile
-------------

.. http:get:: (string:server_name)/ndtilecache/tilecache/viking/(string:token_name)/volume/(string:channel_name)/(int:resolution)/X(int:xtile)_Y(int:xtile)_Z(int:zvalue).png

   :synopsis: Get a 512x512 tile from the tilecache

   :param server_name: Server Name in NeuroData. In the general case this is openconnecto.me.
   :type server_name: string
   :param token_name: Token Name in NeuroData.
   :type token_name: string
   :param channel_name: Channel Name in NeuroData.
   :type channel_name: string
   :param resolution: Resolution value.
   :type resolution: int
   :param xtile: X-Tile value. Each tile is 512x512.
   :type xtile: int
   :param ytile: Y-Tile value. Each tile is 512x512.
   :type ytile: int
   :param zvalue: Zslice value.
   :type zvalue: int

   :statuscode 200: No error
   :statuscode 404: Error in the syntax or file format

   **Example Request**:

   .. sourcecode:: http

      GET  /ndtilecache/tilecache/viking/kasthuri11/volume/image/4/X1_Y1_Z10.png HTTP/1.1
      Host: openconnecto.me

   **Example Response**:

   .. sourcecode:: http

      HTTP/1.1 200 OK
      Content-Type: application/png

.. figure:: ../images/viking_image_tile.png
    :align: center
    :width: 512px
    :height: 512px


text:
package in.thekreml.recaptcha;

import java.net.InetAddress;

/**
 * Defines a specification for a reCAPTCHA validation implementation
 */
public interface ReCaptchaValidator {
	/**
	 * Validate a given challenge and response for a given remote address
	 *
	 * @param challenge reCAPTCHA challenge field
	 * @param response reCAPTCHA response field
	 * @param remoteAddr Remote address associated with the validation request
	 * @return True if response was verified, false otherwise
	 */
	Boolean validate(String challenge, String response, InetAddress remoteAddr);
}


text:
set(ENV{CC}  clang)
set(ENV{CXX} clang++)
set(ENV{FC}  gfortran-11)

set(dashboard_cache "
ADIOS2_USE_Fortran:BOOL=ON
ADIOS2_USE_MPI:BOOL=ON
ADISO2_USE_Python:BOOL=ON

CMAKE_C_FLAGS:STRING=-Wall
CMAKE_CXX_FLAGS:STRING=-Wall
CMAKE_Fortran_FLAGS:STRING=-Wall
")

set(ENV{MACOSX_DEPLOYMENT_TARGET} "10.15")
set(CTEST_CMAKE_GENERATOR "Unix Makefiles")
list(APPEND CTEST_UPDATE_NOTES_FILES "${CMAKE_CURRENT_LIST_FILE}")
set(CTEST_TEST_ARGS
  # Unclear why these tests currently die.  Disabling until it can be addressed.
  EXCLUDE "Install.Make.*"
)
include(${CMAKE_CURRENT_LIST_DIR}/ci-common.cmake)


text:
(function( $ ) {

module( "tooltip: options" );

test( "disabled: true", function() {
	expect( 1 );
	$( "#tooltipped1" ).tooltip({
		disabled: true
	}).tooltip( "open" );
	equal( $( ".ui-tooltip" ).length, 0 );
});

test( "content: default", function() {
	expect( 1 );
	var element = $( "#tooltipped1" ).tooltip().tooltip( "open" );
	deepEqual( $( "#" + element.data( "ui-tooltip-id" ) ).text(), "anchortitle" );
});

test( "content: return string", function() {
	expect( 1 );
	var element = $( "#tooltipped1" ).tooltip({
		content: function() {
			return "customstring";
		}
	}).tooltip( "open" );
	deepEqual( $( "#" + element.data( "ui-tooltip-id" ) ).text(), "customstring" );
});

test( "content: return jQuery", function() {
	expect( 1 );
	var element = $( "#tooltipped1" ).tooltip({
		content: function() {
			return $( "<div>" ).html( "cu<b>s</b>tomstring" );
		}
	}).tooltip( "open" );
	deepEqual( $( "#" + element.data( "ui-tooltip-id" ) ).text(), "customstring" );
});

asyncTest( "content: sync + async callback", function() {
	expect( 2 );
	var element = $( "#tooltipped1" ).tooltip({
		content: function( response ) {
			setTimeout(function() {
				deepEqual( $( "#" + element.data("ui-tooltip-id") ).text(), "loading..." );

				response( "customstring2" );
				setTimeout(function() {
					deepEqual( $( "#" + element.data("ui-tooltip-id") ).text(), "customstring2" );
					start();
				}, 13 );
			}, 13 );
			return "loading...";
		}
	}).tooltip( "open" );
});

test( "content: change while open", function() {
	expect( 2 ) ;
	var element = $( "#tooltipped1" ).tooltip({
		content: function() {
			return "old";
		}
	});

	element.one( "tooltipopen", function( event, ui ) {
		equal( ui.tooltip.text(), "old", "original content" );
		element.tooltip( "option", "content", function() {
			return "new";
		});
		equal( ui.tooltip.text(), "new", "updated content" );
	});

	element.tooltip( "open" );
});

test( "content: string", function() {
	expect( 1 );
	$( "#tooltipped1" ).tooltip({
		content: "just a string",
		open: function( event, ui ) {
			equal( ui.tooltip.text(), "just a string" );
		}
	}).tooltip( "open" );
});

test( "items", function() {
	expect( 2 );
	var event,
		element = $( "#qunit-fixture" ).tooltip({
			items: "#fixture-span"
		});

	event = $.Event( "mouseenter" );
	event.target = $( "#fixture-span" )[ 0 ];
	element.tooltip( "open", event );
	deepEqual( $( "#" + $( "#fixture-span" ).data( "ui-tooltip-id" ) ).text(), "title-text" );

	// make sure default [title] doesn't get used
	event.target = $( "#tooltipped1" )[ 0 ];
	element.tooltip( "open", event );
	deepEqual( $( "#tooltipped1" ).data( "ui-tooltip-id" ), undefined );

	element.tooltip( "destroy" );
});

test( "tooltipClass", function() {
	expect( 1 );
	var element = $( "#tooltipped1" ).tooltip({
		tooltipClass: "custom"
	}).tooltip( "open" );
	ok( $( "#" + element.data( "ui-tooltip-id" ) ).hasClass( "custom" ) );
});

test( "track + show delay", function() {
	expect( 2 );
	var event,
		leftVal = 314,
		topVal = 159,
		offsetVal = 26,
		element = $( "#tooltipped1" ).tooltip({
			track: true,
			show: {
				delay: 1
			},
			position: {
				my: "left+" + offsetVal + " top+" + offsetVal,
				at: "right bottom"
			}
		});

	event = $.Event( "mouseover" );
	event.target = $( "#tooltipped1" )[ 0 ];
	event.originalEvent = { type: "mouseover" };
	event.pageX = leftVal;
	event.pageY = topVal;
	element.trigger( event );

	event = $.Event( "mousemove" );
	event.target = $( "#tooltipped1" )[ 0 ];
	event.originalEvent = { type: "mousemove" };
	event.pageX = leftVal;
	event.pageY = topVal;
	element.trigger( event );

	equal( $( ".ui-tooltip" ).css( "left" ), leftVal + offsetVal + "px" );
	equal( $( ".ui-tooltip" ).css( "top" ), topVal + offsetVal + "px" );
});

test( "track and programmatic focus", function() {
	expect( 1 );
	$( "#qunit-fixture div input" ).tooltip({
		track: true
	}).focus();
	equal( "inputtitle", $( ".ui-tooltip" ).text() );
});

}( jQuery ) );


text:
package org.fcrepo.persistence.ocfl.impl;

import org.fcrepo.persistence.api.PersistentStorageSession;
import org.fcrepo.persistence.api.PersistentStorageSessionManager;
import org.fcrepo.persistence.ocfl.api.FedoraToOCFLObjectIndex;
import org.fcrepo.persistence.ocfl.api.OCFLObjectSessionFactory;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;

/**
 * OCFL implementation of PersistentStorageSessionManager
 *
 * @author whikloj
 * @author dbernstein
 * @since 2019-09-20
 */
@Component
public class OCFLPersistentSessionManager implements PersistentStorageSessionManager {

    private PersistentStorageSession readOnlySession;

    private Map<String, PersistentStorageSession> sessionMap;

    @Inject
    private OCFLObjectSessionFactory objectSessionFactory;

    @Inject
    private FedoraToOCFLObjectIndex fedoraOcflIndex;

    /**
     * Default constructor
     */
    public OCFLPersistentSessionManager() {
        this.sessionMap = new HashMap<>();
    }

    @Override
    public PersistentStorageSession getSession(final String sessionId) {

        if (sessionId == null) {
            throw new IllegalArgumentException("session id must be non-null");
        }

        final PersistentStorageSession session = sessionMap.get(sessionId);

        if (session != null) {
            return session;
        }

        final PersistentStorageSession newSession = new OCFLPersistentStorageSession(sessionId,
                fedoraOcflIndex,
                objectSessionFactory);
        sessionMap.put(sessionId, newSession);
        return newSession;
    }

    @Override
    public PersistentStorageSession getReadOnlySession() {
        if (this.readOnlySession == null) {
            this.readOnlySession = new OCFLPersistentStorageSession(fedoraOcflIndex, objectSessionFactory);
        }
        return this.readOnlySession;
    }
}


text:
CREATE DATABASE seocrawler;
CREATE USER 'seo'@'localhost' IDENTIFIED BY 'oes';
GRANT ALL PRIVILEGES ON seocrawler . * TO 'seo'@'localhost';
FLUSH PRIVILEGES;


text:
var natureOfCode = natureOfCode || {};

(function(ns){
  "use strict";

  ns.arrows = {};
  ns.arrows.drawForceOnMover = function(context,mover,force,color){
    //make a copy just for display purposes, so that we don't affect the real force
    var forceForDisplay = force.clone();
    //scale it up so we can see it
    forceForDisplay = forceForDisplay.multiply(50);
    //translate it on top of the mover's body
    forceForDisplay = forceForDisplay.addVector(mover.location);
    //draw it
    ns.arrows.drawArrow(context,mover.location.x,mover.location.y,forceForDisplay.x,forceForDisplay.y,color);
  }

  //Drawing the velocity and acceleration is completely optional, just for me to understand what is happening.
  ns.arrows.drawVelocityAndAcceleration = function(context,mover){
      //draw velocity
      //make a copy just for display purposes, so that we don't affect the real velocity
      var velocityForDisplay = new ns.Vector2D(mover.velocity.x, mover.velocity.y);
      //scale it up so we can see it
      velocityForDisplay = velocityForDisplay.multiply(5);
      //translate it on top of the mover's body
      velocityForDisplay = velocityForDisplay.addVector(mover.location);
      //draw it
      ns.arrows.drawArrow(context,mover.location.x,mover.location.y,velocityForDisplay.x,velocityForDisplay.y,'blue');

      //draw acceleration
      //make a copy just for display purposes, so that we don't affect the real acceleration
      var accelerationForDisplay = new ns.Vector2D(mover.acceleration.x, mover.acceleration.y);
      //scale it up so we can see it. Acceleration is tiny so it needs to be scaled up a lot.
      accelerationForDisplay = accelerationForDisplay.multiply(50);
      //translate it on top of the mover's body
      accelerationForDisplay = accelerationForDisplay.addVector(mover.location);
      ns.arrows.drawArrow(context,mover.location.x,mover.location.y,accelerationForDisplay.x,accelerationForDisplay.y,'red');
  };

  ns.arrows.drawArrow = function(context, sourceX, sourceY, destinationX, destinationY, color){
      context.beginPath();
      context.moveTo(sourceX, sourceY);
      context.lineTo(destinationX, destinationY);

      var size = 5;
      var angle = Math.atan2(destinationY - sourceY, destinationX - sourceX);

      context.lineTo(destinationX - size * Math.cos(angle-Math.PI/6), destinationY - size * Math.sin(angle-Math.PI/6));
      context.moveTo(destinationX, destinationY);
      context.lineTo(destinationX - size * Math.cos(angle+Math.PI/6), destinationY - size * Math.sin(angle+Math.PI/6));
      context.strokeStyle = color;
      context.stroke();
  };

})(natureOfCode);


text:
package gov.nih.nci.caintegrator.application.query;

import static org.junit.Assert.assertEquals;
import gov.nih.nci.caintegrator.data.CaIntegrator2Dao;
import gov.nih.nci.caintegrator.data.StudyHelper;
import gov.nih.nci.caintegrator.domain.application.EntityTypeEnum;
import gov.nih.nci.caintegrator.domain.application.NumericComparisonCriterion;
import gov.nih.nci.caintegrator.domain.application.NumericComparisonOperatorEnum;
import gov.nih.nci.caintegrator.domain.application.Query;
import gov.nih.nci.caintegrator.domain.application.StudySubscription;
import gov.nih.nci.caintegrator.domain.translational.Study;
import gov.nih.nci.caintegrator.mockito.AbstractMockitoTest;

import java.util.HashSet;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

/**
 * Annotation criterion handler integration tests.
 *
 * @author Abraham J. Evans-EL <aevansel@5amsolutions.com>
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:integration-test-config.xml")
@Transactional
public class AnnotationCriterionHandlerTestIntegration extends AbstractMockitoTest {

    @Autowired
    private CaIntegrator2Dao dao;

    @Test
    public void testGetMatches() throws InvalidCriterionException {
        StudyHelper studyHelper = new StudyHelper();
        dao.save(studyHelper.getPlatform());
        Study study = studyHelper.populateAndRetrieveStudy().getStudy();
        dao.save(study);

        Query query = new Query();
        StudySubscription subscription = new StudySubscription();
        subscription.setStudy(study);
        query.setSubscription(subscription);

        NumericComparisonCriterion criterion = new NumericComparisonCriterion();
        criterion.setNumericValue(12.0);
        criterion.setNumericComparisonOperator(NumericComparisonOperatorEnum.GREATEROREQUAL);
        criterion.setAnnotationFieldDescriptor(studyHelper.getSampleAnnotationFieldDescriptor());
        criterion.setEntityType(EntityTypeEnum.SAMPLE);

        AnnotationCriterionHandler annotationCriterionHandler = new AnnotationCriterionHandler(criterion);
        assertEquals(4, annotationCriterionHandler.getMatches(dao, arrayDataService, query,
                new HashSet<EntityTypeEnum>()).size());
    }
}


text:
This functional test suite deploys a fleet cluster using nspawn containers, and asserts fleet is functioning properly.

It shares an instance of etcd deployed on the host machine with each of the nspawn containers.

It's recommended to run this in a virtual machine environment on CoreOS (e.g. using coreos-vagrant). The only dependency for the tests not provided on the CoreOS image is `go`.

The caller must do three things before running the tests:

1. Ensure an ssh-agent is running and the functional-testing identity is loaded. The `SSH_AUTH_SOCK` environment variable must be set.

```
$ ssh-agent
$ ssh-add fleet/functional/fixtures/id_rsa
$ echo $SSH_AUTH_SOCK
/tmp/ssh-kwmtTOsL7978/agent.7978
```
2. Ensure the `FLEETD_BIN` and `FLEETCTL_BIN` environment variables point to the respective fleetd and fleetctl binaries that should be used to drive the actual tests.

```
$ export FLEETD_BIN=/path/to/fleetd
$ export FLEETCTL_BIN=/path/to/fleetctl
```

3. Make sure etcd is running on the host system.

```
$ systemctl start etcd
```

Then the tests can be run with:

```
# go test github.com/coreos/fleet/functional
```

Since the tests utilize `systemd-nspawn`, this needs to be invoked as sudo/root.

An example test session using coreos-vagrant follows. This assumes that go is available in `/home/core/go` and the fleet repository in `/home/core/fleet` on the target machine (the easiest way to achieve this is to use shared folders).
```
vagrant ssh core-01 -- -A
export GOROOT="$(pwd)/go"
export PATH="${GOROOT}/bin:$PATH"
cd fleet
ssh-add functional/fixtures/id_rsa
export GOPATH="$(pwd)/gopath"
export FLEETD_BIN="$(pwd)/bin/fleetd"
export FLEETCTL_BIN="$(pwd)/bin/fleetctl"
sudo -E env PATH=$PATH go test github.com/coreos/fleet/functional -v
```

If the tests are aborted partway through, it's currently possible for them to leave residual state as a result of the systemd-nspawn operations. This can be cleaned up using the `clean.sh` script.


text:
package org.apache.spark.streaming.flume.sink

import java.util.concurrent.{CountDownLatch, Executors}
import java.util.concurrent.atomic.AtomicLong

import scala.collection.mutable

import org.apache.flume.Channel
import org.apache.commons.lang.RandomStringUtils
import com.google.common.util.concurrent.ThreadFactoryBuilder

/**
 * Class that implements the SparkFlumeProtocol, that is used by the Avro Netty Server to process
 * requests. Each getEvents, ack and nack call is forwarded to an instance of this class.
 * @param threads Number of threads to use to process requests.
 * @param channel The channel that the sink pulls events from
 * @param transactionTimeout Timeout in millis after which the transaction if not acked by Spark
 *                           is rolled back.
 */
// Flume forces transactions to be thread-local. So each transaction *must* be committed, or
// rolled back from the thread it was originally created in. So each getEvents call from Spark
// creates a TransactionProcessor which runs in a new thread, in which the transaction is created
// and events are pulled off the channel. Once the events are sent to spark,
// that thread is blocked and the TransactionProcessor is saved in a map,
// until an ACK or NACK comes back or the transaction times out (after the specified timeout).
// When the response comes or a timeout is hit, the TransactionProcessor is retrieved and then
// unblocked, at which point the transaction is committed or rolled back.

private[flume] class SparkAvroCallbackHandler(val threads: Int, val channel: Channel,
  val transactionTimeout: Int, val backOffInterval: Int) extends SparkFlumeProtocol with Logging {
  val transactionExecutorOpt = Option(Executors.newFixedThreadPool(threads,
    new ThreadFactoryBuilder().setDaemon(true)
      .setNameFormat("Spark Sink Processor Thread - %d").build()))
  // Protected by `sequenceNumberToProcessor`
  private val sequenceNumberToProcessor = mutable.HashMap[CharSequence, TransactionProcessor]()
  // This sink will not persist sequence numbers and reuses them if it gets restarted.
  // So it is possible to commit a transaction which may have been meant for the sink before the
  // restart.
  // Since the new txn may not have the same sequence number we must guard against accidentally
  // committing a new transaction. To reduce the probability of that happening a random string is
  // prepended to the sequence number. Does not change for life of sink
  private val seqBase = RandomStringUtils.randomAlphanumeric(8)
  private val seqCounter = new AtomicLong(0)

  // Protected by `sequenceNumberToProcessor`
  private var stopped = false

  @volatile private var isTest = false
  private var testLatch: CountDownLatch = null

  /**
   * Returns a bunch of events to Spark over Avro RPC.
   * @param n Maximum number of events to return in a batch
   * @return [[EventBatch]] instance that has a sequence number and an array of at most n events
   */
  override def getEventBatch(n: Int): EventBatch = {
    logDebug("Got getEventBatch call from Spark.")
    val sequenceNumber = seqBase + seqCounter.incrementAndGet()
    createProcessor(sequenceNumber, n) match {
      case Some(processor) =>
        transactionExecutorOpt.foreach(_.submit(processor))
        // Wait until a batch is available - will be an error if error message is non-empty
        val batch = processor.getEventBatch
        if (SparkSinkUtils.isErrorBatch(batch)) {
          // Remove the processor if it is an error batch since no ACK is sent.
          removeAndGetProcessor(sequenceNumber)
          logWarning("Received an error batch - no events were received from channel! ")
        }
        batch
      case None =>
        new EventBatch("Spark sink has been stopped!", "", java.util.Collections.emptyList())
    }
  }

  private def createProcessor(seq: String, n: Int): Option[TransactionProcessor] = {
    sequenceNumberToProcessor.synchronized {
      if (!stopped) {
        val processor = new TransactionProcessor(
          channel, seq, n, transactionTimeout, backOffInterval, this)
        sequenceNumberToProcessor.put(seq, processor)
        if (isTest) {
          processor.countDownWhenBatchAcked(testLatch)
        }
        Some(processor)
      } else {
        None
      }
    }
  }

  /**
   * Called by Spark to indicate successful commit of a batch
   * @param sequenceNumber The sequence number of the event batch that was successful
   */
  override def ack(sequenceNumber: CharSequence): Void = {
    logDebug("Received Ack for batch with sequence number: " + sequenceNumber)
    completeTransaction(sequenceNumber, success = true)
    null
  }

  /**
   * Called by Spark to indicate failed commit of a batch
   * @param sequenceNumber The sequence number of the event batch that failed
   * @return
   */
  override def nack(sequenceNumber: CharSequence): Void = {
    completeTransaction(sequenceNumber, success = false)
    logInfo("Spark failed to commit transaction. Will reattempt events.")
    null
  }

  /**
   * Helper method to commit or rollback a transaction.
   * @param sequenceNumber The sequence number of the batch that was completed
   * @param success Whether the batch was successful or not.
   */
  private def completeTransaction(sequenceNumber: CharSequence, success: Boolean) {
    removeAndGetProcessor(sequenceNumber).foreach(processor => {
      processor.batchProcessed(success)
    })
  }

  /**
   * Helper method to remove the TxnProcessor for a Sequence Number. Can be used to avoid a leak.
   * @param sequenceNumber
   * @return An `Option` of the transaction processor for the corresponding batch. Note that this
   *         instance is no longer tracked and the caller is responsible for that txn processor.
   */
  private[sink] def removeAndGetProcessor(sequenceNumber: CharSequence):
      Option[TransactionProcessor] = {
    sequenceNumberToProcessor.synchronized {
      sequenceNumberToProcessor.remove(sequenceNumber.toString)
    }
  }

  private[sink] def countDownWhenBatchAcked(latch: CountDownLatch) {
    testLatch = latch
    isTest = true
  }

  /**
   * Shuts down the executor used to process transactions.
   */
  def shutdown() {
    logInfo("Shutting down Spark Avro Callback Handler")
    sequenceNumberToProcessor.synchronized {
      stopped = true
      sequenceNumberToProcessor.values.foreach(_.shutdown())
    }
    transactionExecutorOpt.foreach(_.shutdownNow())
  }
}


text:
using SevenDigital.Api.Schema.ParameterDefinitions.Get;

namespace SevenDigital.Api.Wrapper
{
	public static class HasTrackIdParameterExtensions
	{
		public static IFluentApi<T> ForTrackId<T>(this IFluentApi<T> api, int trackId) where T : HasTrackIdParameter
		{
			api.WithParameter("trackId", trackId.ToString());
			return api;
		}
	}
}


text:
@extends('layouts.default')

@section('title')
Login
@stop

@section('content')

    {{ Form::open(array('url' => Request::fullUrl(), 'class' => 'col-md-6 col-md-offset-3')) }}
    <legend>Login</legend>

    @include('manavo/laravel-toolkit::partials.alerts')

        {{ Form::label('email', 'Email', array('class' => '')) }}
        {{ Form::email('email', Input::get('email'), array('class' => 'form-control')) }}

        {{ Form::label('password', 'Password', array('class' => '')) }}
        {{ Form::password('password', array('class' => 'form-control')) }}Forgot your password?

        {{ Form::submit('Login', array('class' => 'btn btn-primary', 'data-loading-text' => 'Logging in...')) }}

    {{ Form::close() }}

@stop


text:
"""Tests for SpeedTest integration."""

from collections.abc import Awaitable
from datetime import timedelta
from typing import Callable
from unittest.mock import MagicMock

from aiohttp import ClientWebSocketResponse
import speedtest

from homeassistant.components.speedtestdotnet.const import (
    CONF_MANUAL,
    CONF_SERVER_ID,
    CONF_SERVER_NAME,
    DOMAIN,
    SPEED_TEST_SERVICE,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_SCAN_INTERVAL, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
import homeassistant.util.dt as dt_util

from tests.common import MockConfigEntry, async_fire_time_changed
from tests.components.repairs import get_repairs

async def test_successful_config_entry(hass: HomeAssistant) -> None:
    """Test that SpeedTestDotNet is configured successfully."""

    entry = MockConfigEntry(
        domain=DOMAIN,
        data={},
        options={
            CONF_SERVER_NAME: "Country1 - Sponsor1 - Server1",
            CONF_SERVER_ID: "1",
            CONF_SCAN_INTERVAL: 30,
            CONF_MANUAL: False,
        },
    )
    entry.add_to_hass(hass)

    await hass.config_entries.async_setup(entry.entry_id)

    assert entry.state == ConfigEntryState.LOADED
    assert hass.data[DOMAIN]
    assert hass.services.has_service(DOMAIN, SPEED_TEST_SERVICE)

async def test_setup_failed(hass: HomeAssistant, mock_api: MagicMock) -> None:
    """Test SpeedTestDotNet failed due to an error."""

    entry = MockConfigEntry(
        domain=DOMAIN,
    )
    entry.add_to_hass(hass)

    mock_api.side_effect = speedtest.ConfigRetrievalError
    await hass.config_entries.async_setup(entry.entry_id)
    assert entry.state is ConfigEntryState.SETUP_RETRY

async def test_unload_entry(hass: HomeAssistant) -> None:
    """Test removing SpeedTestDotNet."""
    entry = MockConfigEntry(
        domain=DOMAIN,
    )
    entry.add_to_hass(hass)

    await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    assert await hass.config_entries.async_unload(entry.entry_id)
    await hass.async_block_till_done()

    assert entry.state is ConfigEntryState.NOT_LOADED
    assert DOMAIN not in hass.data

async def test_server_not_found(hass: HomeAssistant, mock_api: MagicMock) -> None:
    """Test configured server id is not found."""

    entry = MockConfigEntry(
        domain=DOMAIN,
        options={
            CONF_MANUAL: False,
            CONF_SCAN_INTERVAL: 60,
        },
    )
    entry.add_to_hass(hass)

    await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()
    assert hass.data[DOMAIN]

    mock_api.return_value.get_servers.side_effect = speedtest.NoMatchedServers
    async_fire_time_changed(
        hass,
        dt_util.utcnow() + timedelta(minutes=entry.options[CONF_SCAN_INTERVAL] + 1),
    )
    await hass.async_block_till_done()
    state = hass.states.get("sensor.speedtest_ping")
    assert state is not None
    assert state.state == STATE_UNAVAILABLE

async def test_get_best_server_error(hass: HomeAssistant, mock_api: MagicMock) -> None:
    """Test configured server id is not found."""

    entry = MockConfigEntry(
        domain=DOMAIN,
    )
    entry.add_to_hass(hass)

    await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()
    assert hass.data[DOMAIN]

    mock_api.return_value.get_best_server.side_effect = (
        speedtest.SpeedtestBestServerFailure(
            "Unable to connect to servers to test latency."
        )
    )
    await hass.data[DOMAIN].async_refresh()
    await hass.async_block_till_done()
    state = hass.states.get("sensor.speedtest_ping")
    assert state is not None
    assert state.state == STATE_UNAVAILABLE

async def test_deprecated_service_alert(
    hass: HomeAssistant,
    hass_ws_client: Callable[[HomeAssistant], Awaitable[ClientWebSocketResponse]],
) -> None:
    """Test that an issue is raised if deprecated services is called."""
    entry = MockConfigEntry(
        domain=DOMAIN,
    )
    entry.add_to_hass(hass)

    await hass.config_entries.async_setup(entry.entry_id)
    await hass.async_block_till_done()

    await hass.services.async_call(
        DOMAIN,
        "speedtest",
        {},
        blocking=True,
    )
    await hass.async_block_till_done()
    issues = await get_repairs(hass, hass_ws_client)
    assert len(issues) == 1
    assert issues[0]["issue_id"] == "deprecated_service"


text:
Contributing to django CMS
##########################

Like every open-source project, django CMS always welcomes contributions.

*******************************
GitHub issues and pull requests
*******************************

`GitHub issues <https://github.com/divio/django-cms/issues>`_ should only be used to report *suspected issues* in
django CMS.

It should **not** be used for reporting *security issues* - please use `security@django-cms.org
<security@django-cms.org>`_ for those.

For *help with django CMS*, please use our `users' email list <https://groups.google.com/forum/#!forum/django-cms>`_.

For *feature requests*, please use our `developers' email list
<https://groups.google.com/forum/#!forum/django-cms-developers>`_.

**************************
Contribution documentation
**************************

We maintain comprehensive `contribution documentation <http://docs.django-cms.org/en/stable/contributing/>`_ - please
familiarise yourself with it.

***************
Security issues
***************

Security issues should not be reported **anywhere** except via our dedicated and private `security@django-cms.org
<security@django-cms.org>`_ email address.

If you think you have discovered a security issue in our code, please do not raise it on

    * IRC
    * GitHub
    * either of our email lists

    or in any other public forum until we have had a chance to deal with it.

***************
Code of conduct
***************

django CMS is governed by a `Code of Conduct
<http://docs.django-cms.org/en/stable/contributing/code_of_conduct.html>`_. All participants in our community and its
various forums are expect to abide by it.

*********
Community
*********

You can join us online:

* in our IRC channel, #django-cms, on ``irc.freenode.net``. If you don't have an IRC client, you can
  `join our IRC channel using the KiwiIRC web client
  <https://kiwiirc.com/client/irc.freenode.net/django-cms>`_, which works pretty well.
* on our `django CMS users email list <https://groups.google.com/forum/#!forum/django-cms>`_ for
  **general** django CMS questions and discussion
* on our `django CMS developers email list
  <https://groups.google.com/forum/#!forum/django-cms-developers>`_ for discussions about the
  **development of django CMS**

You can also follow:

* the `Travis Continuous Integration build reports <https://travis-ci.org/divio/django-cms>`_
* the `@djangocms`_ Twitter account for general announcements


text:
FOUNDATION_EXPORT double APAvatarImageViewVersionNumber;
FOUNDATION_EXPORT const unsigned char APAvatarImageViewVersionString[];


text:
package org.kaaproject.kaa.server.operations.service.event;

import nl.jqno.equalsverifier.EqualsVerifier;

import org.junit.Test;

public class UserRouteInfoTest {

  @Test
  public void hashCodeEqualsTest() {
    EqualsVerifier.forClass(UserRouteInfo.class).verify();
  }
}


text:
package com.taobao.weex.common;

import android.content.Intent;
import android.text.TextUtils;

import com.taobao.weex.WXSDKInstance;

import java.util.HashMap;
import java.util.Map;

/**
 * All modules must extend this class
 */
public abstract class WXModule implements IWXObject {

  public static final String ACTION_ACTIVITY_RESULT = "actionActivityResult";
  public static final String ACTION_REQUEST_PERMISSIONS_RESULT = "actionRequestPermissionsResult";
  public static final String REQUEST_CODE = "requestCode";
  public static final String RESULT_CODE = "resultCode";
  public static final String PERMISSIONS = "permissions";
  public static final String GRANT_RESULTS = "grantResults";

  public WXSDKInstance mWXSDKInstance;

  private Map<String, String> mEvents = new HashMap<>();
  private Map<String, Boolean> mKeepAlives = new HashMap<>();

  public void onActivityResult(int requestCode, int resultCode, Intent data) {
  }

  @WXModuleAnno
  public void addEventListener(String eventName, String callback, Map<String, Object> options) {
    if (TextUtils.isEmpty(eventName) || TextUtils.isEmpty(callback)) {
      return;
    }
    boolean isOnce = true;
    if (options != null && options.size() > 0 && options.containsKey("once")) {
      Object temp = options.get("once");
      if ("false".equals(temp)) {
        isOnce = false;
      }
    }
    mKeepAlives.put(callback, isOnce);
    mEvents.put(eventName, callback);
  }

  @WXModuleAnno
  public void removeEventListener(String eventName) {
    if (mEvents.containsKey(eventName)) {
      String callback = mEvents.remove(eventName);
      mKeepAlives.remove(callback);
    }
  }

  /**
   * Check whether the EventName has been registered
   */
  public String getEventCallback(String eventName) {
    return mEvents.get(eventName);
  }

  public boolean isOnce(String callback){
    return mKeepAlives.get(callback);
  }
}