text:
// MIT License
// Copyright (c) 2011-2016 Elisée Maurer, Sparklin Labs, Creative Patterns
// Copyright (c) 2016 Thomas Morgner, Rabbit-StewDio Ltd.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;

using Microsoft.Xna.Framework;

using Steropes.UI.Components;
using Steropes.UI.Platform;
using Steropes.UI.Styles;
using Steropes.UI.Widgets.TextWidgets.Documents.Helper;

namespace Steropes.UI.Widgets.TextWidgets.Documents.Views
{
  /// <summary>
  ///   A view representing a chunk of text. This can be a sub-set of the leaf-node's full text to facilitate line breaking.
  /// </summary>
  public class TextChunkView<TDocument> : TextView<TDocument>, ITextChunkView<TDocument>
    where TDocument : ITextDocument
  {
    readonly ITextProcessingRules rules;

    string buffer;

    string displayText;

    Vector2 maxSize;

    public TextChunkView(ITextProcessingRules rules, ITextNode node, IStyle style, ITextPosition offset, ITextPosition endOffset) : base(node, style)
    {
      this.rules = rules;
      OffsetPosition = offset;
      EndOffsetPosition = endOffset;
    }

    public float BaseLine => Font.Baseline;

    public override int EndOffset => EndOffsetPosition.Offset;

    public ITextPosition EndOffsetPosition { get; }

    public int EndOffsetWithoutLineBreaks => EndOffset - HardTrimAtEnd;

    public override int Offset => OffsetPosition.Offset;

    public ITextPosition OffsetPosition { get; }

    public int StretchWeight { get; private set; }

    public string Text => TextFor(Offset, EndOffset);

    /// <summary>
    ///   Public for testing
    /// </summary>
    protected int HardTrimAtEnd { get; private set; }

    /// <summary>
    ///   Public for testing
    /// </summary>
    protected int TrimAtEnd { get; private set; }

    /// <summary>
    ///   Public for testing
    /// </summary>
    protected int TrimAtStart { get; private set; }

    float MaxHeight
    {
      get
      {
        if (float.IsInfinity(maxSize.X))
        {
          maxSize = Font.MeasureString(displayText);
          maxSize.Y = Font.LineSpacing;
        }
        return maxSize.Y;
      }
    }

    float MaxWidth
    {
      get
      {
        if (float.IsInfinity(maxSize.X))
        {
          maxSize = Font.MeasureString(displayText);
          maxSize.Y = Font.LineSpacing;
        }
        return maxSize.X;
      }
    }

    public int TrimmedEndOffset => EndOffsetPosition.Offset - TrimAtEnd;

    public int TrimmedStartOffset => OffsetPosition.Offset + TrimAtStart;

    /// <summary>
    ///   Computes the nearest valid break offset for the given width, and attempts to break this chunk
    ///   into two independent text-chunks. The first chunk will contain the text that should remain on
    ///   the current line, the second chunk contains the content that should be pushed to the next
    ///   line.
    /// </summary>
    /// <param name="width">The width position.</param>
    /// <param name="first">The left hand chunk, never null.</param>
    /// <param name="second">The right hand chunk or null if the content did not break.</param>
    public void BreakAt(float width, out ITextChunkView<TDocument> first, out ITextChunkView<TDocument> second)
    {
      var breakPoint = FindWordBreakOffset(width);
      BreakAtOffset(breakPoint, out first, out second);
    }

    public void BreakAtOffset(int breakPoint, out ITextChunkView<TDocument> first, out ITextChunkView<TDocument> second)
    {
      // is the break within the leading whitespace content? If so, dont break.
      if (breakPoint <= TrimmedStartOffset)
      {
        first = this;
        second = null;
        return;
      }

      // is the break within the trailing whitespace content? If so, dont break.
      if (breakPoint >= TrimmedEndOffset)
      {
        first = this;
        second = null;
        return;
      }

      first = SubChunk(OffsetPosition, Node.Document.CreatePosition(breakPoint, Bias.Backward));
      second = SubChunk(Node.Document.CreatePosition(breakPoint, Bias.Forward), EndOffsetPosition);
    }

    public override void Draw(IBatchedDrawingService drawingService)
    {
      var x = LayoutRect.X;
      var y = LayoutRect.Y + Padding.Top;
      var width = DesiredSize.Width;
      var font = Font;
      var textColor = Style.GetValue(TextStyles.TextColor);
      var outlineColor = Style.GetValue(TextStyles.OutlineColor);
      var outlineRadius = Style.GetValue(TextStyles.OutlineSize);
      var underline = Style.GetValue(TextStyles.Underline);
      var strikeThrough = Style.GetValue(TextStyles.StrikeThrough);
      drawingService.DrawBlurredText(font, displayText, new Vector2(x + Padding.Left, y + font.Baseline), textColor, outlineRadius, outlineColor);
      if (underline)
      {
        var bottomLeft = new Vector2(x, y + font.LineSpacing + font.Baseline);
        drawingService.DrawLine(bottomLeft, bottomLeft + new Vector2(width, 0), textColor);
      }
      if (strikeThrough)
      {
        var bottomLeft = new Vector2(x, y + font.LineSpacing / 2f + font.Baseline);
        drawingService.DrawLine(bottomLeft, bottomLeft + new Vector2(width, 0), textColor);
      }
    }

    public void Initialize()
    {
      var length = EndOffsetPosition.Offset - OffsetPosition.Offset;
      buffer = Node.Document.TextAt(OffsetPosition.Offset, length);

      TrimAtStart = TextProcessing.CountFromStart(buffer, 0, length, TextProcessing.CanTrim);
      TrimAtEnd = TextProcessing.CountFromEnd(buffer, TrimAtStart, length, TextProcessing.CanTrim);

      HardTrimAtEnd = TextProcessing.CountFromEnd(buffer, 0, length, rules.IsInvalidCursorPosition);
      maxSize = new Vector2(float.NegativeInfinity, float.NegativeInfinity);
      StretchWeight = 0;
      Padding = ComputePaddings();

      displayText = TextFor(TrimmedStartOffset, TrimmedEndOffset);
    }

    public override bool ModelToView(int offset, out Rectangle result)
    {
      if (LayoutInvalid)
      {
        result = default(Rectangle);
        return false;
      }
      if (EndOffset == offset)
      {
        // special case to allow to place the cursor at the end of the line and to insert
        // text after the last visible character.
        result = new Rectangle(LayoutRect.Right, LayoutRect.Y, 0, Font.LineSpacing);
        return true;
      }

      if (!Node.InRange(offset))
      {
        result = default(Rectangle);
        return false;
      }

      var start = WidthFor(Offset, offset);
      var end = WidthFor(Offset, offset + 1);

      result = new Rectangle(LayoutRect.X + (int)start, LayoutRect.Y, (int)(end - start), Font.LineSpacing);
      return true;
    }

    public override NavigationResult Navigate(int editOffset, Direction direction, out int targetOffset)
    {
      if (LayoutInvalid)
      {
        targetOffset = -1;
        return NavigationResult.Invalid;
      }

      switch (direction)
      {
        case Direction.Right:
        case Direction.Down:
          {
            if (editOffset >= EndOffset)
            {
              targetOffset = -1;
              return NavigationResult.Invalid;
            }
            if (editOffset < Offset)
            {
              targetOffset = Offset;
              return NavigationResult.Valid;
            }

            targetOffset = editOffset + 1;
            if (targetOffset == EndOffset)
            {
              return NavigationResult.BoundaryChanged;
            }

            return NavigationResult.Valid;
          }
        case Direction.Left:
        case Direction.Up:
          {
            if (editOffset > EndOffset)
            {
              targetOffset = EndOffset;
              return NavigationResult.Valid;
            }
            if (editOffset <= Offset)
            {
              targetOffset = -1;
              return NavigationResult.Invalid;
            }

            targetOffset = editOffset - 1;
            if (targetOffset == Offset)
            {
              return NavigationResult.BoundaryChanged;
            }
            return NavigationResult.Valid;
          }
        default:
          {
            throw new ArgumentOutOfRangeException(nameof(direction), direction, null);
          }
      }
    }

    public override void OnNodeContentChanged(IDocumentView<TDocument> docView, TextModificationEventArgs args)
    {
      Initialize();
      InvalidateLayout();
    }

    public override void OnNodeStructureChanged(IDocumentView<TDocument> docView, IElementEdit edit)
    {
      Initialize();
      InvalidateLayout();
    }

    public TextChunkView<TDocument> SubChunk(ITextPosition start, ITextPosition end)
    {
      if (start.Bias != Bias.Forward)
      {
        throw new ArgumentException();
      }
      if (end.Bias != Bias.Backward)
      {
        throw new ArgumentException();
      }
      var subChunk = new TextChunkView<TDocument>(rules, Node, Style, start, end);
      subChunk.Initialize();
      return subChunk;
    }

    public virtual string TextFor(int offset, int endOffset)
    {
      // text buffer is valid within the range of the node.
      // buffer-offset tells us the number of characters to disregard at the start of the buffer.
      var length = endOffset - offset;
      return buffer.Substring(offset - Offset, length);
    }

    public override bool ViewToModel(Point position, out int offset, out Bias bias)
    {
      if (LayoutInvalid)
      {
        offset = -1;
        bias = Bias.Forward;
        return false;
      }

      if (!LayoutRect.Contains(position))
      {
        offset = -1;
        bias = Bias.Forward;
        return false;
      }

      var targetWidth = position.X - LayoutRect.X;
      offset = FindEditPositionBreakOffset(targetWidth);
      if (offset == EndOffset)
      {
        bias = Bias.Backward;
        return true;
      }

      var offsetWidth = WidthFor(Offset, offset);
      var nextWidth = WidthFor(Offset, offset + 1);
      var width = nextWidth - offsetWidth;
      bias = targetWidth - offsetWidth < width / 2 ? Bias.Backward : Bias.Forward;
      return true;
    }

    protected override Rectangle ArrangeOverride(Rectangle layoutSize)
    {
      var x = layoutSize.X;
      var y = layoutSize.Y;
      var width = (int)(Alignment == Alignment.Fill ? Math.Max(layoutSize.Width, MaxWidth) : MaxWidth);
      var height = (int)MaxHeight;
      return new Rectangle(x, y, width, height);
    }

    protected override Size MeasureOverride(Size availableSize)
    {
      return new Size(MaxWidth, MaxHeight);
    }

    protected override void OnLayoutInvalidated()
    {
      maxSize = new Vector2(float.PositiveInfinity, float.PositiveInfinity);
      base.OnLayoutInvalidated();
    }

    Insets ComputePaddings()
    {
      var left = (int)WidthFor(Offset, TrimmedStartOffset);
      var right = (int)WidthFor(TrimmedEndOffset, EndOffset);
      return new Insets(0, left, 0, right);
    }

    int FindBreakOffset(float targetPosition, Func<char, char, bool> breakEvaluator)
    {
      var start = Offset;
      var end = EndOffset - HardTrimAtEnd;

      var it = new BreakIterator<bool>(Node.Document.Content, breakEvaluator, start, end);
      var cursor = start;
      var lastGoodBreak = cursor;
      while (it.MoveNext())
      {
        if (it.Current == false)
        {
          cursor += 1;
          continue;
        }

        var width = WidthFor(start, cursor);
        if (width < targetPosition)
        {
          lastGoodBreak = cursor;
        }
        else if (lastGoodBreak == start || Math.Abs(width - targetPosition) < 0.5)
        {
          return cursor;
        }
        else
        {
          return lastGoodBreak;
        }
        cursor += 1;
      }
      return lastGoodBreak;
    }

    int FindEditPositionBreakOffset(float targetPosition)
    {
      return FindBreakOffset(targetPosition, rules.IsValidCursorPosition);
    }

    int FindWordBreakOffset(float targetPosition)
    {
      return FindBreakOffset(targetPosition, rules.IsWordBreakPosition);
    }

    float WidthFor(int offset, int positionWithinDocument)
    {
      if (Font == null)
      {
        throw new InvalidOperationException("No font for text-view. The style system is not initialized correctly.");
      }
      return Font.MeasureString(TextFor(offset, positionWithinDocument)).X;
    }
  }
}


text:
import { CallbackHook, CallbackChainHook } from '../lib/vulcan-lib/callbacks';
import { getCollection } from '../lib/vulcan-lib/getCollection';

type CallbackValidationErrors = Array<any>;

export interface CreateCallbackProperties<T extends DbObject> {
  data: Partial<T>|undefined
  currentUser: DbUser|null
  collection: CollectionBase<T>
  context: ResolverContext
  document: T
  newDocument: T
  schema: SchemaType<T>
}

export interface UpdateCallbackProperties<T extends DbObject> {
  data: Partial<T>
  oldDocument: T
  document: T
  newDocument: T
  currentUser: DbUser|null
  collection: CollectionBase<T>
  context: ResolverContext
  schema: SchemaType<T>
}

export interface DeleteCallbackProperties<T extends DbObject> {
  document: T
  currentUser: DbUser|null
  collection: CollectionBase<T>
  context: ResolverContext
  schema: SchemaType<T>
}

export class CollectionMutationCallbacks<T extends DbObject> {
  createValidate: CallbackChainHook<CallbackValidationErrors,[CreateCallbackProperties<T>]>
  newValidate: CallbackChainHook<DbInsertion<T>,[DbUser|null,CallbackValidationErrors]>
  createBefore: CallbackChainHook<T,[CreateCallbackProperties<T>]>
  newBefore: CallbackChainHook<T,[DbUser|null]>
  newSync: CallbackChainHook<T,[DbUser|null]>
  createAfter: CallbackChainHook<T,[CreateCallbackProperties<T>]>
  newAfter: CallbackChainHook<T,[DbUser|null]>
  createAsync: CallbackHook<[CreateCallbackProperties<T>]>
  newAsync: CallbackHook<[T,DbUser|null,any]>

  updateValidate: CallbackChainHook<CallbackValidationErrors,[UpdateCallbackProperties<T>]>
  editValidate: CallbackChainHook<MongoModifier<T>,[T,DbUser|null,CallbackValidationErrors]>
  updateBefore: CallbackChainHook<Partial<T>,[UpdateCallbackProperties<T>]>
  editBefore: CallbackChainHook<MongoModifier<T>,[T,DbUser|null,T]>
  editSync: CallbackChainHook<MongoModifier<T>,[T,DbUser|null,T]>
  updateAfter: CallbackChainHook<T,[UpdateCallbackProperties<T>]>
  editAfter: CallbackChainHook<T,[T,DbUser|null]>
  updateAsync: CallbackHook<[UpdateCallbackProperties<T>]>
  editAsync: CallbackHook<[T,T,DbUser|null,CollectionBase<T>]>

  deleteValidate: CallbackChainHook<CallbackValidationErrors,[DeleteCallbackProperties<T>]>
  removeValidate: CallbackChainHook<T,[DbUser|null]>
  deleteBefore: CallbackChainHook<T,[DeleteCallbackProperties<T>]>
  removeBefore: CallbackChainHook<T,[DbUser|null]>
  removeSync: CallbackChainHook<T,[DbUser|null]>
  deleteAsync: CallbackHook<[DeleteCallbackProperties<T>]>
  removeAsync: CallbackHook<[T,DbUser|null,CollectionBase<T>]>

  constructor(collectionName: CollectionNameString) {
    const collection = getCollection(collectionName);
    const typeName = collection.options.typeName;

    this.createValidate = new CallbackChainHook<CallbackValidationErrors,[CreateCallbackProperties<T>]>(`${typeName.toLowerCase()}.create.validate`);
    this.newValidate = new CallbackChainHook<DbInsertion<T>,[DbUser|null,CallbackValidationErrors]>(`${collectionName.toLowerCase()}.new.validate`);
    this.createBefore = new CallbackChainHook<T,[CreateCallbackProperties<T>]>(`${typeName.toLowerCase()}.create.before`);
    this.newBefore = new CallbackChainHook<T,[DbUser|null]>(`${collectionName.toLowerCase()}.new.before`);
    this.newSync = new CallbackChainHook<T,[DbUser|null]>(`${collectionName.toLowerCase()}.new.sync`);
    this.createAfter = new CallbackChainHook<T,[CreateCallbackProperties<T>]>(`${typeName.toLowerCase()}.create.after`);
    this.newAfter = new CallbackChainHook<T,[DbUser|null]>(`${collectionName.toLowerCase()}.new.after`);
    this.createAsync = new CallbackHook<[CreateCallbackProperties<T>]>(`${typeName.toLowerCase()}.create.async`);
    this.newAsync = new CallbackHook<[T,DbUser|null,any]>(`${collectionName.toLowerCase()}.new.async`);

    this.updateValidate = new CallbackChainHook<CallbackValidationErrors,[UpdateCallbackProperties<T>]>(`${typeName.toLowerCase()}.update.validate`);
    this.editValidate = new CallbackChainHook<MongoModifier<T>,[T,DbUser|null,CallbackValidationErrors]>(`${collectionName.toLowerCase()}.edit.validate`)
    this.updateBefore = new CallbackChainHook<Partial<T>,[UpdateCallbackProperties<T>]>(`${typeName.toLowerCase()}.update.before`);
    this.editBefore = new CallbackChainHook<MongoModifier<T>,[T,DbUser|null,T]>(`${collectionName.toLowerCase()}.edit.before`);
    this.editSync = new CallbackChainHook<MongoModifier<T>,[T,DbUser|null,T]>(`${collectionName.toLowerCase()}.edit.sync`);
    this.updateAfter = new CallbackChainHook<T,[UpdateCallbackProperties<T>]>(`${typeName.toLowerCase()}.update.after`);
    this.editAfter = new CallbackChainHook<T,[T,DbUser|null]>(`${collectionName.toLowerCase()}.edit.after`)
    this.updateAsync = new CallbackHook<[UpdateCallbackProperties<T>]>(`${typeName.toLowerCase()}.update.async`);
    this.editAsync = new CallbackHook<[T,T,DbUser|null,CollectionBase<T>]>(`${collectionName.toLowerCase()}.edit.async`)

    this.deleteValidate = new CallbackChainHook<CallbackValidationErrors,[DeleteCallbackProperties<T>]>(`${typeName.toLowerCase()}.delete.validate`);
    this.removeValidate = new CallbackChainHook<T,[DbUser|null]>(`${collectionName.toLowerCase()}.remove.validate`);
    this.deleteBefore = new CallbackChainHook<T,[DeleteCallbackProperties<T>]>(`${typeName.toLowerCase()}.delete.before`);
    this.removeBefore = new CallbackChainHook<T,[DbUser|null]>(`${collectionName.toLowerCase()}.remove.before`);
    this.removeSync = new CallbackChainHook<T,[DbUser|null]>(`${collectionName.toLowerCase()}.remove.sync`);
    this.deleteAsync = new CallbackHook<[DeleteCallbackProperties<T>]>(`${typeName.toLowerCase()}.delete.async`);
    this.removeAsync = new CallbackHook<[T,DbUser|null,CollectionBase<T>]>(`${collectionName.toLowerCase()}.remove.async`);
  }
}

const collectionHooks: any = {};

export const getCollectionHooks = <N extends CollectionNameString>(collectionName: N): CollectionMutationCallbacks<ObjectsByCollectionName[N]> =>  {
  if (!(collectionName in collectionHooks)) {
    collectionHooks[collectionName] = new CollectionMutationCallbacks(collectionName);
  }
  return collectionHooks[collectionName];
}

redpajama_set_name: RedPajamaGithub


text:
  Rahay est
       un village
       localisé dans le département de Sarthe en Pays de la Loire. Elle totalisait 201 habitants en 2008.

Si vous envisagez de venir habiter à Rahay, vous pourrez aisément trouver une maison à acheter.

À coté de Rahay sont positionnées géographiquement les villes de
Berfay à 6 km, 381 habitants,
Cormenon située à 4 km, 694 habitants,
Choue à 8 km, 531 habitants,
Valennes située à 4 km, 356 habitants,
Sargé-sur-Braye à 4 km, 934 habitants,
Mondoubleau située à 5 km, 1 509 habitants,
 entre autres. De plus, Rahay est située à seulement 26 km de Vendôme.

Le nombre de logements, à Rahay, était réparti en 2011 en zero appartements et 113 maisons soit
 un marché relativement équilibré.

La commune offre quelques  aménagements, elle dispose, entre autres, de une boucle de randonnée.


text:
.. SINT Rest App documentation master file, created by
   sphinx-quickstart on Fri Apr  4 19:31:27 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to SINT Rest App's documentation!
=========================================

:download:`Download der in der LV präsentierten Präsentation  <_static/sint_projektarbeit_20140409_v01.pptx>`

Applikation
-----------

* `Applikation <http://sintapp.herokuapp.com/>`_
* `App Dokumentation <http://sint-app.readthedocs.org/>`_
* `Source <https://github.com/sumpfgottheit/rhc-sint-app/>`_

Rest Service
------------

* `REST Service <http://sintrest-sumpfgottheit.rhcloud.com>`_
* `REST Dokumentation <http://sint-rest.readthedocs.org>`_
* `Source <https://github.com/sumpfgottheit/rhc-sint-rest/>`_

SOAP Service
------------

* `SOAP Service URL <http://lnurn3.schlof.net:8080/SOAP_CurrencyConverter/wsdl/CurrencyConverter.wsdl>`_
* `SOAP Dokumentation <http://lnurn3.schlof.net/sint-java-doc/>`_

Technologiestack
----------------

Frontend und Webservice sind in **Python** geschrieben, das Webservice in **Java**

* `Python 2.7 <http://www.python.org/>`_
* `Flask - Webframework <http://flask.pocoo.org/>`_
* `SQLALchemy - Persistenz Layer <http://www.sqlalchemy.org/>`_
* `Postgresql - Relationale Datenbank <http://www.postgresql.org>`_
* `Bootstrap - Front End <http://getbootstrap.com/>`_
* `Sphinx - Documentation Generator <http://sphinx-doc.org/>`_
* `WTForms - HTML Form Helper <http://wtforms.readthedocs.org/en/latest/>`_
* `ReadTheDocs - Documentation Hosting <https://readthedocs.org/>`_
* `Requests - HTTP for Humans <http://docs.python-requests.org/en/latest/>`_
* `Flask Restless <https://flask-restless.readthedocs.org/en/latest/>`_

Deployment
----------

**Applikation**
    http://sintapp.herokuapp.com/leihen/

    `Heroku <https://www.heroku.com>`_, AWS, EU Region

   **Python**

**REST Service**
    http://sintrest-sumpfgottheit.rhcloud.com

    `OpenShift - Red Hats Cloud Angebot <https://www.openshift.com/>`_, AWS, US Region

   **Python**

**Webservice**
    http://lnurn3.schlof.net:8080/SOAP_CurrencyConverter/wsdl/CurrencyConverter.wsdl

    `Netcup <http://www.netcup.de>`_ Serverhousing, Nürnberg, DE

   **Java**

**Redis**
    Cache um nicht mehr als 2.500 Abfragen auf Googleapi zu machen

    `RedisLabs <http://redislabs.com/>`_, AWS, US Region

Aufgabe 1: Google Webservice Nutzen
-----------------------------------

Wählt man unter http://sintapp.herokuapp.com/kunden/ einen Kunden aus und klickt auf **Neue Leihe** werden die Verleihstationen
der Distanz von der Kundenadresse bis zur Station sortiert angeboten. Die Google API wird mittels :ref:`googleapi` angesprochen.

.. image:: _static/sintapp1.png

Aufgabe 2: REST Service Entwickeln
----------------------------------

Die Kommunikation zwischen Applikation und Backend erfolg ausschliesslich über REST calls. In :ref:`flaskapp` können die
einzelnen Funktionen im Source betrachtet werden. Die REST Api selbst ist unter http://sint-rest.readthedocs.org zu finden.
In :ref:`rest` werden die Wrapperfunktionen für den Aufruf dargestellt.

Aufgabe 3: Webservice nutzen
----------------------------

Das REST Service verwendet seinerseits das SOAP Service, um abhängig von dem Land, indem der Kunde wohnt die Kosten für
die Leihe in die entsprechende Währung umzurechnen. Genaueres ist in http://sint-rest.readthedocs.org/soapclient.html
dokumentiert.

.. image:: _static/sintapp2.png

Wie man sehen kann ist Herr Zurbriggen Schweizer und die entsprechenden Kosten werden in Schweizer Franken angezeigt, während
Herr Nagy seine Forint bekommt.

Contents
--------

.. toctree::
   :maxdepth: 2

   googleapi
   flaskapp
   rest
   config

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
@class MIUImplementation;

@interface MIUClass : NSObject<NSCoding, NSCopying>

@property(nonatomic, strong) NSString *name;
@property(nonatomic, copy) NSString *superClass;
@property(nonatomic, strong) MIUImplementation *implementation;

@property(nonatomic, strong) NSSet *properties;
@property(nonatomic, strong) NSArray *conformedToProtocols; // contains |MIUProtocol *| objects
@property(nonatomic, strong) NSArray *conformedToProtocolsStrings; // contains |MIUProtocol *| objects

- (instancetype)initWithName:(NSString *)name
                  properties:(NSSet *)properties
           andImplementation:(MIUImplementation *)implementation
                  superClass:(NSString *)superClass
        conformedToProtocols:(NSArray *)conformedToProtocols;

- (instancetype)initWithName:(NSString *)name
                  properties:(NSSet *)properties
                  superClass:(NSString *)superClass
        conformedToProtocols:(NSArray *)conformedToProtocols;

- (BOOL)isBase;

@end


text:
use strict;
use warnings;

package Mail::Message::Body;
use vars '$VERSION';
$VERSION = '2.082';

use base 'Mail::Reporter';

use Carp;

use MIME::Types;
use File::Basename 'basename';

my MIME::Types $mime_types;

sub encode(@)
{   my ($self, %args) = @_;

    # simplify the arguments

    my $type_from = $self->type;
    my $type_to   = $args{mime_type} || $type_from->clone;
    $type_to = Mail::Message::Field->new('Content-Type' => $type_to)
        unless ref $type_to;

    if(my $charset = delete $args{charset})
    {   # Charset conversions are ignored for now.
        $type_to->attribute(charset => $charset);
    }

    my $transfer = $args{transfer_encoding} || $self->transferEncoding->clone;
    $transfer    = Mail::Message::Field->new('Content-Transfer-Encoding' =>
         $transfer) unless ref $transfer;

    # What will we do?
#   my $mime_was  = lc $type_from;
#   my $mime_to   = lc $type_to;

# If possible, update unify() too.
#   my $char_was  = $type_from->attribute('charset');
#   my $char_to   = $type_to->attribute('charset');

    my $trans_was = lc $self->transferEncoding;
    my $trans_to  = lc $transfer;

    #
    # The only translations implemented now is content transfer encoding.
    #

#warn "Translate ($trans_was) -> ($trans_to)\n";
    return $self if $trans_was eq $trans_to;

    my $bodytype  = $args{result_type} || ref $self;

    my $decoded;
    if($trans_was eq 'none') {$decoded = $self}
    elsif(my $decoder = $self->getTransferEncHandler($trans_was))
    {   $decoded = $decoder->decode($self, result_type => $bodytype) }
    else
    {   $self->log(WARNING =>
           "No decoder defined for transfer encoding $trans_was.");
        return $self;
    }

    my $encoded;
    if($trans_to eq 'none') {$encoded = $decoded}
    elsif(my $encoder = $self->getTransferEncHandler($trans_to))
    {   $encoded = $encoder->encode($decoded, result_type => $bodytype) }
    else
    {   $self->log(WARNING =>
           "No encoder defined for transfer encoding $trans_to.");
        return $decoded;
    }
    $encoded;
}

#------------------------------------------

sub check()
{   my $self     = shift;
    return $self if $self->checked;
    my $eol      = $self->eol;

    my $encoding = $self->transferEncoding->body;
    return $self->eol($eol)
       if $encoding eq 'none';

    my $encoder  = $self->getTransferEncHandler($encoding);

    my $checked
      = $encoder
      ? $encoder->check($self)->eol($eol)
      : $self->eol($eol);

    $checked->checked(1);
    $checked;
}

#------------------------------------------

sub encoded()
{   my $self = shift;

    return $self->check
        unless $self->transferEncoding eq 'none';

    $mime_types ||= MIME::Types->new;

    my $mime = $mime_types->type($self->type->body);
    $self->encode(transfer_encoding =>
         defined $mime ? $mime->encoding : 'base64');
}

#------------------------------------------

sub unify($)
{   my ($self, $body) = @_;
    return $self if $self==$body;

    my $mime     = $self->type;
    my $transfer = $self->transferEncoding;

    my $encoded  = $body->encode
     ( mime_type         => $mime
     , transfer_encoding => $transfer
     );

    # Encode makes the best of it, but is it good enough?

    my $newmime     = $encoded->type;
    return unless $newmime  eq $mime;
    return unless $transfer eq $encoded->transferEncoding;

# Character transformation not possible yet.
#   my $want_charset= $mime->attribute('charset')    || '';
#   my $got_charset = $newmime->attribute('charset') || '';
#   return unless $want_charset eq $got_charset;

    $encoded;
}

#------------------------------------------

sub isBinary()
{   my $self = shift;
    $mime_types ||= MIME::Types->new(only_complete => 1);
    my $type = $self->type                    or return 1;
    my $mime = $mime_types->type($type->body) or return 1;
    $mime->isBinary;
}

#------------------------------------------

sub isText() { not shift->isBinary }

#------------------------------------------

sub dispositionFilename(;$)
{   my $self = shift;
    my $raw;

    my $field;
    if($field = $self->disposition)
    {   $raw  = $field->attribute('filename')
             || $field->attribute('file')
             || $field->attribute('name');
    }

    if(!defined $raw && ($field = $self->type))
    {   $raw  = $field->attribute('filename')
             || $field->attribute('file')
             || $field->attribute('name');
    }

    return $raw unless @_;

    my $dir      = shift;
    my $filename = '';
    if(defined $raw)
    {   $filename = basename $raw;
        $filename =~ s/[^\w.-]//;
    }

    unless(length $filename)
    {   my $ext    = ($self->mimeType->extensions)[0] || 'raw';
        my $unique;
        for($unique = 'part-0'; 1; $unique++)
        {   my $out = File::Spec->catfile($dir, "$unique.$ext");
            open IN, "<", $out or last;  # does not exist: can use it
            close IN;
        }
        $filename = "$unique.$ext";
    }

    File::Spec->catfile($dir, $filename);
}

#------------------------------------------

my %transfer_encoder_classes =
 ( base64  => 'Mail::Message::TransferEnc::Base64'
 , binary  => 'Mail::Message::TransferEnc::Binary'
 , '8bit'  => 'Mail::Message::TransferEnc::EightBit'
 , 'quoted-printable' => 'Mail::Message::TransferEnc::QuotedPrint'
 , '7bit'  => 'Mail::Message::TransferEnc::SevenBit'
 );

my %transfer_encoders;   # they are reused.

sub getTransferEncHandler($)
{   my ($self, $type) = @_;

    return $transfer_encoders{$type}
        if exists $transfer_encoders{$type};   # they are reused.

    my $class = $transfer_encoder_classes{$type};
    return unless $class;

    eval "require $class";
    confess "Cannot load $class: $@\n" if $@;

    $transfer_encoders{$type} = $class->new;
}

#------------------------------------------

sub addTransferEncHandler($$)
{   my ($this, $name, $what) = @_;

    my $class;
    if(ref $what)
    {   $transfer_encoders{$name} = $what;
        $class = ref $what;
    }
    else
    {   delete $transfer_encoders{$name};
        $class = $what;
    }

    $transfer_encoder_classes{$name} = $class;
    $this;
}

1;


text:
Back

Chrome

Default

Installed

Chrome

Google Chrome's Default Icon. This icon is here to show you the side by side comparison

Maximal

Install

Chrome

Maximal Icon for Google Chrome

Squared

Install

Chrome

Make Chrome Even More Squared Than Before!

Lumino Square

Install

Chrome

Novus

Install

Chrome

GCon

Install

Chrome

Chrome themed GCon

Light Winter

Install

App Store

A Light Winter Themed App Store


text:
package com.wiley.autotest.selenium.driver;

import org.mockito.internal.stubbing.answers.ThrowsException;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.WrapsElement;
import org.testng.annotations.Test;

import java.util.Stack;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.sameInstance;
import static org.mockito.Mockito.mock;

public class FrameAwareWebElementTransformerTest {
    private final FrameAwareWebElementTransformer transformer =
            new FrameAwareWebElementTransformer(mock(WebDriver.class), new Stack<WebElement>());

    @Test(enabled = false, expectedExceptions = StaleElementReferenceException.class)
    public void testTryToAccessToStolenElement() {
        final WebElement stolenElement = givenStolenElement();
        final WebElement transformedStolenElement = transformer.apply(stolenElement);

        transformedStolenElement.isDisplayed();
    }

    @Test(enabled = false)
    public void testGetWrappedElementOfTransformedElement() {
        final WebElement element = givenElement();
        final WebElement transformedElement = transformer.apply(element);

        assertThat(((WrapsElement) transformedElement).getWrappedElement(), sameInstance(element));
    }

    private WebElement givenElement() {
        return mock(WebElement.class);
    }

    private WebElement givenStolenElement() {
        return mock(WebElement.class, new ThrowsException(new StaleElementReferenceException("stolen")));
    }

}


text:
namespace DAVA
{
class UIFadeTransition : public UIScreenTransition
{
public:
    UIFadeTransition();
    virtual ~UIFadeTransition();

    enum eType
    {
        FADE_MIX = 0,
        FADE_IN_FADE_OUT,
    };

    virtual void SetType(eType _type);
    virtual void Update(float32 timeElapsed);
    virtual void Draw(const UIGeometricData& geometricData);

private:
    eType type;
};
};

#endif // __DAVAENGINE_UI_MOVEIN_TRANSITION_H__


text:
<?php

namespace Doctrine\ODM\MongoDB\Mapping\Types;

/**
 * The Array type.
 *
 * @since       1.0
 * @author      Jonathan H. Wage <jonwage@gmail.com>
 * @author      Roman Borschel <roman@code-factory.org>
 * @author      Bulat Shakirzyanov <mallluhuct@gmail.com>
 */
class HashType extends Type
{
    public function convertToDatabaseValue($value)
    {
        return $value !== null ? (object) $value : null;
    }

    public function convertToPHPValue($value)
    {
        return $value !== null ? (array) $value : null;
    }
}


text:
@interface CordovaHttpPlugin : CDVPlugin

- (void)useBasicAuth:(CDVInvokedUrlCommand*)command;
- (void)setHeader:(CDVInvokedUrlCommand*)command;
- (void)enableSSLPinning:(CDVInvokedUrlCommand*)command;
- (void)acceptAllCerts:(CDVInvokedUrlCommand*)command;
- (void)post:(CDVInvokedUrlCommand*)command;
- (void)get:(CDVInvokedUrlCommand*)command;
- (void)put:(CDVInvokedUrlCommand*)command;
- (void)delete:(CDVInvokedUrlCommand*)command;
- (void)uploadFile:(CDVInvokedUrlCommand*)command;
- (void)downloadFile:(CDVInvokedUrlCommand*)command;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--  Copyright (C) 2013 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

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

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

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="mr_system_route_name" msgid="5441529851481176817">"Systeem"</string>
    <string name="mr_user_route_category_name" msgid="7498112907524977311">"Apparaten"</string>
    <string name="mr_media_route_button_content_description" msgid="4271159405637008602">"Media-uitvoer"</string>
    <string name="mr_media_route_chooser_title" msgid="7106830097177242655">"Verbinding maken met apparaat"</string>
    <string name="mr_media_route_chooser_searching" msgid="7553005460920830010">"Zoeken naar apparaten…"</string>
    <string name="mr_media_route_controller_disconnect" msgid="109793632378378069">"Verbinding verbreken"</string>
</resources>


text:
<form (ngSubmit)="submit()" [formGroup]="formGroup">
  <ion-progress-bar *ngIf="isLoading" type="indeterminate"></ion-progress-bar>
  <mat-horizontal-stepper (selectionChange)="stepChanged($event)"
                          (animationDone)="stepAnimationDone.next($event)"
                          [linear]="true"
                          labelPosition="bottom"
                          #stepper>
    <ng-template matStepperIcon="edit">
      <ion-icon color="light" name="pencil" class="stepper-icon"></ion-icon>
    </ng-template>
    <ng-template matStepperIcon="done">
      <ion-icon color="light" name="checkmark" class="stepper-icon"></ion-icon>
    </ng-template>
    <ng-template let-index="index" matStepperIcon="number">
      <ion-text color="light">{{ index + 1 }}</ion-text>
    </ng-template>
    <mat-step [label]="'app.timeblockr.services' | translate" [stepControl]="formGroup.controls.product">
      <ion-item class="ion-item-no-padding">
        <ion-label position="floating">{{ 'app.timeblockr.service' | translate }}</ion-label>
        <ionic-selectable
          #productSelect
          [canSearch]="true"
          [clearButtonText]="'app.timeblockr.cancel' | translate"
          [closeButtonText]="'app.timeblockr.close' | translate"
          [items]="products"
          [searchFailText]="'app.timeblockr.no_services_found' | translate"
          [searchPlaceholder]="'app.timeblockr.search' | translate"
          formControlName="product"
          itemTextField="Name"
          itemValueField="Guid"
        ></ionic-selectable>
      </ion-item>

        <ion-button type="button" (click)="stepper.next()" [disabled]="formGroup.controls.product.invalid">
          {{ 'app.timeblockr.next' | translate }}
        </ion-button>

    </mat-step>
    <mat-step [label]="'app.timeblockr.location_date_and_time' | translate" [stepControl]="formGroup.controls.time">
      <ion-list>
        <ion-item class="ion-item-no-padding">
          <ion-label>{{ 'app.timeblockr.location' | translate }}</ion-label>
          <ion-select #locationSelect
                      [cancelText]="'app.timeblockr.cancel' | translate"
                      [okText]="'app.timeblockr.ok' | translate"
                      formControlName="location"
                      required>
            <ion-select-option *ngFor="let location of locations" [value]="location">
              {{ location.Name }}
            </ion-select-option>
          </ion-select>
        </ion-item>
        <ion-item class="ion-item-no-padding">
          <ion-label>{{ 'app.timeblockr.date' | translate }}</ion-label>
          <mat-form-field>
            <input (click)="datePicker.open()"
                   [matDatepickerFilter]="dateFilter"
                   [matDatepicker]="datePicker"
                   formControlName="date"
                   matInput
                   readonly
                   required>
            <mat-datepicker-toggle [for]="datePicker" matSuffix></mat-datepicker-toggle>
            <mat-datepicker #datePicker></mat-datepicker>
          </mat-form-field>
        </ion-item>
        <ion-item [class.hidden]="formGroup.controls.date.invalid" class="ion-item-no-padding">
          <ion-label>{{ 'app.timeblockr.time' | translate }}</ion-label>
          <ion-select #timePicker
                      [cancelText]="'app.timeblockr.cancel' | translate"
                      [okText]="'app.timeblockr.ok' | translate"
                      formControlName="time"
                      required>
            <ion-select-option *ngFor="let time of timeSlots" [value]="time.value">
              {{ time.date | date : 'HH:mm' }}
            </ion-select-option>
          </ion-select>
        </ion-item>
      </ion-list>

        <ion-button type="button" (click)="stepper.previous()"
                    color="light">{{ 'app.timeblockr.back' | translate }}</ion-button>
        <ion-button type="button" (click)="stepper.next()" [disabled]="formGroup.controls.time.invalid">
          {{ 'app.timeblockr.next' | translate }}
        </ion-button>

    </mat-step>
    <mat-step [label]="'app.timeblockr.data' | translate" [stepControl]="formGroup.controls.dynamicFields">
      <ion-list>
        <ng-container formGroupName="dynamicFields">
          <ng-container *ngFor="let field of templateDynamicFields">
            <ion-item>
              <ion-label position="floating">
                {{ field.field.Name }} *
              </ion-label>
              <ng-container [ngSwitch]="field.type">
                <ion-input *ngSwitchCase="'input'"
                           [formControlName]="field.field.Key"
                           [maxlength]="field.field.MaxLength"
                           [required]="field.field.IsRequired"
                           [type]="field.inputType"></ion-input>
                <ion-select *ngSwitchCase="'select'"
                            [formControlName]="field.field.Key"
                            [required]="field.field.IsRequired">
                  <ion-select-option *ngFor="let option of field.field.OptionValuesList" [value]="option.Value">
                    {{ option.Text }}
                  </ion-select-option>
                </ion-select>
              </ng-container>
            </ion-item>
            {{ errorMsg }}
          </ng-container>
        </ng-container>
      </ion-list>

        <ion-button type="button" (click)="stepper.previous()"
                    color="light">{{ 'app.timeblockr.back' | translate }}</ion-button>
        <ion-button type="button" (click)="stepper.next()" [disabled]="formGroup.controls.dynamicFields.invalid">
          {{ 'app.timeblockr.next' | translate }}
        </ion-button>

    </mat-step>
    <mat-step [label]="'app.timeblockr.confirm' | translate" class="last-step">

{{ 'app.timeblockr.services' | translate }}

      <ng-container *ngIf="formGroup.controls.product.value as product">

{{ product.Name }}

      </ng-container>
      <ng-container *ngIf="formGroup.controls.location.value as location">

{{ 'app.timeblockr.location' | translate }}

{{ location.Name }}

{{ location.Street }} {{ location.StreetNumber || '' }} {{ location.StreetNumberAddition || '' }}

{{ location.PostalCode}} {{ location.City }}

      </ng-container>

{{ 'app.timeblockr.date' | translate }}

{{ selectedTime | date : 'medium' }}

{{ 'app.timeblockr.data' | translate }}

      <ion-list>
        <ion-item *ngFor="let field of templateDynamicFields" class="ion-item-no-padding">
          <ion-label>{{ field.field.Name}}</ion-label>
          <ion-note color="contrast" slot="end">{{ getFieldValue(field) }}</ion-note>
        </ion-item>
      </ion-list>

        <ion-button type="button" (click)="stepper.previous()"
                    color="light">{{ 'app.timeblockr.back' | translate }}</ion-button>
        <ion-button [disabled]="isLoading"
                    type="submit">{{ 'app.timeblockr.book_appointment' | translate }}</ion-button>

    </mat-step>
  </mat-horizontal-stepper>
</form>


text:
'use strict';

var util = require('./<%= yo_front_src %>/gulp/util');
util.checkIfEnvIsValid();

var gulp = require('gulp');
var $    = require('gulp-load-plugins')();
var del  = require('del');

gulp.task('scripts', function() {
    var browserify = require('browserify');
    var source     = require('vinyl-source-stream');
    var buffer     = require('vinyl-buffer');
    var glob       = require('glob');
    var path       = require('path');
    var Q          = require('q');

    del.sync(util.dest(util.jsDestDir));

    var promises = [];
    glob.sync(util.src('scripts/*.js')).forEach(function(scriptPath) {
        var deferred = Q.defer();
        promises.push(deferred.promise);

        browserify({
            entries: scriptPath
            ,debug: util.isEnv('dev') // Triggers sourcemap generation
            // ,paths: [util.src('bower_components')]
        })
        .bundle()
        .on('error', util.handleError)
        .pipe(source(path.basename(scriptPath)))
        .pipe(buffer())
        .pipe($.if(util.isEnv('prod'), $.uglify({ mangle: false })))
        .pipe(gulp.dest(util.dest('js')))
        .on('finish', function() { deferred.resolve() });
    });

    return Q.all(promises);
});

gulp.task('styles', function () {
    del.sync(util.dest(util.cssDestDir));

    return gulp.src(util.src('styles/*.scss'))
        .pipe($.if(util.isEnv('dev'), $.sourcemaps.init()))
        .pipe($.sass({
            includePaths: [util.src('bower_components')],
            // Used by the `image-url` sass function
            imagePath: '../' + util.imagesDestDir
        })
        .on('error', util.handleError))
        .pipe($.autoprefixer({browsers: ['> 1%']}))
        .pipe($.if(util.isEnv('dev'), $.sourcemaps.write()))
        .pipe($.if(util.isEnv('prod'), $.cssmin()))
        .pipe(gulp.dest(util.dest('css')));
});

gulp.task('vendors', function() {
    if (!util.isEnv('dev')) {
        return;
    }

    var Q = require('q');

    // Promises are used here, so that the task finished console log would be
    // accurate.
    var promises = [];

    del.sync(util.dest(util.vendorDestDir));

    (function () {
        // Copy stuff into the vendor dir
        var deferred = Q.defer();
        promises.push(deferred.promise);

        console.log('Copying files to the "' + util.dest(util.vendorDestDir) + '" dir...');
        gulp
            .src([
                util.src('bower_components/jquery/dist/jquery.min.js'),
                // ,util.src('bower_components/ckeditor/**/*')
            ], {base: util.src('bower_components')})
            .pipe(gulp.dest(util.dest(util.vendorDestDir)))
            .on('finish', function() { deferred.resolve() });
    })();

    (function () {
        // Concatenate files into vendor.js
        var deferred = Q.defer();
        promises.push(deferred.promise);

        console.log('Creating "vendor.js"...');
        gulp
            .src([
                util.src('bower_components/modernizr/modernizr.js')
                // ,util.src('bower_components/foundation/js/foundation.min.js')
            ])
            .pipe($.concat('vendor.js'))
            // Careful with this, sometimes it mangle's too aggressively. In
            // those cases, try `$.uglify({ mangle: false })` or change the
            // library entirely if you want
            .pipe($.uglify())
            .pipe(gulp.dest(util.dest(util.vendorDestDir)))
            .on('finish', function() { deferred.resolve() });
    })();

    (function () {
        // Concatenate files into vendor.css
        var deferred = Q.defer();
        promises.push(deferred.promise);

        console.log('Creating "vendor.css"...');
        gulp
            .src([
                util.src('bower_components/normalize.css/normalize.css')
                // ,util.src('bower_components/foundation/js/foundation.min.js')
            ])
            .pipe($.cssmin())
            .pipe($.concat('vendor.css'))
            .pipe(gulp.dest(util.dest(util.vendorDestDir)))
            .on('finish', function() { deferred.resolve() });
    })();

    return Q.all(promises);
});

gulp.task('images', function () {
    if (!util.isEnv('dev')) {
        return;
    }

    return gulp
        .src(util.dest(util.imagesDestDir + '/**/*'))
        .pipe($.imagemin({
            progressive: true,
            interlaced: true
        }))
        .pipe(gulp.dest(util.dest(util.imagesDestDir)));
});

gulp.task('watch', function() {
    if (!util.isEnv('dev')) {
        return;
    }

    var notifier = require('node-notifier');

    $.watch(util.src('styles/**/*.scss'), function () {
        gulp.start('styles');
    });

    $.watch(util.src('scripts/**/*.js'), function () {
        gulp.start('scripts');
    });

    $.watch(util.src('sprites/**/*.png'), function () {
        gulp.start('sprites');
    });

    $.watch(util.dest(util.imagesDestDir + '/**/*'), function () {
        notifier.notify({
            'title': 'Reminder',
            'message': 'It seems you added some images. Don\'t forget to run `gulp images` to optimise them!'
        });
    });
});

gulp.task('build', ['scripts', 'styles']);

gulp.task('default', ['build']);


text:
#pragma once

#include <SQLiteCpp/Exception.h>

namespace SQLite {

// Foward declaration
class Database;

/**
 * @brief RAII encapsulation of a SQLite Savepoint.
 *
 * A Savepoint is a way to group multiple SQL statements into an atomic
 * secureced operation; either it succeeds, with all the changes commited to the
 * database file, or if it fails, all the changes are rolled back to the initial
 * state at the start of the savepoint.
 *
 * This method also offers big performances improvements compared to
 * individually executed statements.
 *
 * Caveats:
 *
 * 1) Calling COMMIT or commiting a parent transaction or RELEASE on a parent
 * savepoint will cause this savepoint to be released.
 *
 * 2) Calling ROLLBACK or rolling back a parent savepoint will cause this
 * savepoint to be rolled back.
 *
 * 3) This savepoint is not saved to the database until this and all savepoints
 * or transaction in the savepoint stack have been released or commited.
 *
 * See also: https://sqlite.org/lang_savepoint.html
 *
 * Thread-safety: a Transaction object shall not be shared by multiple threads,
 * because:
 *
 * 1) in the SQLite "Thread Safe" mode, "SQLite can be safely used by multiple
 * threads provided that no single database connection is used simultaneously in
 * two or more threads."
 *
 * 2) the SQLite "Serialized" mode is not supported by SQLiteC++, because of the
 * way it shares the underling SQLite precompiled statement in a custom shared
 * pointer (See the inner class "Statement::Ptr").
 */

class Savepoint {
   public:
    /**
     * @brief Begins the SQLite savepoint
     *
     * @param[in] aDatabase the SQLite Database Connection
     * @param[in] aName the name of the Savepoint
     *
     * Exception is thrown in case of error, then the Savepoint is NOT
     * initiated.
     */
    Savepoint(Database& aDatabase, const std::string& name);

    // Savepoint is non-copyable
    Savepoint(const Savepoint&) = delete;
    Savepoint& operator=(const Savepoint&) = delete;

    /**
     * @brief Safely rollback the savepoint if it has not been commited.
     */
    ~Savepoint();

    /**
     * @brief Commit and release the savepoint.
     */
    void release();

    /**
     * @brief Rollback the savepoint
     */
    void rollback();

   private:
    Database& mDatabase;        ///< Reference to the SQLite Database Connection
    std::string msName;         ///< Name of the Savepoint
    bool mbReleased = false;    ///< True when release has been called
};
}  // namespace SQLite


text:
Demo example for Raspberry Pi status

## Install & Run

```
pip install paho-mqtt httplib2
python main.py
```

## Push notification

Please edit push.py and set your mobile phone ids (go to IoT Manager - Statistics - IDS)

```
python push.py
```


text:
/*
 You could also use a class for a controller, but if you work
 with $scope and not the controller-as syntax a function makes
 more sense, because most of the code would anyway go to the
 constructor if you would use a class.
 */

export default class HomeController {

    /*@ngInject;*/
    constructor(PersonService, $scope) {
        PersonService.getPerson().then(person => {
            this.person = person;
        });

        $scope.greeting = "Hello, ES6!";
    }

}


text:
namespace PublicCounterCompiler
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Security.Cryptography;
    using System.Text;

    /// <summary>
    /// Maps block instance counters to their counter index
    /// </summary>
    class DerivedCounterRegisterMap
    {
        /// <summary>
        /// Adds a counter the list of block instance counters.
        /// </summary>
        /// <param name="counterName">The name of the counter.</param>
        public void AddCounter(string counterName)
        {
            registerMap[counterName] = globalRegisterIndex;
            ++globalRegisterIndex;
        }

        /// <summary>
        /// Gets the counter index for a block instance counter.
        /// </summary>
        /// <param name="counterName">The name of the counter.</param>
        /// <returns>Index of counter, or -1 if not found</returns>
        public int GetCounterIndex(string counterName)
        {
            try
            {
                if (!registerMap.ContainsKey(counterName))
                    return -1;
                return registerMap[counterName];
            }
            catch
            {
                return -1;
            }
        }

        /// <summary>
        /// Gets all the counter indices for the indicated block instance counter template.
        /// </summary>
        /// <param name="counterName">The base name of the counter.</param>
        /// <returns>Ordered list of indices</returns>
        public List<int> GetAllCounterIndices(string counterNameBase)
        {
            List<int> indices = new List<int>();

            int baseCounterIndex = 0;

            while (true)
            {
                string counterName = counterNameBase.Replace("*", baseCounterIndex.ToString());

                int registerIndex = GetCounterIndex(counterName);

                if (registerIndex < 0)
                    break;

                indices.Add(registerIndex);

                ++baseCounterIndex;
            }

            return indices;
        }

        /// <summary>
        /// Global register index of the block instance counter within this counter.
        /// </summary>
        private int globalRegisterIndex = 0;

        /// <summary>
        /// Map of block instance counters and indices.
        /// </summary>
        private Dictionary<string, int> registerMap = new Dictionary<string, int>();
    }

    /// <summary>
    /// Contains information about a public counter definition
    /// </summary>
    public class DerivedCounterDef
    {
        /// <summary>
        /// MD5 hash function used by reproducible counter GUID generation based on the
        /// counter name and description
        /// </summary>
        MD5 md5Hash = MD5.Create();

        /// <summary>
        /// Map of name referenced counters to their index
        /// </summary>
        private DerivedCounterRegisterMap counterRegisterMap = new DerivedCounterRegisterMap();

        /// <summary>
        /// Block instance register base name and the range of counter indices it covers.
        /// </summary>
        private class RegisterBaseNameRange
        {
            public string registerBaseName;
            public int startIndex;
            public int endIndex;
        }

        /// <summary>
        /// List of block instance register base names and the ranges of counter indices they cover.
        /// </summary>
        List<RegisterBaseNameRange> registerBaseNameRanges = new List<RegisterBaseNameRange>();

        /// <summary>
        /// Adds a block instance register to the register map.
        /// </summary>
        /// <param name="registerCounterName">Name of the block instance register.</param>
        public void AddRegisterCounter(string registerCounterName)
        {
            counterRegisterMap.AddCounter(registerCounterName);
        }

        /// <summary>
        /// Returns the ending index of the last register counter.
        /// </summary>
        /// <returns>On success, the ending index of the last register counter.  Otherwise, -1.</returns>
        private int GetLastRegisterCounterEndingIndex()
        {
            if (registerBaseNameRanges.Count == 0)
            {
                return -1;
            }

            return registerBaseNameRanges[registerBaseNameRanges.Count - 1].endIndex;
        }

        /// <summary>
        /// Records a block instance register base name and its reference range.
        /// </summary>
        /// <param name="registerCounterBaseName">Base name of the block instance register.</param>
        /// <param name="startIndex">Starting index of the register.</param>
        /// <param name="endIndex">Ending index of the register.</param>
        public void AddRegisterCounterBaseNameRange(string registerCounterBaseName, int startIndex, int endIndex)
        {
            int offset = GetLastRegisterCounterEndingIndex();

            if (offset >= 0)
            {
                ++offset;
            }
            else
            {
                offset = 0;
            }

            RegisterBaseNameRange range = new RegisterBaseNameRange();

            range.registerBaseName = registerCounterBaseName;
            range.startIndex = startIndex + offset;
            range.endIndex = endIndex + offset;

            registerBaseNameRanges.Add(range);
        }

        /// <summary>
        /// Determine the block instance register base name by counter index.
        /// </summary>
        /// <param name="index">Counter index to lookup the block instance register base name for.</param>
        /// <param name="startIndex">Returned start index of the register.</param>
        /// <param name="endIndex">Returned end index of the register.</param>
        /// <returns>On success, the block instance register base name, and the start end end indices.  Otherwise, an empty string.</returns>
        public string GetRegisterCounterBaseNameForIndex(int index, out int startIndex, out int endIndex)
        {
            startIndex = -1;
            endIndex = -1;

            foreach (var register in registerBaseNameRanges)
            {
                if (index >= register.startIndex && index <= register.endIndex)
                {
                    startIndex = register.startIndex;
                    endIndex = register.endIndex;
                    return register.registerBaseName;
                }
            }

            Debug.Assert(false);
            return string.Empty;
        }

        /// <summary>
        /// Retrieves the index of a block instance register.
        /// </summary>
        /// <param name="counterName">Name of the block instance register.</param>
        /// <returns>Index of the block instance register</returns>
        public int GetRegisterCounterIndex(string counterName)
        {
            return counterRegisterMap.GetCounterIndex(counterName);
        }

        /// <summary>
        /// Retrieves all of the indices based on the wild-carded base block instance register template name.
        /// </summary>
        /// <param name="baseCounterName">Wild-cared template name of the block instance register.</param>
        /// <returns>True if the index is in the </returns>
        public List<int> GetAllRegisterCounterIndices(string baseCounterName)
        {
            return counterRegisterMap.GetAllCounterIndices(baseCounterName);
        }

        /// <summary>
        /// Structure for a hardware counter
        /// </summary>
        public class HardwareCounterDef : IEquatable<HardwareCounterDef>
        {
            /// <summary>
            /// Constructor
            /// </summary>
            public HardwareCounterDef(string counterName, int counterId)
            {
                Name = counterName;
                Id = counterId;
                Referenced = false;
            }

            /// <summary>
            /// ToString() conversion for a hardware counter definition
            /// </summary>
            override public string ToString()
            {
                return Id.ToString();
            }

            /// <summary>
            /// Equality operator
            /// </summary>
            public bool Equals(HardwareCounterDef other)
            {
                return Id == other.Id;
            }

            /// <summary>
            /// Hardware counter name
            /// </summary>
            public string Name
            {
                get;
            }

            /// <summary>
            /// Hardware counter id
            /// </summary>
            public int Id
            {
                get;
            }

            /// <summary>
            /// Whether the hardware counter has been referenced
            /// </summary>
            public bool Referenced
            {
                get;
                set;
            }
        };

        /// <summary>
        /// The list of internal counters.
        /// </summary>
        private List<HardwareCounterDef> _counters = new List<HardwareCounterDef>();

        /// <summary>
        /// Gets or sets the name of the counter.
        /// </summary>
        public string Name
        {
            get;
            set;
        }

        public bool ValidName()
        {
            return !string.IsNullOrEmpty(Name);
        }

        /// <summary>
        /// Gets or sets the counter group (aka category).
        /// </summary>
        public string Group
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the counter description.
        /// </summary>
        public string Desc
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the counter type.
        /// </summary>
        public string Type
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets usage information.
        /// </summary>
        public string Usage
        {
            get;
            set;
        }

        public bool ValidUsage()
        {
            return !string.IsNullOrEmpty(Usage);
        }

        /// <summary>
        /// Gets or sets the equation from which the counter should be computed.
        /// </summary>
        public string Comp
        {
            get;
            set;
        }

        public bool ValidEquation()
        {
            return !string.IsNullOrEmpty(Comp);
        }

        /// <summary>
        /// Gets or sets the readable comp for readable debugging, output, validation
        /// </summary>
        public string CompReadable
        {
            get;
            set;
        }

        /// <summary>
        /// Adds a counter the list of required internal counters for this public counter.
        /// </summary>
        /// <param name="counterIndex">The index of the internal counter to add.</param>
        public void AddCounter(string counterName, int counterIndex)
        {
            this._counters.Add(new HardwareCounterDef(counterName, counterIndex));
        }

        /// <summary>
        /// Gets a required counter based on the index from the computation equation.
        /// </summary>
        /// <param name="index">the index of the counter to get.</param>
        /// <returns>The 'global' index of the internal counter.</returns>
        public HardwareCounterDef GetCounter(int index)
        {
            return this._counters[index];
        }

        /// <summary>
        /// Get the number of internal counters used in this public counter.
        /// </summary>
        /// <returns>The number of counters used.</returns>
        public int GetCounterCount()
        {
            return this._counters.Count;
        }

        /// <summary>
        /// Clears the list of internal counters used.
        /// </summary>
        public void ClearCounters()
        {
            this._counters.Clear();
        }

        /// <summary>
        /// Checks to see if a 'global' index is available in the counters list.
        /// </summary>
        /// <param name="counterIndex">The 'global' index to find.</param>
        /// <returns>True if the index is in the </returns>
        public bool CounterDefined(int counterIndex)
        {
            return this._counters.Contains(new HardwareCounterDef(string.Empty, counterIndex));
        }

        /// <summary>
        /// Gets the list of internal counters.
        /// </summary>
        /// <returns>List of internal counters.</returns>
        public List<HardwareCounterDef> GetCounters()
        {
            return this._counters;
        }

        /// <summary>
        /// Generates a Guid for the counter using an MD5 hash of the counter name and description.
        /// </summary>
        /// <returns>Guid for the counter.</returns>
        public Guid GuidHash
        {
            get
            {
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(Name + Desc));

                StringBuilder sBuilder = new StringBuilder();

                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                Guid guid = new Guid(sBuilder.ToString());
                return guid;
            }
        }

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="MultiThemer" parent="Theme.AppCompat.DayNight.NoActionBar">
        <item name="android:navigationBarColor">?attr/colorPrimaryDark</item>
    </style>

</resources>


text:
package com.rodrigodev.xgen4j.test.code.codeNumericIdAndNumberAreGeneratedWhenSpecified.c1;

import com.rodrigodev.xgen4j.test.code.codeNumericIdAndNumberAreGeneratedWhenSpecified.RootException;
import com.rodrigodev.xgen4j.test.code.codeNumericIdAndNumberAreGeneratedWhenSpecified.RootException;
import com.rodrigodev.xgen4j.test.code.codeNumericIdAndNumberAreGeneratedWhenSpecified.ErrorCode;

/**
 * Autogenerated by XGen4J on January 1, 0001.
 */
public class C1Exception extends RootException {

    protected C1Exception(ErrorCode errorCode, String message) {
        super(errorCode, message);
    }

    protected C1Exception(ErrorCode errorCode, String message, Throwable cause) {
        super(errorCode, message, cause);
    }
}


text:
import ResponseHandler from '../helpers/ResponseHandler';

/**
 * Middleware class to handle verify/check User related
 * requests
 */
export default class UserMiddleware {
  /**
   * Middleware to check and handle validation of user creation request
   * @param {Object} request - Request Object
   * @param {Object} response - Response Object
   * @param {Function} next - Function call to move to next
   * @return {Void} - Returns void
   */
  static validateCreateRequest(request, response, next) {
    const { email, firstName, lastName, password } = request.body;
    if (!email || !firstName || !lastName || !password) {
      ResponseHandler.send400(response,
        { message: 'Incomplete registration data',
          data: request.body });
    } else if (password.length < 8 || password.length > 50) {
      ResponseHandler.send400(response,
      { message: 'Password should be between 8 and 50 letters' });
    } else if (request.body.id) {
      request.body.id = null;
      next();
    } else {
      next();
    }
  }

    /**
   * Method that checks and validates user get requests
   * @param {Object} request - Request Object
   * @param {Object} response - Response Object
   * @param {Function} next - Function call to continue with next function
   * @return {undefined}
   */
  static validateGetRequest(request, response, next) {
    if (request.query && Number(request.query.limit) < 1) {
      ResponseHandler.send400(
        response,
        { message: 'Invalid limit; limit should not be less than 1' }
      );
    } else if (request.query && Number(request.query.offset) < 0) {
      ResponseHandler.send400(
        response,
        { message: 'Invalid offset; offset should not be less than 1' }
      );
    } else {
      next();
    }
  }

  /**
   * Middleware to check and handle validation of user deletion request
   * @param {Object} request - Request Object
   * @param {Object} response - Response Object
   * @param {Function} next - Function call to move to next
   * @return {Void} - Returns void
   */
  static validateDeleteRequest(request, response, next) {
    const requesterRoleId = request.decoded.roleId;
    if (requesterRoleId !== 1) {
      ResponseHandler.send403(
        response,
        { message: 'Admin Privilege Required' }
      );
    } else {
      next();
    }
  }

  /**
   * Middleware to check and handle violation of user update
   * rules by the request
   * @param {Object} request - Request Object
   * @param {Object} response - Response Object
   * @param {Function} next - Function call to move to next
   * @return {undefined}
   */
  static validateUpdateRequest(request, response, next) {
    const updateId = Number(request.params.id);
    if (request.body.roleId === 1) {
      ResponseHandler.send403(
        response,
        { message: 'Cannot Update To Admin User' }
      );
    } else if (request.body.id) {
      ResponseHandler.send400(
        response,
        { message: 'Update User ID Not Allowed' }
      );
    } else if (request.body.email) {
      ResponseHandler.send400(
        response,
        { message: 'Email Updating Not Allowed' }
      );
    } else if (request.body.password &&
      (request.body.password.length < 8 || request.body.password.length > 50)) {
      ResponseHandler.send400(response, {
        message: 'Password length should range between 8 - 50 characters'
      });
    } else if (
      request.decoded.userId === updateId
      ||
      request.decoded.roleId === 1
    ) {
      next();
    } else {
      ResponseHandler.send403(response);
    }
  }
}


text:
""" MongoDB Backend - Uses aggregation pipeline

If you don't have a mongo server running

    $ conda install mongodb -y
    $ mongod &

>> from blaze import *

>> data = [(1, 'Alice', 100),
...        (2, 'Bob', -200),
...        (3, 'Charlie', 300),
...        (4, 'Denis', 400),
...        (5, 'Edith', -500)]

Migrate data into MongoDB

>> import pymongo
>> db = pymongo.MongoClient().db
>> db.mydata.drop()  # clear out old results
>> _ = into(db.mydata, data, columns=['id', 'name', 'amount'])

Objective: find the name of accounts with negative amount

Using MongoDB query language

>> db.mydata.aggregate([{'$match': {'amount': {'$lt': 0}}}, # doctest: +SKIP
..                      {'$project': {'name': 1, '_id': 0}}])['result']
[{'name': 'Bob'}, {'name': 'Edith'}]

Using Blaze

>> t = Data(db.mydata)
>> t[t.amount < 0].name
    name
0    Bob
1  Edith

>> db.mydata.drop()

Uses the aggregation pipeline
http://docs.mongodb.org/manual/core/aggregation-pipeline/
"""

from __future__ import absolute_import, division, print_function

import numbers
from operator import attrgetter

from pymongo.collection import Collection
from pymongo.database import Database

import fnmatch
from datashape.predicates import isscalar
from toolz import pluck, first, get, compose
import toolz
import datetime

from ..expr import (
    And,
    Arithmetic,
    Broadcast,
    By,
    Distinct,
    Eq,
    Expr,
    Field,
    FloorDiv,
    Ge,
    Gt,
    Head,
    Le,
    Like,
    Lt,
    Ne,
    Or,
    Projection,
    Reduction,
    Selection,
    SimpleSelection,
    Sort,
    Summary,
    Symbol,
    ceil,
    count,
    floor,
    math,
    max,
    mean,
    min,
    nelements,
    nunique,
    sum,
    symbol,
)
from ..expr.broadcast import broadcast_collect, Broadcastable
from ..expr.datetime import Day, Month, Year, Minute, Second, UTCFromTimestamp
from ..expr.optimize import simple_selections
from ..compatibility import _strtypes
from ..dispatch import dispatch

__all__ = ['MongoQuery']

@dispatch(Expr, Collection)
def pre_compute(expr, data, scope=None, **kwargs):
    return MongoQuery(data, [])

@dispatch(Expr, Database)
def pre_compute(expr, data, **kwargs):
    return data

class MongoQuery(object):
    """
    A Pair of a pymongo collection and a aggregate query

    We need to carry around both a pymongo collection and a list of
    dictionaries to feed into the aggregation pipeline.  This class
    carries around such a pair.

    Parameters
    ----------
    coll: pymongo.collection.Collection
        A single pymongo collection
    query: list of dicts
        A query to send to coll.aggregate

    >>> q = MongoQuery(db.my_collection, # doctest: +SKIP
    ...     [{'$match': {'name': 'Alice'}},
    ...      {'$project': {'name': 1, 'amount': 1, '_id': 0}}])
    """
    def __init__(self, coll, query):
        self.coll = coll
        self.query = tuple(query)

    def append(self, clause):
        return MongoQuery(self.coll, self.query + (clause,))

    def info(self):
        return self.coll, self.query

    def __eq__(self, other):
        return type(self) == type(other) and self.info() == other.info()

    def __hash__(self):
        return hash((type(self), self.info()))

@dispatch(Expr, (MongoQuery, Collection))
def optimize(expr, seq):
    return broadcast_collect(simple_selections(expr), no_recurse=SimpleSelection)

@dispatch(Head, MongoQuery)
def compute_up(t, q, **kwargs):
    return q.append({'$limit': t.n})

@dispatch(Broadcast, MongoQuery)
def compute_up(t, q, **kwargs):
    s = t._scalars[0]
    d = dict((s[c], symbol(c, s[c].dshape.measure)) for c in s.fields)
    expr = t._scalar_expr._subs(d)
    name = expr._name or 'expr_%d' % abs(hash(expr))
    return q.append({'$project': {name: compute_sub(expr)}})

binops = {'+': 'add',
          '*': 'multiply',
          '/': 'divide',
          '-': 'subtract',
          '%': 'mod'}

def compute_sub(t):
    """
    Build an expression tree in a MongoDB compatible way.

    Parameters
    ----------
    t : Arithmetic
        Scalar arithmetic expression

    Returns
    -------
    sub : dict
        An expression tree

    Examples
    --------
    >>> from blaze import Symbol
    >>> s = symbol('s', 'float64')
    >>> expr = s * 2 + s - 1
    >>> expr
    ((s * 2) + s) - 1
    >>> compute_sub(expr)
    {'$subtract': [{'$add': [{'$multiply': ['$s', 2]}, '$s']}, 1]}

    >>> when = symbol('when', 'datetime')
    >>> compute_sub(s + when.day)
    {'$add': ['$s', {'$dayOfMonth': '$when'}]}
    """
    if isinstance(t, _strtypes + (Symbol,)):
        return '$%s' % t
    elif isinstance(t, numbers.Number):
        return t
    elif isinstance(t, FloorDiv):
        return compute_sub(floor(t.lhs / t.rhs))
    elif isinstance(t, Arithmetic) and hasattr(t, 'symbol') and t.symbol in binops:
        op = binops[t.symbol]
        return {'$%s' % op: [compute_sub(t.lhs), compute_sub(t.rhs)]}
    elif isinstance(t, floor):
        x = compute_sub(t._child)
        return {'$subtract': [x, {'$mod': [x, 1]}]}
    elif isinstance(t, math.abs):
        x = compute_sub(t._child)
        return {'$cond': [{'$lt': [x, 0]},
                          {'$subtract': [0, x]},
                          x]}
    elif isinstance(t, ceil):
        x = compute_sub(t._child)
        return {'$add': [x, {'$subtract': [1, {'$mod': [x, 1]}]}]}
    elif isinstance(t, tuple(datetime_terms)):
        op = datetime_terms[type(t)]
        return {'$%s' % op: compute_sub(t._child)}
    elif isinstance(t, UTCFromTimestamp):
        return {'$add': [datetime.datetime.utcfromtimestamp(0),
                         {'$multiply': [1000, compute_sub(t._child)]}]}
    raise NotImplementedError('Operation %s not supported' % type(t).__name__)

@dispatch((Projection, Field), MongoQuery)
def compute_up(t, q, **kwargs):
    return q.append({'$project': dict((col, 1) for col in t.fields)})

@dispatch(SimpleSelection, MongoQuery)
def compute_up(expr, data, **kwargs):
    predicate = optimize(expr.predicate, data)

    if not isinstance(predicate, Broadcast):
        raise TypeError("Selection predicate must be a broadcastable "
                        "operation.\nReceived an expression of type %r.\n"
                        "Available broadcastable operations are (%s)" %
                        (type(predicate).__name__,
                         ', '.join(map(compose(repr, attrgetter('__name__')),
                                   Broadcastable))))

    s = predicate._scalars[0]
    d = dict((s[c], symbol(c, s[c].dshape.measure)) for c in s.fields)
    expr = predicate._scalar_expr._subs(d)
    return data.append({'$match': match(expr)})

@dispatch(Like, MongoQuery)
def compute_up(t, q, **kwargs):
    pats = dict((name, {'$regex': fnmatch.translate(pattern)})
                for name, pattern in t.patterns.items())
    return q.append({'$match': pats})

@dispatch(By, MongoQuery)
def compute_up(t, q, **kwargs):
    if not isinstance(t.grouper, (Field, Projection, Symbol)):
        raise ValueError("Complex By operations not supported on MongoDB.\n"
                "The grouping element must be a simple Field or Projection\n"
                "Got %s" % t.grouper)
    apply = optimize(t.apply, q)
    names = apply.fields
    return MongoQuery(q.coll, q.query +
    ({
        '$group': toolz.merge(
                    {'_id': dict((col, '$'+col) for col in t.grouper.fields)},
                    group_apply(apply)
                    )
     },
     {
         '$project': toolz.merge(dict((col, '$_id.'+col) for col in t.grouper.fields),
                                 dict((name, '$' + name) for name in names))
     }))

@dispatch(nunique, MongoQuery)
def compute_up(t, q, **kwargs):
    return MongoQuery(q.coll, q.query +
    ({'$group': {'_id': dict((col, '$'+col) for col in t.fields),
                 t._name: {'$sum': 1}}},
     {'$project': {'_id': 0, t._name: 1}}))

@dispatch(Distinct, MongoQuery)
def compute_up(t, q, **kwargs):
    return MongoQuery(q.coll, q.query +
    ({'$group': {'_id': dict((col, '$'+col) for col in t.fields)}},
     {'$project': toolz.merge(dict((col, '$_id.'+col) for col in t.fields),
                              {'_id': 0})}))

@dispatch(Reduction)
def group_apply(expr):
    """
    Dictionary corresponding to apply part of split-apply-combine operation

    >>> accounts = symbol('accounts', 'var * {name: string, amount: int}')
    >>> group_apply(accounts.amount.sum())
    {'amount_sum': {'$sum': '$amount'}}
    """
    key = expr._name
    col = '$' + expr._child._name
    if isinstance(expr, count):
        return {key: {'$sum': 1}}
    if isinstance(expr, sum):
        return {key: {'$sum': col}}
    if isinstance(expr, max):
        return {key: {'$max': col}}
    if isinstance(expr, min):
        return {key: {'$min': col}}
    if isinstance(expr, mean):
        return {key: {'$avg': col}}
    raise NotImplementedError("Reduction %s not yet supported in MongoDB"
                              % type(expr).__name__)

reductions = {mean: '$avg', count: '$sum', max: '$max', min: '$min', sum: '$sum'}

def scalar_expr(expr):
    if isinstance(expr, Broadcast):
        s = expr._scalars[0]
        d = dict((s[c], symbol(c, s[c].dshape.measure)) for c in s.fields)
        return expr._scalar_expr._subs(d)
    elif isinstance(expr, Field):
        return symbol(expr._name, expr.dshape.measure)
    else:
        # TODO: This is a hack
        # broadcast_collect should reach into summary, By, selection
        # And perform these kinds of optimizations itself
        expr2 = broadcast_collect(expr)
        if not expr2.isidentical(expr):
            return scalar_expr(expr2)

@dispatch(Summary)
def group_apply(expr):
    # TODO: implement columns variable more generally when Broadcast works
    reducs = expr.values
    names = expr.fields
    values = [(name, c, getattr(c._child, 'column', None) or name)
               for name, c in zip(names, reducs)]

    query = dict((k, {reductions[type(v)]: 1 if isinstance(v, count)
                                        else compute_sub(scalar_expr(v._child))})
                 for k, v, z in values)
    return query

@dispatch((count, nelements), MongoQuery)
def compute_up(t, q, **kwargs):
    name = t._name
    return q.append({'$group': {'_id': {}, name: {'$sum': 1}}})

@dispatch((sum, min, max, mean), MongoQuery)
def compute_up(t, q, **kwargs):
    name = t._name
    reduction = {sum: '$sum', min: '$min', max: '$max', mean: '$avg'}[type(t)]
    column = '$' + t._child._name
    arg = {'$group': {'_id': {}, name: {reduction: column}}}
    return q.append(arg)

@dispatch(Sort, MongoQuery)
def compute_up(t, q, **kwargs):
    return q.append({'$sort': {t.key: 1 if t.ascending else -1}})

datetime_terms = {Day: 'dayOfMonth',
                  Month: 'month',
                  Year: 'year',
                  Minute: 'minute',
                  Second: 'second'}

@dispatch(Field, Database)
def compute_up(expr, data, **kwargs):
    return getattr(data, expr._name)

@dispatch(Expr, Collection)
def post_compute(e, c, scope=None):
    """
    Calling compute on a raw collection?  Compute on an empty MongoQuery.
    """
    return post_compute(e, MongoQuery(c, ()), scope=scope)

def get_result(result):
    try:
        return result['result']
    except TypeError:
        return list(result)

@dispatch(Expr, MongoQuery)
def post_compute(e, q, scope=None):
    """
    Execute a query using MongoDB's aggregation pipeline

    The compute_up functions operate on Mongo Collection / list-of-dict
    queries.  Once they're done we need to actually execute the query on
    MongoDB.  We do this using the aggregation pipeline framework.

    http://docs.mongodb.org/manual/core/aggregation-pipeline/
    """
    scope = {'$project': toolz.merge({'_id': 0},  # remove mongo identifier
                                 dict((col, 1) for col in e.fields))}
    q = q.append(scope)

    if not e.dshape.shape:  # not a collection
        result = get_result(q.coll.aggregate(list(q.query)))[0]
        if isscalar(e.dshape.measure):
            return result[e._name]
        else:
            return get(e.fields, result)

    dicts = get_result(q.coll.aggregate(list(q.query)))

    if isscalar(e.dshape.measure):
        return list(pluck(e.fields[0], dicts, default=None))  # dicts -> values
    else:
        return list(pluck(e.fields, dicts, default=None))  # dicts -> tuples

@dispatch(Broadcast, MongoQuery)
def post_compute(e, q, scope=None):
    """Compute the result of a Broadcast expression.
    """
    columns = dict((col, 1) for qry in q.query
                   for col in qry.get('$project', []))
    scope = {'$project': toolz.merge({'_id': 0},  # remove mongo identifier
                                 dict((col, 1) for col in columns))}
    q = q.append(scope)
    dicts = get_result(q.coll.aggregate(list(q.query)))

    assert len(columns) == 1
    return list(pluck(first(columns.keys()), dicts))

def name(e):
    """

    >>> name(Symbol('x', 'int32'))
    'x'
    >>> name(1)
    1
    """
    if isinstance(e, Symbol):
        return e._name
    elif isinstance(e, Expr):
        raise NotImplementedError("Complex queries not yet supported")
    else:
        return e

# Reflective binary operator, e.g. (x < y) -> (y > x)
binop_swap = {Lt: Gt, Gt: Lt, Ge: Le, Le: Ge, Eq: Eq, Ne: Ne}

def match(expr):
    """ Match query for MongoDB

    Examples
    --------
    >>> x = symbol('x', 'int32')
    >>> name = symbol('name', 'string')
    >>> match(name == 'Alice')
    {'name': 'Alice'}
    >>> match(x > 10)
    {'x': {'$gt': 10}}
    >>> match(10 > x)
    {'x': {'$lt': 10}}
    >>> match((x > 10) & (name == 'Alice'))  # doctest: +SKIP
    {'x': {'$gt': 10}, 'name': 'Alice'}
    >>> match((x > 10) | (name == 'Alice'))
    {'$or': [{'x': {'$gt': 10}}, {'name': 'Alice'}]}
    """
    if not isinstance(expr.lhs, Expr):
        return match(binop_swap(type(expr))(expr.lhs, expr.rhs))
    if isinstance(expr, Eq):
        return {name(expr.lhs): name(expr.rhs)}
    if isinstance(expr, Lt):
        return {name(expr.lhs): {'$lt': expr.rhs}}
    if isinstance(expr, Le):
        return {name(expr.lhs): {'$lte': expr.rhs}}
    if isinstance(expr, Gt):
        return {name(expr.lhs): {'$gt': expr.rhs}}
    if isinstance(expr, Ge):
        return {name(expr.lhs): {'$gte': expr.rhs}}
    if isinstance(expr, And):
        return {'$and': [match(expr.lhs), match(expr.rhs)]}
    if isinstance(expr, Or):
        return {'$or': [match(expr.lhs), match(expr.rhs)]}
    if isinstance(expr, Ne):
        return {name(expr.lhs): {'$ne': expr.rhs}}
    raise NotImplementedError("Matching not supported on expressions of type "
                              "%r" % type(expr).__name__)


text:
New Program sheet

        <form data-ng-submit="create()" novalidate>
            <fieldset>

                    Order number
                        <input type="text" data-ng-model="orderNo" id="orderNo" class="form-control" placeholder="Eg: 000345" required>

                    Style number
                        <input type="text" data-ng-model="styleNo" id="styleNo" class="form-control" placeholder="Eg: 000123" required>

                    Work order number
                        <input type="text" data-ng-model="workOrderNo" id="workOrderNo" class="form-control" placeholder="Eg: 004353" required>

                    Work order date
                        <input type="text" data-ng-model="workOrderDate" id="workOrderDate" class="form-control" placeholder="dd/MM/YYYY" required>

                    Operator name
                        <input type="text" data-ng-model="operatorName" id="operatorName" class="form-control" placeholder="Eg: Mr. Bino Balan" required>

                    Operation name
                        <input type="text" data-ng-model="operationName" id="operationName" class="form-control" placeholder="Eg: Cutting" required>

                    Serial number
                        <input type="text" data-ng-model="sLNo" id="sLNo" class="form-control" placeholder="Eg: 000324" required>

                    Color
                        <input type="text" data-ng-model="color" id="color" class="form-control" placeholder="Eg: Orange" required>

                    Size
                        <input type="text" data-ng-model="size" id="size" class="form-control" placeholder="Eg: Large" required>

                    Quantity
                        <input type="text" data-ng-model="quantity" id="quantity" class="form-control" placeholder="Eg: 1000" required>

                    <input type="submit" class="btn btn-default">

            </fieldset>
        </form>


text:
param($installPath, $toolsPath, $package, $project)

. (Join-Path $toolsPath 'bin_tools.ps1')

$cmd = '.bin\npm.cmd'
Set-BuildAction $cmd 'None'
Update-BinPaths $cmd
Add-BinToPath $cmd


text:
<?php

namespace PHPExiftool\Driver\Tag\XMPMwgKw;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class HierarchicalKeywords6Applied extends AbstractTag
{

    protected $Id = 'KeywordsHierarchyChildrenChildrenChildrenChildrenChildrenApplied';

    protected $Name = 'HierarchicalKeywords6Applied';

    protected $FullName = 'MWG::Keywords';

    protected $GroupName = 'XMP-mwg-kw';

    protected $g0 = 'XMP';

    protected $g1 = 'XMP-mwg-kw';

    protected $g2 = 'Image';

    protected $Type = 'boolean';

    protected $Writable = true;

    protected $Description = 'Hierarchical Keywords 6 Applied';

    protected $flag_List = true;

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace dp2Circulation
{
    // 存储书目对象的集合。
    // 可以当作数组遍历,也可以通过记录路径快速获取对象
    public class BiblioStoreCollection : IEnumerable
    {
        List<BiblioStore> _lines = new List<BiblioStore>();

        Hashtable _recPathTable = new Hashtable();  // biblio_recpath --> BiblioStore

        public void Clear()
        {
            _lines.Clear();
            _recPathTable.Clear();
        }

        public IEnumerator GetEnumerator()
        {
            return this._lines.GetEnumerator();
        }

        public ICollection Keys
        {
            get
            {
                return this._recPathTable.Keys;
            }
        }

        public BiblioStore GetByRecPath(string strBiblioRecPath)
        {
            return this._recPathTable[strBiblioRecPath] as BiblioStore;
        }

        public bool Remove(BiblioStore biblio)
        {
            this._recPathTable.Remove(biblio.RecPath);
            return this._lines.Remove(biblio);
        }

        // TODO: 遇到 recpath 重复的,是否抛出异常?
        public void Add(BiblioStore biblio)
        {
            if (this._recPathTable.ContainsKey(biblio.RecPath) == true)
                throw new ArgumentException("路径为 '"+biblio.RecPath+"' 的书目记录不能重复添加");

            this._lines.Add(biblio);
            this._recPathTable[biblio.RecPath] = biblio;
        }
    }
}


text:
package org.apache.camel.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.camel.Predicate;
import org.apache.camel.Processor;
import org.apache.camel.model.language.ExpressionDefinition;
import org.apache.camel.processor.FilterProcessor;
import org.apache.camel.spi.RouteContext;

/**
 * Represents an XML <filter/> element
 *
 * @version
 */
@XmlRootElement(name = "filter")
@XmlAccessorType(XmlAccessType.FIELD)
public class FilterDefinition extends ExpressionNode {

    public FilterDefinition() {
    }

    public FilterDefinition(ExpressionDefinition expression) {
        super(expression);
    }

    public FilterDefinition(Predicate predicate) {
        super(predicate);
    }

    @Override
    public String toString() {
        return "Filter[" + getExpression() + " -> " + getOutputs() + "]";
    }

    @Override
    public String getShortName() {
        return "filter";
    }

    @Override
    public FilterProcessor createProcessor(RouteContext routeContext) throws Exception {
        return createFilterProcessor(routeContext);
    }

    @Override
    protected FilterProcessor createFilterProcessor(RouteContext routeContext) throws Exception {
        // filter EIP should have child outputs
        Processor childProcessor = this.createChildProcessor(routeContext, true);
        return new FilterProcessor(getExpression().createPredicate(routeContext), childProcessor);
    }

}


text:
require('../../modules/es.array.concat');

module.exports = require('../../internals/entry-unbind')('Array', 'concat');


text:
var lc_timer;
var lc_sound = new Array;
var lc_sound_started = false;

jQuery(document).ready(
    function () {
        jQuery('textarea[name=comment]').after( '

' );
		if (typeof jQuery('#secureimgdiv').on == 'function') {
			jQuery('#secureimgdiv').on('click', '#lc_reload_action', function() {
				lean_captcha_load_img();
				return false;
			});
            jQuery('#secureimgdiv').on('click', '#lc_audio_action', function() {
                jQuery(this).addClass('lc_loading');
                lean_captcha_load_audio(this);
                return false;
            });
		} else {
			jQuery('#secureimgdiv').live('click', '#lc_reload_action', function() {
				lean_captcha_load_img();
				return false;
			});
            jQuery('#secureimgdiv').live('click', '#lc_audio_action', function() {
                jQuery(this).addClass('lc_loading');
                lean_captcha_load_audio(this);
                return false;
            });
		}
        lean_captcha_load_img();
    }
);

function lean_captcha_load_img() {
    lc_sound = new Array;
    lc_sound_started = false;
    jQuery('#secureimgdiv').load(lean_captcha_object.ajax_url,
        {'action': 'lean_captcha_render', 'key' : lean_captcha_object.key},
        function () {
            var lc_timer;
            if (typeof lc_timer !== undefined) {
				clearTimeout(lc_timer);
			}

			lc_timer = setTimeout('lean_captcha_load_img();', 290000);
			lean_captcha_fix_tab_index();
		}
    );
}

function lean_captcha_audio_focus() {
	jQuery('#securitycode').focus();
	return false;
}

function lean_captcha_refresh_alert() {
	jQuery('.lean-captcha-refresh-notification').attr({'aria-hidden': false, 'role': 'alert'});
	setTimeout(function() {
		jQuery('#securitycode').focus();
	},1000);
	return false;
}

function lean_captcha_load_audio(anchor) {
    if (lc_sound_started) {
        return;
    }

    lc_sound_started = true;

    href = jQuery(anchor).attr('href');

    lc_sound[0] = new Howl({
        urls: [ href + '&c=0' ],
        format: 'mp3',
        onend: lean_captch_play_audio_1,
        autoplay:true,
        onplay: function () {
            jQuery('#lc_audio_action').removeClass('lc_loading').addClass('lc_playing');
        }
    });
    lc_sound[1] = new Howl({
        urls: [ href + '&c=1' ],
        format: 'mp3',
        onend: lean_captch_play_audio_2,
    });
    lc_sound[2] = new Howl({
        urls: [ href + '&c=2' ],
        format: 'mp3',
        onend: lean_captch_play_audio_3,
    });
    lc_sound[3] = new Howl({
        urls: [ href + '&c=3' ],
        format: 'mp3',
        onend: lean_captch_play_audio_4,
    });
    lc_sound[4] = new Howl({
        urls: [ href + '&c=4' ],
        format: 'mp3',
        onend: lean_captch_play_audio_5,
    });
    lc_sound[5] = new Howl({
        urls: [ href + '&c=5' ],
        format: 'mp3',
        onend: lean_captch_play_audio_6,
    });
    lc_sound[6] = new Howl({
        urls: [ href + '&c=6' ],
        format: 'mp3',
        onend: lean_captch_play_audio_7,
    });
    lc_sound[7] = new Howl({
        urls: [ href + '&c=7' ],
        format: 'mp3',
        onend: lean_captch_play_audio_8,
    });
    lc_sound[8] = new Howl({
        urls: [ href + '&c=8' ],
        format: 'mp3',
        onend: function () {
            lc_sound_started = false;
            jQuery('#lc_audio_action').removeClass('lc_loading').removeClass('lc_playing');
        }
    });
}

function lean_captch_play_audio_1() {
    lean_captch_play_audio(1);
}

function lean_captch_play_audio_2() {
    lean_captch_play_audio(2);
}

function lean_captch_play_audio_3() {
    lean_captch_play_audio(3);
}

function lean_captch_play_audio_4() {
    lean_captch_play_audio(4);
}

function lean_captch_play_audio_5() {
    lean_captch_play_audio(5);
}

function lean_captch_play_audio_6() {
    lean_captch_play_audio(6);
}

function lean_captch_play_audio_7() {
    lean_captch_play_audio(7);
}

function lean_captch_play_audio_8() {
    lean_captch_play_audio(8);
}

function lean_captch_play_audio_9() {
    lean_captch_play_audio(9);
}

function lean_captch_play_audio(i) {
    lc_sound[i].play();
}

function lean_captcha_fix_tab_index() {
    var tabindex = 1;
    jQuery('#commentform input,select,textarea,.lc_action').each(function() {
    	if (this.type != "hidden") {
	    var $input = jQuery(this);
	    $input.attr("tabindex", tabindex);
	    tabindex++;
        }
    });
}


text:
namespace Mgc {

class MAGICFM Integrate
{
public:
    // last parameter is for user-defined data
    typedef Real (*Function)(Real,void*);

    // Romberg integration
    static void SetOrder (int iOrder);
    static int GetOrder ();
    static Real RombergIntegral (Real fA, Real fB, Function oF,
        void* pvUserData = 0);

    // Gaussian quadrature
    static Real GaussianQuadrature (Real fA, Real fB, Function oF,
        void* pvUserData = 0);

protected:
    // parameters for Romberg integration
    static int ms_iOrder;
    static Real* ms_apfRom[2];

    // pre-main initialization and post-main termination
    static void Initialize ();
    static void Terminate ();
    friend class _IntegrateInitTerm;
};

} // namespace Mgc

#endif


text:
#include "CFErrorUtilities.h"
#include "CreateDisplayNameForURL.h"
#include "CFWrapper.h"

CFErrorRef SFB::CreateError(CFStringRef domain, CFIndex code, CFStringRef description, CFStringRef failureReason, CFStringRef recoverySuggestion)
{
	if(nullptr == domain)
		return nullptr;

	SFB::CFMutableDictionary errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
	if(!errorDictionary)
		return nullptr;

	if(description)
		CFDictionarySetValue(errorDictionary, kCFErrorLocalizedDescriptionKey, description);

	if(failureReason)
		CFDictionarySetValue(errorDictionary, kCFErrorLocalizedFailureReasonKey, failureReason);

	if(recoverySuggestion)
		CFDictionarySetValue(errorDictionary, kCFErrorLocalizedRecoverySuggestionKey, recoverySuggestion);

	return CFErrorCreate(kCFAllocatorDefault, domain, code, errorDictionary);
}

CFErrorRef SFB::CreateErrorForURL(CFStringRef domain, CFIndex code, CFStringRef descriptionFormatStringForURL, CFURLRef url, CFStringRef failureReason, CFStringRef recoverySuggestion)
{
	if(nullptr == domain)
		return nullptr;

	SFB::CFMutableDictionary errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
	if(!errorDictionary)
		return nullptr;

	if(descriptionFormatStringForURL && url) {
		CFDictionarySetValue(errorDictionary, kCFErrorURLKey, url);

		SFB::CFString displayName = CreateDisplayNameForURL(url);
		if(displayName) {
			SFB::CFString description = CFStringCreateWithFormat(kCFAllocatorDefault, nullptr, descriptionFormatStringForURL, displayName.Object());
			if(description)
				CFDictionarySetValue(errorDictionary, kCFErrorLocalizedDescriptionKey, description);
		}
	}

	if(failureReason)
		CFDictionarySetValue(errorDictionary, kCFErrorLocalizedFailureReasonKey, failureReason);

	if(recoverySuggestion)
		CFDictionarySetValue(errorDictionary, kCFErrorLocalizedRecoverySuggestionKey, recoverySuggestion);

	return CFErrorCreate(kCFAllocatorDefault, domain, code, errorDictionary);
}