text:
/**
 * Regression test for #1295
 *
 * Validate that creating a window without focus doesn't crash the app!
 */

import * as assert from "assert"

import * as Oni from "oni-api"

export const test = async (oni: Oni.Plugin.Api) => {
    await oni.automation.waitForEditors()

    // We'll execute two commands in quick succession:
    // :vsp
    // :wincmd p
    // This creates a new vertical split, and immediately moves back to the previous window

    const neovim = oni.editors.activeEditor.neovim

    const p1 = neovim.command(":vsp")
    const p2 = neovim.command(":wincmd p")

    await Promise.all([p1, p1])

    // Not sure of a deterministic way to wait for this, but we need
    // to wait for a redraw to come back from the editor
    await oni.automation.sleep(1000)

    const editorElements = document.getElementsByClassName("editor")
    assert.ok(editorElements.length > 0, "Validate an editor is still present")
}


text:
/*
 * 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.
 */
package io.trino.operator.aggregation;

import com.google.common.collect.ImmutableList;
import io.trino.spi.type.Type;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import static io.trino.spi.type.TinyintType.TINYINT;

public class TestApproximateSetGenericTinyint
        extends AbstractTestApproximateSetGeneric
{
    @Override
    protected Type getValueType()
    {
        return TINYINT;
    }

    @Override
    protected Object randomValue()
    {
        return ThreadLocalRandom.current().nextLong(Byte.MIN_VALUE, Byte.MAX_VALUE + 1);
    }

    @Override
    protected int getUniqueValuesCount()
    {
        return (Byte.MAX_VALUE - Byte.MIN_VALUE + 1) / 10;
    }

    @Override
    protected List<Object> getResultStabilityTestSample()
    {
        return ImmutableList.of(
                (long) Byte.MIN_VALUE,
                -100L,
                -1L,
                0L,
                1L,
                100L,
                (long) Byte.MAX_VALUE);
    }

    @Override
    protected String getResultStabilityExpected()
    {
        // This value should not be changed; it is used to test result stability for $approx_set
        // Result stability is important because a produced value can be persisted by a connector.
        return "020C0700C06D8B32C26AC934C09F6D598036D18501CB299F419CDFA14000CCDE";
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.terasology.reflection.metadata;

import com.google.common.base.Predicates;
import org.terasology.reflection.copy.CopyStrategyLibrary;
import org.terasology.reflection.reflect.InaccessibleFieldException;
import org.terasology.reflection.reflect.ReflectFactory;

import java.lang.reflect.Field;

/**
 * A standard class metadata implementation using FieldMetadata.
 */
public class DefaultClassMetadata<T> extends ClassMetadata<T, FieldMetadata<T, ?>> {

    /**
     * Creates a class metatdata
     *
     * @param id The id that identifies this class
     * @param type The type to create the metadata for
     * @param factory A reflection library to provide class construction and field get/set functionality
     * @param copyStrategyLibrary A copy strategy library
     * @throws NoSuchMethodException If the class has no default constructor
     */
    public DefaultClassMetadata(String id, Class<T> type, ReflectFactory factory,
                                CopyStrategyLibrary copyStrategyLibrary) throws NoSuchMethodException {
        super(id, type, factory, copyStrategyLibrary, Predicates.<Field>alwaysTrue());
    }

    @Override
    protected <V> FieldMetadata<T, V> createField(Field field, CopyStrategyLibrary copyStrategyLibrary,
                                                  ReflectFactory factory) throws InaccessibleFieldException {
        return new FieldMetadata<>(this, field, copyStrategyLibrary, factory);
    }
}


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'waitlisted'
require 'webmock/rspec'
require 'vcr'

WebMock.disable_net_connect!

VCR.configure do |config|
  config.cassette_library_dir = "spec/fixtures/vcr_cassettes"
  config.hook_into :webmock
end


text:
'''OpenGL extension SGIX.texture_lod_bias

Automatically generated by the get_gl_extensions script, do not edit!
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_SGIX_texture_lod_bias'
_DEPRECATED = False
GL_TEXTURE_LOD_BIAS_S_SGIX = constant.Constant( 'GL_TEXTURE_LOD_BIAS_S_SGIX', 0x818E )
GL_TEXTURE_LOD_BIAS_T_SGIX = constant.Constant( 'GL_TEXTURE_LOD_BIAS_T_SGIX', 0x818F )
GL_TEXTURE_LOD_BIAS_R_SGIX = constant.Constant( 'GL_TEXTURE_LOD_BIAS_R_SGIX', 0x8190 )

def glInitTextureLodBiasSGIX():
    '''Return boolean indicating whether this extension is available'''
    return extensions.hasGLExtension( EXTENSION_NAME )


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Verticillium nanum var. corticii Sacc.

### Remarks
null


text:
'------------------------------------------------------------------------------
' <auto-generated>
'     This code was generated by a tool.
'
'     Changes to this file may cause incorrect behavior and will be lost if
'     the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------

Option Strict On
Option Explicit On

Partial Public Class LogIn

    '''
    '''form1 control.
    '''
    '''<remarks>
    '''Auto-generated field.
    '''To modify move field declaration from designer file to code-behind file.
    '''</remarks>
    Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm

    '''
    '''lblError control.
    '''
    '''<remarks>
    '''Auto-generated field.
    '''To modify move field declaration from designer file to code-behind file.
    '''</remarks>
    Protected WithEvents lblError As Global.System.Web.UI.WebControls.Label

    '''
    '''txtUsername control.
    '''
    '''<remarks>
    '''Auto-generated field.
    '''To modify move field declaration from designer file to code-behind file.
    '''</remarks>
    Protected WithEvents txtUsername As Global.System.Web.UI.WebControls.TextBox

    '''
    '''txtPassword control.
    '''
    '''<remarks>
    '''Auto-generated field.
    '''To modify move field declaration from designer file to code-behind file.
    '''</remarks>
    Protected WithEvents txtPassword As Global.System.Web.UI.WebControls.TextBox

    '''
    '''lblStatus control.
    '''
    '''<remarks>
    '''Auto-generated field.
    '''To modify move field declaration from designer file to code-behind file.
    '''</remarks>
    Protected WithEvents lblStatus As Global.System.Web.UI.WebControls.Label

    '''
    '''chkRemember control.
    '''
    '''<remarks>
    '''Auto-generated field.
    '''To modify move field declaration from designer file to code-behind file.
    '''</remarks>
    Protected WithEvents chkRemember As Global.System.Web.UI.WebControls.CheckBox

    '''
    '''cmdLogIn control.
    '''
    '''<remarks>
    '''Auto-generated field.
    '''To modify move field declaration from designer file to code-behind file.
    '''</remarks>
    Protected WithEvents cmdLogIn As Global.System.Web.UI.WebControls.Button
End Class


text:
require "kandan/endpoints/github/engine"

module Kandan
  module Endpoints
    module Github
    end
  end
end


text:
module.exports = {
  catalan: require('./resources/catalan'),
  czech: require('./resources/czech'),
  danish: require('./resources/danish'),
  dutch: require('./resources/dutch'),
  ukacd: require('./resources/ukacd'),
  finnish: require('./resources/finnish'),
  french: require('./resources/french'),
  german: require('./resources/german'),
  hungarian: require('./resources/hungarian'),
  icelandic: require('./resources/icelandic'),
  italian: require('./resources/italian'),
  latin: require('./resources/latin'),
  norwegian: require('./resources/norwegian'),
  polish: require('./resources/polish'),
  slovak: require('./resources/slovak'),
  spanish: require('./resources/spanish'),
  vietnamese: require('./resources/vietnamese')
}


text:
These instructions were tested on MacOSX 10.11.1 (El Capitan).

1. Install Homebrew: http://www.howtogeek.com/211541/homebrew-for-os-x-easily-installs-desktop-apps-and-terminal-utilities/

2. Install dependencies:

  ```
  brew update
  brew upgrade
  brew install boost --with-python
  brew install ffmpeg swig boost-python xerces-c doxygen git cmake
  sudo brew cask install java
  brew install xsd
  brew unlink xsd
  brew install mono
  brew link --overwrite xsd
  ```

3. Clone and build Project Malmo:
    1. `git clone https://github.com/Microsoft/malmo.git ~/MalmoPlatform`
    2. `wget https://raw.githubusercontent.com/bitfehler/xs3p/1b71310dd1e8b9e4087cf6120856c5f701bd336b/xs3p.xsl -P ~/MalmoPlatform/Schemas`
    3. Add `export MALMO_XSD_PATH=~/MalmoPlatform/Schemas` to your `~/.bashrc` and do `source ~/.bashrc`
    3. `cd MalmoPlatform`
    4. `mkdir build`
    5. `cd build`
    6. `cmake ..`
    7. `make install`
    8. Then you can run the samples that are installed ready-to-run in e.g. `install/Python_Examples`

4. Run the tests:
    1. `cd MalmoPlatform/build`
    2. `ctest -E Integration` to run a smaller set of tests (exclude the integration tests).
    3. `ctest` to run all the tests


text:
/* IE fix */
svg {
    overflow: hidden;
}

#classView {
    position: relative;
    height: 100%;
}

#svgContainer {
    z-index: 0;
    position: relative;
    height: 100%;
    cursor: -webkit-grab; cursor: -moz-grab;
}

.uml-class-name-rect {
    /*fill: lightgray;*/
}

.uml-class-attrs-rect, .uml-class-methods-rect, .uml-class-queries-rect, .uml-class-xdatas-rect {
    fill: white;
}

text {
    font-family: monospace;
}

.centralText {
    display: table;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    text-align: center;
}

.centralText > div {
    display: table-cell;
    vertical-align: middle;
}

.uml-class-name-text {
    cursor: help;
    -webkit-transition: all .2s ease;
    -moz-transition: all .2s ease;
    -o-transition: all .2s ease;
    transition: all .2s ease;
}

.uml-class-name-text:hover {
    fill: red;
}

.uml-class-attrs-label {
    font-family: monospace;
    font-weight: 900;
    fill: rgb(255, 97, 0);
}

.uml-class-methods-label {
    font-family: monospace;
    font-weight: 900;
    fill: blue;
}

.uml-class-queries-label {
    font-family: monospace;
    font-weight: 900;
    fill: #0d0;
}

.uml-class-params-label {
    font-family: monospace;
    font-weight: 900;
    fill: magenta;
}

.uml-class-xdatas-label {
    font-family: monospace;
    font-weight: 900;
    fill: #0ab;
}

.line-clickable {
    cursor: pointer;
    -webkit-transition: all .2s ease;
    -moz-transition: all .2s ease;
    -o-transition: all .2s ease;
    transition: all .2s ease;
}

.line-clickable:hover {
    fill: red;
}

.line-selected {
    fill: red;
    text-shadow: 0 1px 3px #CCC;
    -webkit-transition: all .2s ease;
    -moz-transition: all .2s ease;
    -o-transition: all .2s ease;
    transition: all .2s ease;
}

.inlineSearchBlock {
    display: inline-block;
    vertical-align: bottom;
}

#diagramSearch {
    display: block;
    box-sizing: border-box;
    border: 1px solid gray;
    border-radius: 5px;
    width: 200px;
    margin: 4px 0 4px 4px;
    height: 22px;
}

.element.highlighted {
    outline: 4px solid rgba(255, 0, 0, 0.6);
}

.element.uml.Class .tool-remove {
    display: none;
    cursor: pointer;
}

.element.uml.Class:hover .tool-remove {
    display: block;
}

.marker-source, .marker-target {
    vector-effect: none !important;
}

.connection {
    stroke: black;
}


text:
import * as Accordion from './Accordion';
import * as Alert from './Alert';
import * as Badge from './Badge';
import * as Breadcrumb from './Breadcrumb';
import * as BreadcrumbItem from './BreadcrumbItem';
import * as Button from './Button';
import * as ButtonGroup from './ButtonGroup';
import * as ButtonToolbar from './ButtonToolbar';
import * as Carousel from './Carousel';
import * as CarouselCaption from './CarouselCaption';
import * as CarouselItem from './CarouselItem';
import * as Checkbox from './Checkbox';
import * as Clearfix from './Clearfix';
import * as Col from './Col';
import * as Collapse from './Collapse';
import * as ControlLabel from './ControlLabel';
import * as Dropdown from './Dropdown';
import * as DropdownButton from './DropdownButton';
import * as DropdownMenu from './DropdownMenu';
import * as DropdownToggle from './DropdownToggle';
import * as Fade from './Fade';
import * as Form from './Form';
import * as FormControl from './FormControl';
import * as FormControlFeedback from './FormControlFeedback';
import * as FormControlStatic from './FormControlStatic';
import * as FormGroup from './FormGroup';
import * as Glyphicon from './Glyphicon';
import * as Grid from './Grid';
import * as HelpBlock from './HelpBlock';
import * as Image from './Image';
import * as InputGroup from './InputGroup';
import * as InputGroupAddon from './InputGroupAddon';
import * as InputGroupButton from './InputGroupButton';
import * as Jumbotron from './Jumbotron';
import * as Label from './Label';
import * as ListGroup from './ListGroup';
import * as ListGroupItem from './ListGroupItem';
import * as Media from './Media';
import * as MediaBody from './MediaBody';
import * as MediaHeading from './MediaHeading';
import * as MediaLeft from './MediaLeft';
import * as MediaList from './MediaList';
import * as MediaListItem from './MediaListItem';
import * as MediaRight from './MediaRight';
import * as MenuItem from './MenuItem';
import * as Modal from './Modal';
import * as ModalBody from './ModalBody';
import * as ModalDialog from './ModalDialog';
import * as ModalFooter from './ModalFooter';
import * as ModalHeader from './ModalHeader';
import * as ModalTitle from './ModalTitle';
import * as Nav from './Nav';
import * as Navbar from './Navbar';
import * as NavbarBrand from './NavbarBrand';
import * as NavbarCollapse from './NavbarCollapse';
import * as NavbarHeader from './NavbarHeader';
import * as NavbarToggle from './NavbarToggle';
import * as NavDropdown from './NavDropdown';
import * as NavItem from './NavItem';
import * as Overlay from './Overlay';
import * as OverlayTrigger from './OverlayTrigger';
import * as PageHeader from './PageHeader';
import * as PageItem from './PageItem';
import * as Pager from './Pager';
import * as PagerItem from './PagerItem';
import * as Pagination from './Pagination';
import * as PaginationButton from './PaginationButton';
import * as Panel from './Panel';
import * as PanelGroup from './PanelGroup';
import * as Popover from './Popover';
import * as ProgressBar from './ProgressBar';
import * as Radio from './Radio';
import * as ResponsiveEmbed from './ResponsiveEmbed';
import * as Row from './Row';
import * as SafeAnchor from './SafeAnchor';
import * as SplitButton from './SplitButton';
import * as SplitToggle from './SplitToggle';
import * as Tab from './Tab';
import * as TabContainer from './TabContainer';
import * as TabContent from './TabContent';
import * as Table from './Table';
import * as TabPane from './TabPane';
import * as Tabs from './Tabs';
import * as Thumbnail from './Thumbnail';
import * as Tooltip from './Tooltip';
import * as Well from './Well';

import * as utils from './utils';

export {
  Accordion,
  Alert,
  Badge,
  Breadcrumb,
  BreadcrumbItem,
  Button,
  ButtonGroup,
  ButtonToolbar,
  Carousel,
  CarouselCaption,
  CarouselItem,
  Checkbox,
  Clearfix,
  Col,
  Collapse,
  ControlLabel,
  Dropdown,
  DropdownButton,
  DropdownMenu,
  DropdownToggle,
  Fade,
  Form,
  FormControl,
  FormControlFeedback,
  FormControlStatic,
  FormGroup,
  Glyphicon,
  Grid,
  HelpBlock,
  Image,
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  Jumbotron,
  Label,
  ListGroup,
  ListGroupItem,
  Media,
  MediaBody,
  MediaHeading,
  MediaLeft,
  MediaList,
  MediaListItem,
  MediaRight,
  MenuItem,
  Modal,
  ModalBody,
  ModalDialog,
  ModalFooter,
  ModalHeader,
  ModalTitle,
  Nav,
  Navbar,
  NavbarBrand,
  NavbarCollapse,
  NavbarHeader,
  NavbarToggle,
  NavDropdown,
  NavItem,
  Overlay,
  OverlayTrigger,
  PageHeader,
  PageItem,
  Pager,
  PagerItem,
  Pagination,
  PaginationButton,
  Panel,
  PanelGroup,
  Popover,
  ProgressBar,
  Radio,
  ResponsiveEmbed,
  Row,
  SafeAnchor,
  SplitButton,
  SplitToggle,
  Tab,
  TabContainer,
  TabContent,
  Table,
  TabPane,
  Tabs,
  Thumbnail,
  Tooltip,
  Well,
  utils,
}


text:
cask 'p5' do
  # note: "5" is not a version number, but an intrinsic part of the product name
  version '0.5.10'
  sha256 '52d7abe71a9613c9ef694adeede7a0a9dfa78ff0a11602783fe0187c476bc25b'

  # github.com is the official download host per the vendor homepage
  url "https://github.com/processing/p5.js-editor/releases/download/v#{version}/p5-mac.zip"
  appcast 'https://github.com/processing/p5.js-editor/releases.atom',
          checkpoint: '15242dba0ba4ed40a22e23cdfc0b93d64781d229fcb05b0f2517aa2ef97588f3'
  name 'p5.js Editor'
  homepage 'http://p5js.org/download/#editor'
  license :mit

  app 'p5.app'
end


text:
"""Profile page test"""
import datetime

from django.test import TransactionTestCase
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from apps.managers.challenge_mgr import challenge_mgr

from apps.utils import test_utils
from apps.widgets.smartgrid.models import Activity, ActionMember, Commitment, Event
from apps.widgets.quests.models import Quest

class MyAchievementsTestCase(TransactionTestCase):
    """Profile page test"""

    def setUp(self):
        """setup"""
        challenge_mgr.init()
        self.user = test_utils.setup_user(username="user", password="changeme")
        test_utils.set_competition_round()

        test_utils.enable_quest()
        challenge_mgr.register_page_widget("home", "home")
        challenge_mgr.register_page_widget("profile", "my_achievements")
        challenge_mgr.register_page_widget("profile", "my_commitments")

        from apps.managers.cache_mgr import cache_mgr
        cache_mgr.clear()

        self.client.login(username="user", password="changeme")

    def testActivityAchievement(self):
        """Check that the user's activity achievements are loaded."""
        activity = Activity(
            title="Test activity",
            description="Testing!",
            expected_duration=10,
            point_value=10,
            slug="test-activity",
            pub_date=datetime.datetime.today(),
            expire_date=datetime.datetime.today() + datetime.timedelta(days=7),
            confirm_type="text",
            type="activity",
        )
        activity.save()

        # Test that profile page has a pending activity.
        member = ActionMember(user=self.user,
                              action=activity,
                              approval_status="approved")
        member.save()

        response = self.client.get(reverse("profile_index"))
        self.assertContains(response,
            reverse("activity_task", args=(activity.type, activity.slug,)))
        self.assertContains(response, "Test activity")

        # Test adding an event to catch a bug.
        event = Event(
            title="Test event",
            slug="test-event",
            description="Testing!",
            expected_duration=10,
            point_value=10,
            pub_date=datetime.datetime.today(),
            expire_date=datetime.datetime.today() + datetime.timedelta(days=7),
            type="event",
            event_date=datetime.datetime.today() + datetime.timedelta(days=3),
        )
        event.save()

        member = ActionMember(user=self.user, action=event, approval_status="pending")
        member.save()
        response = self.client.get(reverse("profile_index"))
        self.assertContains(response,
            reverse("activity_task", args=(activity.type, activity.slug,)))
        self.assertContains(response, "Pending")
        self.assertContains(response, "Activity:")
        self.assertContains(response, "Event:")
        self.assertNotContains(response, "You have nothing in progress or pending.")

    def testCommitmentAchievement(self):
        """Check that the user's commitment achievements are loaded."""
        commitment = Commitment(
            title="Test commitment",
            description="A commitment!",
            point_value=10,
            type="commitment",
            slug="test-commitment",
        )
        commitment.save()

        # Test that profile page has a pending activity.
        member = ActionMember(user=self.user, action=commitment)
        member.save()
        response = self.client.get(reverse("profile_index"))
        self.assertContains(response,
            reverse("activity_task", args=(commitment.type, commitment.slug,)))
        self.assertContains(response, "In Progress")
        self.assertContains(response, "Commitment:")
        self.assertNotContains(response, "You have nothing in progress or pending.")

        # Test that the profile page has a rejected activity
        member.award_date = datetime.datetime.today()
        member.save()
        response = self.client.get(reverse("profile_index"))
        self.assertContains(response,
            reverse("activity_task", args=(commitment.type, commitment.slug,)))
        self.assertNotContains(response, "You have not been awarded anything yet!")
        self.assertNotContains(response, "In Progress")

    def testVariablePointAchievement(self):
        """Test that a variable point activity appears correctly in the my achievements list."""
        activity = Activity(
            title="Test activity",
            slug="test-activity",
            description="Variable points!",
            expected_duration=10,
            point_range_start=5,
            point_range_end=314160,
            pub_date=datetime.datetime.today(),
            expire_date=datetime.datetime.today() + datetime.timedelta(days=7),
            confirm_type="text",
            type="activity",
        )
        activity.save()

        points = self.user.profile.points()
        member = ActionMember(
            user=self.user,
            action=activity,
            approval_status="approved",
        )
        member.points_awarded = 314159
        member.save()

        self.assertEqual(self.user.profile.points(), points + 314159,
            "Variable number of points should have been awarded.")

        # Kludge to change point value for the info bar.
        profile = self.user.profile
        profile.add_points(3, datetime.datetime.today(), "test")
        profile.save()

        response = self.client.get(reverse("profile_index"))
        self.assertContains(response,
            reverse("activity_task", args=(activity.type, activity.slug,)))
        # Note, this test may break if something in the page has the value 314159.
        # Try finding another suitable number.
        # print response.content
        self.assertContains(response, "314159", count=5,
            msg_prefix="314159 points should appear for the activity.")

    def testSocialBonusAchievement(self):
        """Check that the social bonus appears in the my achievements list."""
        # Create a second test user.
        user2 = User.objects.create_user("user2", "user2@test.com")
        event = Event.objects.create(
            title="Test event",
            slug="test-event",
            description="Testing!",
            expected_duration=10,
            point_value=10,
            social_bonus=10,
            pub_date=datetime.datetime.today(),
            expire_date=datetime.datetime.today() + datetime.timedelta(days=7),
            type="event",
            event_date=datetime.datetime.today(),
        )

        # Create membership for the two users.
        m = ActionMember(
            user=self.user,
            action=event,
            approval_status="approved",
        )
        m.social_email = "user2@test.com"
        m.save()

        m2 = ActionMember(
            user=user2,
            action=event,
            approval_status="approved",
        )
        m2.social_email = "user@test.com"
        m2.save()

        response = self.client.get(reverse("profile_index"))
        self.assertContains(response, reverse("activity_task", args=(event.type, event.slug,)))
        entry = "Event: Test event (Social Bonus)"
        self.assertContains(response, entry, count=1,
            msg_prefix="Achievements should contain a social bonus entry")

    def testQuestAchievement(self):
        """test quest shown up in achievement"""
        quest = Quest(
            name="Test quest",
            quest_slug="test_quest",
            description="test quest",
            priority=1,
            unlock_conditions="True",
            completion_conditions="True",
        )
        quest.save()

        # Accept the quest, which should be automatically completed.
        response = self.client.post(
            reverse("quests_accept", args=(quest.quest_slug,)),
            follow=True,
            HTTP_REFERER=reverse("home_index"),
        )
        response = self.client.get(reverse("profile_index"))
        self.assertContains(response, "Quest: Test quest", count=1,
            msg_prefix="Achievements should contain a quest entry")


text:
//
// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//

var should = require('should');
var azureCommon = require('azure-common');
var utils = require('../../lib/util/utils');

var CLITest = require('../framework/cli-test');

var suite;
var testPrefix = 'cli.storage.service-tests';
var crypto = require('crypto');

function stripAccessKey(connectionString) {
  return connectionString.replace(/AccountKey=[^;]+/, 'AccountKey=null');
}

var requiredEnvironment = [
  { name: 'AZURE_STORAGE_CONNECTION_STRING', secure: stripAccessKey }
];

/**
* Convert a cmd to azure storage cli
*/
describe('cli', function () {
  describe('storage', function() {

    before(function (done) {
      suite = new CLITest(this, testPrefix, requiredEnvironment);
      suite.skipSubscription = true;

      if (suite.isMocked) {
        utils.POLL_REQUEST_INTERVAL = 0;
      }

      suite.setupSuite(done);
    });

    after(function (done) {
      suite.teardownSuite(done);
    });

    beforeEach(function (done) {
      suite.setupTest(done);
    });

    afterEach(function (done) {
      suite.teardownTest(done);
    });

    describe('logging', function() {
      describe('show', function() {
        it('should show logging properties for all services', function(done) {
          suite.execute('storage logging show --json', function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.equal(3);
            properties.forEach(function(property) {
              property.Version.should.equal('1.0');
              property.Type.should.not.be.empty;
              property.Read.should.be.a.Boolean;
              property.Write.should.be.a.Boolean;
              property.Delete.should.be.a.Boolean;
              property.RetentionPolicy.should.be.an.Object;
            });
            done();
          });
        });

        it('should show logging properties for blob service', function(done) {
          suite.execute('storage logging show --blob --json', function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.greaterThan(0);
            properties.forEach(function(property) {
              property.Version.should.equal('1.0');
              property.Type.should.not.be.empty;
              property.Read.should.be.a.Boolean;
              property.Write.should.be.a.Boolean;
              property.Delete.should.be.a.Boolean;
              property.RetentionPolicy.should.be.an.Object;
            });
            done();
          });
        });

        it('should show logging properties for table service', function(done) {
          suite.execute('storage logging show --table --json', function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.greaterThan(0);
              properties.forEach(function(property) {
              property.Version.should.equal('1.0');
              property.Type.should.not.be.empty;
              property.Read.should.be.a.Boolean;
              property.Write.should.be.a.Boolean;
              property.Delete.should.be.a.Boolean;
              property.RetentionPolicy.should.be.an.Object;
              });
            done();
          });
        });

        it('should show logging properties for queue service', function(done) {
          suite.execute('storage logging show --queue --json', function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.greaterThan(0);
            properties.forEach(function(property) {
              property.Version.should.equal('1.0');
              property.Type.should.not.be.empty;
              property.Read.should.be.a.Boolean;
              property.Write.should.be.a.Boolean;
              property.Delete.should.be.a.Boolean;
              property.RetentionPolicy.should.be.an.Object;
            });
            done();
          });
        });
      });

      describe('set', function() {
        it('should set logging properties for blob service', function(done) {
          var retention = 10;
          suite.execute('storage logging set --blob --retention %s --read --write --delete-off --json', retention, function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.equal(1);
            var property = properties[0];
            property.Version.should.equal('1.0');
            property.Type.should.equal('blob');
            property.Read.should.be.true;
            property.Write.should.be.true;
            property.Delete.should.be.false;
            property.RetentionPolicy.Enabled.should.be.true;
            property.RetentionPolicy.Days.should.equal(retention);
            done();
          });
        });

        it('should set logging properties for table service', function(done) {
          var retention = '0';
          suite.execute('storage logging set --table --retention %s --read --write-off --delete --json', retention, function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.equal(1);
            var property = properties[0];
            property.Version.should.equal('1.0');
            property.Type.should.equal('table');
            property.Read.should.be.true;
            property.Write.should.be.false;
            property.Delete.should.be.true;
            property.RetentionPolicy.Enabled.should.be.false;
            done();
          });
        });

        it('should set logging properties for queue service', function(done) {
          var retention = 5;
          suite.execute('storage logging set --queue --retention %s --read-off --write --delete --json', retention, function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.equal(1);
            var property = properties[0];
            property.Version.should.equal('1.0');
            property.Type.should.equal('queue');
            property.Read.should.be.false;
            property.Write.should.be.true;
            property.Delete.should.be.true;
            property.RetentionPolicy.Enabled.should.be.true;
            property.RetentionPolicy.Days.should.equal(retention);
            done();
          });
        });
      });
    });

    describe('metrics', function() {
      describe('show', function() {
        it('should show metrics properties for all services', function(done) {
          suite.execute('storage metrics show --json', function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.equal(3);
            properties.forEach(function(property) {
              property.type.should.not.be.empty;
              property.HourMetrics.length.should.equal(1);
              property.HourMetrics[0].should.be.an.Object;
              property.HourMetrics[0].Version.should.equal('1.0');
              property.HourMetrics[0].Enabled.should.be.a.Boolean;
              property.HourMetrics[0].RetentionPolicy.should.be.an.Object;

              property.MinuteMetrics.length.should.equal(1);
              property.MinuteMetrics[0].should.be.an.Object;
              property.MinuteMetrics[0].Version.should.equal('1.0');
              property.MinuteMetrics[0].Enabled.should.be.a.Boolean;
            });
            done();
          });
        });

        it('should show metrics properties for blob service', function(done) {
          suite.execute('storage metrics show --blob --json', function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.greaterThan(0);
            properties.forEach(function(property) {
              property.type.should.not.be.empty;
              property.HourMetrics.length.should.equal(1);
              property.HourMetrics[0].should.be.an.Object;
              property.HourMetrics[0].Version.should.equal('1.0');
              property.HourMetrics[0].Enabled.should.be.a.Boolean;
              property.HourMetrics[0].RetentionPolicy.should.be.an.Object;

              property.MinuteMetrics.length.should.equal(1);
              property.MinuteMetrics[0].should.be.an.Object;
              property.MinuteMetrics[0].Version.should.equal('1.0');
              property.MinuteMetrics[0].Enabled.should.be.a.Boolean;
            });
            done();
          });
        });

        it('should show metrics properties for table service', function(done) {
          suite.execute('storage metrics show --table --json', function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.greaterThan(0);
            properties.forEach(function(property) {
              property.type.should.not.be.empty;
              property.HourMetrics.length.should.equal(1);
              property.HourMetrics[0].should.be.an.Object;
              property.HourMetrics[0].Version.should.equal('1.0');
              property.HourMetrics[0].Enabled.should.be.a.Boolean;
              property.HourMetrics[0].RetentionPolicy.should.be.an.Object;

              property.MinuteMetrics.length.should.equal(1);
              property.MinuteMetrics[0].should.be.an.Object;
              property.MinuteMetrics[0].Version.should.equal('1.0');
              property.MinuteMetrics[0].Enabled.should.be.a.Boolean;
            });
            done();
          });
        });

        it('should show metrics properties for queue service', function(done) {
          suite.execute('storage metrics show --queue --json', function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.greaterThan(0);
            properties.forEach(function(property) {
              property.type.should.not.be.empty;
              property.HourMetrics.length.should.equal(1);
              property.HourMetrics[0].should.be.an.Object;
              property.HourMetrics[0].Version.should.equal('1.0');
              property.HourMetrics[0].Enabled.should.be.a.Boolean;
              property.HourMetrics[0].RetentionPolicy.should.be.an.Object;

              property.MinuteMetrics.length.should.equal(1);
              property.MinuteMetrics[0].should.should.be.an.Object;
              property.MinuteMetrics[0].Version.should.equal('1.0');
              property.MinuteMetrics[0].Enabled.should.be.a.Boolean;
            });
            done();
          });
        });
      });

      describe('set', function() {
        it('should set hourly metrics properties for blob service', function(done) {
          var retention = 10;
          suite.execute('storage metrics set --blob --retention %s --hour --api --json', retention, function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.equal(1);
            var property = properties[0];
            property.type.should.equal('blob');
            property.HourMetrics.length.should.equal(1);
            property.HourMetrics[0].should.be.an.Object;
            property.HourMetrics[0].Version.should.equal('1.0');
            property.HourMetrics[0].Enabled.should.be.true;
            property.HourMetrics[0].IncludeAPIs.should.be.true;
            property.HourMetrics[0].RetentionPolicy.should.be.an.Object;
            property.HourMetrics[0].RetentionPolicy.Enabled.should.be.true;
            property.HourMetrics[0].RetentionPolicy.Days.should.equal(retention);

            property.MinuteMetrics.length.should.equal(1);
            property.MinuteMetrics[0].should.be.an.Object;
            property.MinuteMetrics[0].Version.should.equal('1.0');
            property.MinuteMetrics[0].Enabled.should.be.a.Boolean;
            done();
          });
        });

        it('should set hourly metrics properties and turn off minute metrics for table service', function(done) {
          var retention = '0';
          suite.execute('storage metrics set --table --retention %s --hour --api-off --minute-off --json', retention, function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.equal(1);
            var property = properties[0];
            property.type.should.equal('table');
            property.HourMetrics.length.should.equal(1);
            property.HourMetrics[0].should.be.an.Object;
            property.HourMetrics[0].Version.should.equal('1.0');
            property.HourMetrics[0].Enabled.should.be.true;
            property.HourMetrics[0].IncludeAPIs.should.be.false;
            property.HourMetrics[0].RetentionPolicy.should.be.an.Object;
            property.HourMetrics[0].RetentionPolicy.Enabled.should.be.false;

            property.MinuteMetrics.length.should.equal(1);
            property.MinuteMetrics[0].should.be.an.Object;
            property.MinuteMetrics[0].Version.should.equal('1.0');
            property.MinuteMetrics[0].Enabled.should.be.false;
            done();
          });
        });

        it('should set minute metrics properties and turn off hourly metrics for queue service', function(done) {
          var retention = 10;
          suite.execute('storage metrics set --queue --retention %s --hour-off --minute --api --json', retention, function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.equal(1);
            var property = properties[0];
            property.type.should.equal('queue');
            property.HourMetrics.length.should.equal(1);
            property.HourMetrics[0].should.be.an.Object;
            property.HourMetrics[0].Version.should.equal('1.0');
            property.HourMetrics[0].Enabled.should.be.false;
            property.HourMetrics[0].RetentionPolicy.should.be.an.Object;
            property.HourMetrics[0].RetentionPolicy.Enabled.should.be.a.Boolean;

            property.MinuteMetrics.length.should.equal(1);
            property.MinuteMetrics[0].should.be.an.Object;
            property.MinuteMetrics[0].Version.should.equal('1.0');
            property.MinuteMetrics[0].Enabled.should.be.true;
            property.MinuteMetrics[0].IncludeAPIs.should.be.true;
            property.MinuteMetrics[0].RetentionPolicy.should.be.an.Object;
            property.MinuteMetrics[0].RetentionPolicy.Enabled.should.be.true;
            property.MinuteMetrics[0].RetentionPolicy.Days.should.equal(retention);
            done();
          });
        });

        it('should turn off both minute and hourly metrics for queue service', function(done) {
          var retention = 10;
          suite.execute('storage metrics set --queue --retention %s --hour-off --minute-off --json', retention, function(result) {
            result.errorText.should.be.empty;
            var properties = JSON.parse(result.text);
            properties.length.should.equal(1);
            var property = properties[0];
            property.type.should.equal('queue');
            property.HourMetrics.length.should.equal(1);
            property.HourMetrics[0].should.be.an.Object;
            property.HourMetrics[0].Version.should.equal('1.0');
            property.HourMetrics[0].Enabled.should.be.false;
            property.HourMetrics[0].RetentionPolicy.should.be.an.Object;
            property.HourMetrics[0].RetentionPolicy.Enabled.should.be.a.Boolean;

            property.MinuteMetrics.length.should.equal(1);
            property.MinuteMetrics[0].should.be.an.Object;
            property.MinuteMetrics[0].Version.should.equal('1.0');
            property.MinuteMetrics[0].Enabled.should.be.false;
            property.MinuteMetrics[0].RetentionPolicy.should.be.an.Object;
            property.MinuteMetrics[0].RetentionPolicy.Enabled.should.be.a.Boolean;
            done();
          });
        });
      });
    });
  });
});


text:
namespace cli { class settings; }

namespace config {
  enum parse_status {
    parse_fail,
    parse_ok
  };

  //! \ingroup grp_config
  //! Parses the configuration files supplied by the cli.  This is the entry
  //! point to the config module.
  parse_status parse(pipeline_config &, const cli::settings &);
}
#endif


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.labservices.generated;

import com.azure.core.util.Context;

/** Samples for VirtualMachines Reimage. */
public final class VirtualMachinesReimageSamples {
    /*
     * x-ms-original-file: specification/labservices/resource-manager/Microsoft.LabServices/stable/2022-08-01/examples/VirtualMachines/reimageVirtualMachine.json
     */
    /**
     * Sample code: reimageVirtualMachine.
     *
     * @param manager Entry point to LabServicesManager.
     */
    public static void reimageVirtualMachine(com.azure.resourcemanager.labservices.LabServicesManager manager) {
        manager.virtualMachines().reimage("testrg123", "testlab", "template", Context.NONE);
    }
}


text:
package com.microsoft.azure.management.network.v2019_08_01.implementation;

import java.util.List;
import com.microsoft.azure.management.network.v2019_08_01.VpnGatewayTunnelingProtocol;
import com.microsoft.azure.management.network.v2019_08_01.VpnAuthenticationType;
import com.microsoft.azure.management.network.v2019_08_01.VpnServerConfigVpnClientRootCertificate;
import com.microsoft.azure.management.network.v2019_08_01.VpnServerConfigVpnClientRevokedCertificate;
import com.microsoft.azure.management.network.v2019_08_01.VpnServerConfigRadiusServerRootCertificate;
import com.microsoft.azure.management.network.v2019_08_01.VpnServerConfigRadiusClientRootCertificate;
import com.microsoft.azure.management.network.v2019_08_01.IpsecPolicy;
import com.microsoft.azure.management.network.v2019_08_01.AadAuthenticationParameters;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.rest.SkipParentValidation;
import com.microsoft.azure.Resource;

/**
 * VpnServerConfiguration Resource.
 */
@JsonFlatten
@SkipParentValidation
public class VpnServerConfigurationInner extends Resource {
    /**
     * The name of the VpnServerConfiguration that is unique within a resource
     * group.
     */
    @JsonProperty(value = "properties.name")
    private String vpnServerConfigurationName;

    /**
     * VPN protocols for the VpnServerConfiguration.
     */
    @JsonProperty(value = "properties.vpnProtocols")
    private List<VpnGatewayTunnelingProtocol> vpnProtocols;

    /**
     * VPN authentication types for the VpnServerConfiguration.
     */
    @JsonProperty(value = "properties.vpnAuthenticationTypes")
    private List<VpnAuthenticationType> vpnAuthenticationTypes;

    /**
     * VPN client root certificate of VpnServerConfiguration.
     */
    @JsonProperty(value = "properties.vpnClientRootCertificates")
    private List<VpnServerConfigVpnClientRootCertificate> vpnClientRootCertificates;

    /**
     * VPN client revoked certificate of VpnServerConfiguration.
     */
    @JsonProperty(value = "properties.vpnClientRevokedCertificates")
    private List<VpnServerConfigVpnClientRevokedCertificate> vpnClientRevokedCertificates;

    /**
     * Radius Server root certificate of VpnServerConfiguration.
     */
    @JsonProperty(value = "properties.radiusServerRootCertificates")
    private List<VpnServerConfigRadiusServerRootCertificate> radiusServerRootCertificates;

    /**
     * Radius client root certificate of VpnServerConfiguration.
     */
    @JsonProperty(value = "properties.radiusClientRootCertificates")
    private List<VpnServerConfigRadiusClientRootCertificate> radiusClientRootCertificates;

    /**
     * VpnClientIpsecPolicies for VpnServerConfiguration.
     */
    @JsonProperty(value = "properties.vpnClientIpsecPolicies")
    private List<IpsecPolicy> vpnClientIpsecPolicies;

    /**
     * The radius server address property of the VpnServerConfiguration
     * resource for point to site client connection.
     */
    @JsonProperty(value = "properties.radiusServerAddress")
    private String radiusServerAddress;

    /**
     * The radius secret property of the VpnServerConfiguration resource for
     * point to site client connection.
     */
    @JsonProperty(value = "properties.radiusServerSecret")
    private String radiusServerSecret;

    /**
     * The set of aad vpn authentication parameters.
     */
    @JsonProperty(value = "properties.aadAuthenticationParameters")
    private AadAuthenticationParameters aadAuthenticationParameters;

    /**
     * The provisioning state of the VpnServerConfiguration resource. Possible
     * values are: 'Updating', 'Deleting', and 'Failed'.
     */
    @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY)
    private String provisioningState;

    /**
     * List of references to P2SVpnGateways.
     */
    @JsonProperty(value = "properties.p2SVpnGateways", access = JsonProperty.Access.WRITE_ONLY)
    private List<P2SVpnGatewayInner> p2SVpnGateways;

    /**
     * A unique read-only string that changes whenever the resource is updated.
     */
    @JsonProperty(value = "properties.etag")
    private String vpnServerConfigurationPropertiesEtag;

    /**
     * Gets a unique read-only string that changes whenever the resource is
     * updated.
     */
    @JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY)
    private String etag;

    /**
     * Resource ID.
     */
    @JsonProperty(value = "id")
    private String id;

    /**
     * Get the name of the VpnServerConfiguration that is unique within a resource group.
     *
     * @return the vpnServerConfigurationName value
     */
    public String vpnServerConfigurationName() {
        return this.vpnServerConfigurationName;
    }

    /**
     * Set the name of the VpnServerConfiguration that is unique within a resource group.
     *
     * @param vpnServerConfigurationName the vpnServerConfigurationName value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withVpnServerConfigurationName(String vpnServerConfigurationName) {
        this.vpnServerConfigurationName = vpnServerConfigurationName;
        return this;
    }

    /**
     * Get vPN protocols for the VpnServerConfiguration.
     *
     * @return the vpnProtocols value
     */
    public List<VpnGatewayTunnelingProtocol> vpnProtocols() {
        return this.vpnProtocols;
    }

    /**
     * Set vPN protocols for the VpnServerConfiguration.
     *
     * @param vpnProtocols the vpnProtocols value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withVpnProtocols(List<VpnGatewayTunnelingProtocol> vpnProtocols) {
        this.vpnProtocols = vpnProtocols;
        return this;
    }

    /**
     * Get vPN authentication types for the VpnServerConfiguration.
     *
     * @return the vpnAuthenticationTypes value
     */
    public List<VpnAuthenticationType> vpnAuthenticationTypes() {
        return this.vpnAuthenticationTypes;
    }

    /**
     * Set vPN authentication types for the VpnServerConfiguration.
     *
     * @param vpnAuthenticationTypes the vpnAuthenticationTypes value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withVpnAuthenticationTypes(List<VpnAuthenticationType> vpnAuthenticationTypes) {
        this.vpnAuthenticationTypes = vpnAuthenticationTypes;
        return this;
    }

    /**
     * Get vPN client root certificate of VpnServerConfiguration.
     *
     * @return the vpnClientRootCertificates value
     */
    public List<VpnServerConfigVpnClientRootCertificate> vpnClientRootCertificates() {
        return this.vpnClientRootCertificates;
    }

    /**
     * Set vPN client root certificate of VpnServerConfiguration.
     *
     * @param vpnClientRootCertificates the vpnClientRootCertificates value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withVpnClientRootCertificates(List<VpnServerConfigVpnClientRootCertificate> vpnClientRootCertificates) {
        this.vpnClientRootCertificates = vpnClientRootCertificates;
        return this;
    }

    /**
     * Get vPN client revoked certificate of VpnServerConfiguration.
     *
     * @return the vpnClientRevokedCertificates value
     */
    public List<VpnServerConfigVpnClientRevokedCertificate> vpnClientRevokedCertificates() {
        return this.vpnClientRevokedCertificates;
    }

    /**
     * Set vPN client revoked certificate of VpnServerConfiguration.
     *
     * @param vpnClientRevokedCertificates the vpnClientRevokedCertificates value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withVpnClientRevokedCertificates(List<VpnServerConfigVpnClientRevokedCertificate> vpnClientRevokedCertificates) {
        this.vpnClientRevokedCertificates = vpnClientRevokedCertificates;
        return this;
    }

    /**
     * Get radius Server root certificate of VpnServerConfiguration.
     *
     * @return the radiusServerRootCertificates value
     */
    public List<VpnServerConfigRadiusServerRootCertificate> radiusServerRootCertificates() {
        return this.radiusServerRootCertificates;
    }

    /**
     * Set radius Server root certificate of VpnServerConfiguration.
     *
     * @param radiusServerRootCertificates the radiusServerRootCertificates value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withRadiusServerRootCertificates(List<VpnServerConfigRadiusServerRootCertificate> radiusServerRootCertificates) {
        this.radiusServerRootCertificates = radiusServerRootCertificates;
        return this;
    }

    /**
     * Get radius client root certificate of VpnServerConfiguration.
     *
     * @return the radiusClientRootCertificates value
     */
    public List<VpnServerConfigRadiusClientRootCertificate> radiusClientRootCertificates() {
        return this.radiusClientRootCertificates;
    }

    /**
     * Set radius client root certificate of VpnServerConfiguration.
     *
     * @param radiusClientRootCertificates the radiusClientRootCertificates value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withRadiusClientRootCertificates(List<VpnServerConfigRadiusClientRootCertificate> radiusClientRootCertificates) {
        this.radiusClientRootCertificates = radiusClientRootCertificates;
        return this;
    }

    /**
     * Get vpnClientIpsecPolicies for VpnServerConfiguration.
     *
     * @return the vpnClientIpsecPolicies value
     */
    public List<IpsecPolicy> vpnClientIpsecPolicies() {
        return this.vpnClientIpsecPolicies;
    }

    /**
     * Set vpnClientIpsecPolicies for VpnServerConfiguration.
     *
     * @param vpnClientIpsecPolicies the vpnClientIpsecPolicies value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withVpnClientIpsecPolicies(List<IpsecPolicy> vpnClientIpsecPolicies) {
        this.vpnClientIpsecPolicies = vpnClientIpsecPolicies;
        return this;
    }

    /**
     * Get the radius server address property of the VpnServerConfiguration resource for point to site client connection.
     *
     * @return the radiusServerAddress value
     */
    public String radiusServerAddress() {
        return this.radiusServerAddress;
    }

    /**
     * Set the radius server address property of the VpnServerConfiguration resource for point to site client connection.
     *
     * @param radiusServerAddress the radiusServerAddress value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withRadiusServerAddress(String radiusServerAddress) {
        this.radiusServerAddress = radiusServerAddress;
        return this;
    }

    /**
     * Get the radius secret property of the VpnServerConfiguration resource for point to site client connection.
     *
     * @return the radiusServerSecret value
     */
    public String radiusServerSecret() {
        return this.radiusServerSecret;
    }

    /**
     * Set the radius secret property of the VpnServerConfiguration resource for point to site client connection.
     *
     * @param radiusServerSecret the radiusServerSecret value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withRadiusServerSecret(String radiusServerSecret) {
        this.radiusServerSecret = radiusServerSecret;
        return this;
    }

    /**
     * Get the set of aad vpn authentication parameters.
     *
     * @return the aadAuthenticationParameters value
     */
    public AadAuthenticationParameters aadAuthenticationParameters() {
        return this.aadAuthenticationParameters;
    }

    /**
     * Set the set of aad vpn authentication parameters.
     *
     * @param aadAuthenticationParameters the aadAuthenticationParameters value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withAadAuthenticationParameters(AadAuthenticationParameters aadAuthenticationParameters) {
        this.aadAuthenticationParameters = aadAuthenticationParameters;
        return this;
    }

    /**
     * Get the provisioning state of the VpnServerConfiguration resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
     *
     * @return the provisioningState value
     */
    public String provisioningState() {
        return this.provisioningState;
    }

    /**
     * Get list of references to P2SVpnGateways.
     *
     * @return the p2SVpnGateways value
     */
    public List<P2SVpnGatewayInner> p2SVpnGateways() {
        return this.p2SVpnGateways;
    }

    /**
     * Get a unique read-only string that changes whenever the resource is updated.
     *
     * @return the vpnServerConfigurationPropertiesEtag value
     */
    public String vpnServerConfigurationPropertiesEtag() {
        return this.vpnServerConfigurationPropertiesEtag;
    }

    /**
     * Set a unique read-only string that changes whenever the resource is updated.
     *
     * @param vpnServerConfigurationPropertiesEtag the vpnServerConfigurationPropertiesEtag value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withVpnServerConfigurationPropertiesEtag(String vpnServerConfigurationPropertiesEtag) {
        this.vpnServerConfigurationPropertiesEtag = vpnServerConfigurationPropertiesEtag;
        return this;
    }

    /**
     * Get gets a unique read-only string that changes whenever the resource is updated.
     *
     * @return the etag value
     */
    public String etag() {
        return this.etag;
    }

    /**
     * Get resource ID.
     *
     * @return the id value
     */
    public String id() {
        return this.id;
    }

    /**
     * Set resource ID.
     *
     * @param id the id value to set
     * @return the VpnServerConfigurationInner object itself.
     */
    public VpnServerConfigurationInner withId(String id) {
        this.id = id;
        return this;
    }

}


text:
package allow.simulator.mobility.data;

import java.util.List;

import allow.simulator.mobility.data.gtfs.GTFSAgency;
import allow.simulator.mobility.data.gtfs.GTFSRoute;
import allow.simulator.mobility.data.gtfs.GTFSService;
import allow.simulator.mobility.data.gtfs.GTFSServiceException;
import allow.simulator.mobility.data.gtfs.GTFSStop;
import allow.simulator.world.Street;

/**
 * Interface for an urban mobility data service.
 *
 * @author Andreas Poxrucker (DFKI)
 *
 */
public interface IDataService {

	/**
	 * Returns available transport agencies.
	 *
	 * @return List of available transport agencies.
	 */
	List<GTFSAgency> getAgencies();

	/**
	 * Returns available routes of an agency.
	 *
	 * @param agencyId Id of agency.
	 *
	 * @return List of available routes served by agency.
	 */
	List<GTFSRoute> getRoutes(String agencyId);

	/**
	 * Returns list of stops along a certain route of an agency.
	 *
	 * @param routeId Id of route.
	 *
	 * @return List of stops along a certain route of an agency.
	 */
	List<GTFSStop> getStops(String routeId);

	/**
	 * Returns a list of exceptions of a service given its Ids.
	 *
	 * @param serviceId Id of the service to return exceptions.
	 * @return List of exceptions of the given service.
	 */
	List<GTFSServiceException> getServiceExceptions(String serviceId);

	GTFSService getServiceId(String routeId, String tripId);

	/**
	 * Returns timetable of a certain route.
	 *
	 * @param routeId Id of route.
	 *
	 * @return Timetable for route.
	 */
	TimeTable getTimeTable(String routeId);

	/**
	 * Returns the route between two bus stops on the level of streets.
	 *
	 * @param start First stop.
	 * @param end Second stop.
	 * @return
	 */
	List<Street> getBusstopRouting(String start, String end);
}


text:
haxelib run hx-gameplay process-build-files android-arm
@ IF errorlevel 1 call :error "failed to process build files" & exit /B 1

cd platforms\.obj\android-arm
@ IF errorlevel 1 call :error "failed to change current directory" & exit /B 1

del /q libgame*.so
@ IF errorlevel 1 call :error-cd "failed to clean previous build files" & exit /B 1

haxelib run hxcpp Build.xml -Dandroid -DNDKV7 -Dandroid-9 %1 %2 %3 %4 %5 %6 %7 %8 %9
@ IF errorlevel 1 call :error-cd "failed to compile application source" & exit /B 1

xcopy /y libgame*.so ..\..\android-arm\bin\out\
@ IF errorlevel 1 call :error-cd "failed to copy application shared object" & exit /B 1

@ GOTO success

:error-cd
cd ..\..\..
:error
@ echo Buiild error: %~1. 1>&2
@ GOTO :eof

:success
cd ..\..\..


text:
@interface DownloadOperation () <NSURLConnectionDelegate>
@property (nonatomic, strong) NSURL* url;
@property (nonatomic, strong) NSURLConnection* connection;
@property (nonatomic, strong) NSMutableData* buffer;
@property (nonatomic) long long int expectedContentLength;
@property (nonatomic, readwrite) NSError* error;
@property (nonatomic) BOOL isExecuting;
@property (nonatomic) BOOL isConcurrent;
@property (nonatomic) BOOL isFinished;
@end

@implementation DownloadOperation
{

}
- (id)initWithURL:(NSURL*)url
{
    self = [super init];
    if(self) {
        self.url = url;
    }
    return self;
}

- (void)start
{
    NSURLRequest* request = [NSURLRequest requestWithURL:self.url];
    self.isExecuting = YES;
    self.isConcurrent = YES;
    self.isFinished = NO;
    [[NSOperationQueue mainQueue] addOperationWithBlock:^
    {
        self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
    }];
}

#pragma mark NSURLConnectionDelegate

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response {
    return request;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    self.expectedContentLength = response.expectedContentLength;
    self.buffer = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.buffer appendData:data];
    self.progressCallback(self.buffer.length / (float)self.expectedContentLength);
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
    return cachedResponse;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    self.data = self.buffer;
    self.buffer = nil;
    self.isExecuting = NO;
    self.isFinished = YES;
}

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    self.error = error;
    self.isExecuting = NO;
    self.isFinished = YES;
}

- (void)setIsExecuting:(BOOL)isExecuting
{
    [self willChangeValueForKey:@"isExecuting"];
    _isExecuting = isExecuting;
    [self didChangeValueForKey:@"isExecuting"];
}

- (void)setIsFinished:(BOOL)isFinished
{
    [self willChangeValueForKey:@"isFinished"];
    _isFinished = isFinished;
    [self didChangeValueForKey:@"isFinished"];
}

- (void)cancel
{
    [super cancel];
    [self.connection cancel];
    self.isFinished = YES;
    self.isExecuting = NO;
}

@end


text:
import pytest

from oscar.apps.offer import models
from oscar.apps.offer.applicator import Applicator
from oscar.test.factories import (
    BasketFactory, ConditionalOfferFactory, ProductFactory)

@pytest.fixture
def filled_basket():
    basket = BasketFactory()
    product1 = ProductFactory()
    product2 = ProductFactory()
    basket.add_product(product1, quantity=10)
    basket.add_product(product2, quantity=20)
    return basket

@pytest.fixture
def single_offer():
    return ConditionalOfferFactory(
        condition__range__includes_all_products=True,
        condition__value=1,
        benefit__range__includes_all_products=True,
        benefit__max_affected_items=1,
        name='offer1',
        exclusive=False,
    )

@pytest.fixture
def multi_offers():
    offer1 = ConditionalOfferFactory(
        condition__range__includes_all_products=True,
        benefit__range__includes_all_products=True,
        name='offer1',
        exclusive=False,
    )
    offer2 = ConditionalOfferFactory(
        condition__range__includes_all_products=True,
        benefit__range__includes_all_products=True,
        name='offer2',
        exclusive=False
    )
    offer3 = ConditionalOfferFactory(
        condition__range__includes_all_products=True,
        benefit__range__includes_all_products=True,
        name='offer3',
        exclusive=False
    )
    return offer1, offer2, offer3

@pytest.mark.django_db
class TestLineOfferConsumer:

    def test_consumed_no_offer(self, filled_basket):
        for line in filled_basket.all_lines():
            assert line.consumer.consumed() == 0

    def test_available_with_offer(self):
        basket = BasketFactory()
        product1 = ProductFactory()
        product2 = ProductFactory()
        basket.add_product(product1, quantity=1)
        basket.add_product(product2, quantity=10)

        benefit = models.Benefit(
            type=models.Benefit.PERCENTAGE,
            value=10,
            max_affected_items=5,
        )
        benefit.save()

        offer1 = ConditionalOfferFactory(name='offer1', benefit=benefit)
        lines = basket.all_lines()
        assert lines[0].consumer.available(offer1) == 1
        assert lines[1].consumer.available(offer1) == 10

    def test_consumed_with_offer(self, filled_basket):
        offer1 = ConditionalOfferFactory(name='offer1')
        offer2 = ConditionalOfferFactory(name='offer2')
        offer1.exclusive = False
        offer2.exclusive = False

        for line in filled_basket.all_lines():
            assert line.consumer.consumed(offer1) == 0
            assert line.consumer.consumed(offer2) == 0

        line1 = filled_basket.all_lines()[0]
        line2 = filled_basket.all_lines()[1]

        line1.consumer.consume(1, offer1)
        assert line1.consumer.consumed() == 1
        assert line1.consumer.consumed(offer1) == 1
        assert line1.consumer.consumed(offer2) == 0

        line1.consumer.consume(9, offer1)
        assert line1.consumer.consumed() == line1.quantity
        assert line1.consumer.consumed(offer1) == line1.quantity
        assert line1.consumer.consumed(offer2) == 0

        line1.consumer.consume(99, offer1)
        assert line1.consumer.consumed(offer1) == line1.quantity
        assert line1.consumer.consumed(offer2) == 0

        line1.consumer.consume(1, offer2)
        line2.consumer.consume(1, offer2)

        assert line1.consumer.consumed(offer2) == 1
        assert line2.consumer.consumed(offer2) == 1

    def test_consume(self, filled_basket):
        line = filled_basket.all_lines()[0]
        line.consume(1)
        assert line.quantity_with_discount == 1
        line.consume(99)
        assert line.quantity_with_discount == 10

    def test_consumed_with_exclusive_offer_1(self, filled_basket):
        offer1 = ConditionalOfferFactory(name='offer1')
        offer2 = ConditionalOfferFactory(name='offer2')
        offer3 = ConditionalOfferFactory(name='offer3')
        offer1.exclusive = True
        offer2.exclusive = False
        offer3.exclusive = False

        for line in filled_basket.all_lines():
            assert line.consumer.consumed(offer1) == 0
            assert line.consumer.consumed(offer2) == 0

        line1, line2 = list(filled_basket.all_lines())

        # exclusive offer consumes one item on line1
        line1.consumer.consume(1, offer1)

        # offer1 is exclusive so that blocks other offers
        assert line1.is_available_for_offer_discount(offer2) is False

        line1.consumer.consume(99, offer1)
        # ran out of room for offer1
        assert line1.is_available_for_offer_discount(offer1) is False
        # offer2 was never an option
        assert line1.is_available_for_offer_discount(offer2) is False

        # exclusivity is per line so line2 is available for offer2
        line2.consumer.consume(1, offer2)
        # nope: exclusive and non-exclusive don't mix
        assert line2.is_available_for_offer_discount(offer1) is False

        line2.consumer.consume(99, offer2)
        # ran out of room for offer2
        assert line2.is_available_for_offer_discount(offer1) is False
        # but still room for offer3!
        assert line2.is_available_for_offer_discount(offer3) is True

    def test_consumed_with_exclusive_offer_2(self, filled_basket):
        offer1 = ConditionalOfferFactory(name='offer1')
        offer2 = ConditionalOfferFactory(name='offer2')
        offer3 = ConditionalOfferFactory(name='offer3')
        offer1.exclusive = True
        offer2.exclusive = False
        offer3.exclusive = False

        for line in filled_basket.all_lines():
            assert line.consumer.consumed(offer1) == 0
            assert line.consumer.consumed(offer2) == 0

        line1, line2 = list(filled_basket.all_lines())

        # exclusive offer consumes one item on line1
        line1.consumer.consume(1, offer1)
        remaining1 = line1.quantity - 1

        assert line1.quantity_with_offer_discount(offer1) == 1
        assert line1.quantity_with_offer_discount(offer2) == 0
        assert line1.quantity_with_offer_discount(offer3) == 0

        assert line1.quantity_without_offer_discount(offer1) == remaining1
        assert line1.quantity_without_offer_discount(offer2) == 0
        assert line1.quantity_without_offer_discount(offer3) == 0

        # exclusive offer consumes all items on line1
        line1.consumer.consume(remaining1, offer1)
        assert line1.quantity_with_offer_discount(offer1) == line1.quantity
        assert line1.quantity_with_offer_discount(offer2) == 0
        assert line1.quantity_with_offer_discount(offer3) == 0

        assert line1.quantity_without_offer_discount(offer1) == 0
        assert line1.quantity_without_offer_discount(offer2) == 0
        assert line1.quantity_without_offer_discount(offer3) == 0

        # non-exclusive offer consumes one item on line2
        line2.consumer.consume(1, offer2)
        remaining2 = line2.quantity - 1

        assert line2.quantity_with_offer_discount(offer1) == 0
        assert line2.quantity_with_offer_discount(offer2) == 1
        assert line2.quantity_with_offer_discount(offer3) == 0

        assert line2.quantity_without_offer_discount(offer1) == 0
        assert line2.quantity_without_offer_discount(offer2) == remaining2
        assert line2.quantity_without_offer_discount(offer3) == line2.quantity

        # non-exclusive offer consumes all items on line2
        line2.consumer.consume(remaining2, offer2)

        assert line2.quantity_with_offer_discount(offer1) == 0
        assert line2.quantity_with_offer_discount(offer2) == line2.quantity
        assert line2.quantity_with_offer_discount(offer3) == 0

        assert line2.quantity_without_offer_discount(offer1) == 0
        assert line2.quantity_without_offer_discount(offer2) == 0
        assert line2.quantity_without_offer_discount(offer3) == line2.quantity

    def test_consumed_by_application(self, filled_basket, single_offer):
        basket = filled_basket
        Applicator().apply(basket)
        assert len(basket.offer_applications.offer_discounts) == 1
        assert [x.consumer.consumed() for x in basket.all_lines()] == [1, 0]

    def test_consumed_with_combined_offer(self, filled_basket):
        offer1 = ConditionalOfferFactory(name='offer1')
        offer2 = ConditionalOfferFactory(name='offer2')
        offer3 = ConditionalOfferFactory(name='offer3')
        offer4 = ConditionalOfferFactory(name='offer4')
        offer1.exclusive = True
        offer2.exclusive = False
        offer3.exclusive = False
        offer4.exclusive = False
        offer2.combinations.add(offer3)
        assert offer3 in offer2.combined_offers
        assert offer2 in offer3.combined_offers

        for line in filled_basket.all_lines():
            assert line.consumer.consumed(offer1) == 0
            assert line.consumer.consumed(offer2) == 0
            assert line.consumer.consumed(offer3) == 0

        line1 = filled_basket.all_lines()[0]

        # combinable offer consumes one item of line1
        line1.consumer.consume(1, offer2)
        remaining1 = line1.quantity - 1

        assert line1.quantity_with_offer_discount(offer1) == 0
        assert line1.quantity_with_offer_discount(offer2) == 1
        assert line1.quantity_with_offer_discount(offer3) == 0
        assert line1.quantity_with_offer_discount(offer4) == 0

        assert line1.quantity_without_offer_discount(offer1) == 0
        assert line1.quantity_without_offer_discount(offer2) == remaining1
        assert line1.quantity_without_offer_discount(offer3) == line1.quantity
        assert line1.quantity_without_offer_discount(offer4) == 0

        # combinable offer consumes one item of line1
        line1.consumer.consume(1, offer3)
        assert line1.quantity_with_offer_discount(offer1) == 0
        assert line1.quantity_with_offer_discount(offer2) == 1
        assert line1.quantity_with_offer_discount(offer3) == 1
        assert line1.quantity_with_offer_discount(offer4) == 0

        assert line1.quantity_without_offer_discount(offer1) == 0
        assert line1.quantity_without_offer_discount(offer2) == remaining1
        assert line1.quantity_without_offer_discount(offer3) == remaining1
        assert line1.quantity_without_offer_discount(offer4) == 0

        # combinable offer consumes all items of line1
        line1.consumer.consume(remaining1, offer2)

        assert line1.quantity_with_offer_discount(offer1) == 0
        assert line1.quantity_with_offer_discount(offer2) == line1.quantity
        assert line1.quantity_with_offer_discount(offer3) == 1
        assert line1.quantity_with_offer_discount(offer4) == 0

        assert line1.quantity_without_offer_discount(offer1) == 0
        assert line1.quantity_without_offer_discount(offer2) == 0
        assert line1.quantity_without_offer_discount(offer3) == remaining1
        assert line1.quantity_without_offer_discount(offer4) == 0


text:
* CQRS in 10 mins
* EventSourcing in 10 mins
* Q&A
* Workshop intro
* Workshop (yes, **you** code) 1-3
* break
* Workshop (yes, **you** code) 4-7
* Q&A

--

### *Kudos*

Oliver Wolf

https://innoq.com

Greg Young

https://goodenoughsoftware.net/

--

#### "You can do CQRS without EventSourcing, but
#### you cannot do EventSourcing without CQRS."

---

## CQRS

##### COMMAND QUERY RESPONSIBILITY SEGREGATION

--
![](md/c1.png "")
Traditional Layered Architecture

--

![](md/c2.png "")
CQRS Pattern applied – done.

--

## THAT IS IT!?

--

![](md/c3.png "")

pro: scale independently

--

![](md/c4.png "")

pro: optimized Query-Models (denormalization)

--

![](md/c5.png "")

pro: **thin** read layer

--

![](md/c6.png "")

pro: Eventual Consistency & Read-Replicas

--

### Conclusion

CQRS helps with

* asymmetric load / read replicas
* gain from different QueryModels / Technologies
* helps Time-to-Market
* avoids technology Lock-In
* enables local optimization on Query-Models

---

# EventSourcing
#### as a Concept

--

"An architectural pattern which warrants that your entities (as per Eric Evans' definition) do not track their internal state by means of *direct serialization or O/R mapping*, but by means of **reading and committing events** to an event store."

--

### EventSourcing

* Architectural Pattern
* EventStore keeps log of Events (Facts)
* 'current' State is
 * transient
 * disposable
 * fully/reliably reconstructible from series of Events

--

![](http://image.slidesharecdn.com/fromcrudtoeventsourcinganinvestiblestockuniverse-slides-150319095920-conversion-gate01/95/from-crud-to-event-sourcing-an-investible-stock-universe-14-638.jpg?cb=1426759432)

--

![](md/es.png "")

--

### Pros

* focus on **state transitions**, rather than data structure
* audit log already included
* reports over the past
* no Information-loss (Socks, Item 137)
* replayable
 * basically Time Machine (travel back and forth)
 * history of System state
 * helps debugging
 * no infamous SQL-migration-scripts, just change aggregation and replay

--

### Cons

* maybe different angle to modeling
* (a little) more complex than a CRUD System
* new challenges like:
 * aggregation performance
 * evolving events
 * capacity

proven Patterns for the new challenges ***do*** exist!

--

### Myths

* artificial approach to modeling (**not** true)
* requires eventual consistency  (**not** true)
* inherently difficult & complex  (**not** true)
* bad performance (**not** true)

--

### Questions up to here?

---

#### EventSourcing Basics
## Workshop

--

## Disclaimer

the code here is

* **NOT** an EventSourcing framework !
* just for demonstration of concepts
* oversimplified
* Java, but can be done in any language
* very basic DI with Spring, but can be done without
* uses Lombok for brevity (just syntactical sugar)

--

![There are many ways to skin a Cat](md/skin_a_cat.jpg "many ways to skin a Cat")

There are many ways to skin a Cat

--

### This Workshop is about
## **Discussion**
### not Code

---

#### EventSourcing Basics
## Intro

--

Hello, we are FooBank !

--

### Our Domain

* local Bank
* physical Counter
* will expand into online-banking

--

### Infrastructure

![](md/es_overview.png "overview")

--

##### Glossary

| Component 	| Responsibility 	|
|---		|---			|
| ApplicationFacade   	| single Entry Point / internal API (optional)  	|
| Command   	| Request for the System to *do* something	|
| CommandBus  	| find CmdHandler for given Cmd   	|
| CommandHandler | accept or reject Command, emit Effects |
| Effects | List of Messages |
| Message	| Event or Command  	|
| Event   	| a given Fact  	|
| EventStore  	| a log of Events *that have happened*  	|
| EventHandler/View   	| process Events, project useful Model   	|
| Query | a Question to a Model |
| QueryModel  	| queried by the outside world, query-optimized data	|
| ValidationModel  	| answers Queries while validating   	|

---

#### EventSourcing Basics
#### Session 1
### Aggregating to the
### canonical Domain Model

--

### Canonical Domain Model

	public class Account {
	    private final UUID id;
	    private final String firstName;
	    private final String lastName;
	    private int balance = 0;

	    void credit(int amount) { balance += amount; }
	    void debit(int amount)  { balance -= amount; }
	}

--

| UseCase Deposition |
|- |
|    |
| As a Customer |
| I want to **deposit** cash at the counter |
| in order to credit it to my account. |

--

| UseCase Withdrawal |
|- |
|    |
| As a Customer |
| I want to **withdraw** money from my account at the counter |
| in order to cash it out. |

--

![](md/es-foo-dm.png "overview")

--

### What we learn

* Implement **write** side
 * minimal Commands
 * minimal CommandHandlers
 * minimal Events
* Implement **read** side
 * minimal EventHandlers (Views)
 * populate the canonical Domain Model

--

git clone https://github.com/uweschaefer/es-basics.git

--
### Session 1
1. Implement **ApplicationFacade.deposit/withdraw**
1. Create **Command classes** for both UseCases (see *CreateAccountCommand*)
1. Create **CommandHandlers** for both UseCases (see *CreateAccountHandler*)
1. Create **Event** classes for every UseCase (see *AccountCreatedEvent*)
1. Extend **AccountView** to aggregate Accounts
1. Pass the Tests

--

### What just happened?

* complete Roundtrip
 * Command -> CommandHandler
 * Event -> EventHandler (View)
 * Query via DomainModel

---

#### EventSourcing Basics
#### Session 2
## Dedicated QueryModel

--

## Overview

![](md/es-foo-rm.png "overview")

--

## Aggregation

AccountView = EventHandler that aggregates Events to an Account.

--

### Not every Query within one Account

--

| UseCase ValuedCustomerReport |
|- |
|    |
| As a Manager, I want |
| a complete report the lists all *valued customers* |
| in order to free them from handling charges. |

--

| Specification ValuedCustomer |
|- |
|    |
| a *valued Customer* |
| has deposited an amount of **>=1000€ at least twice**. |

--

### How **not** to do that

Iterate Accounts and inspect their Depositions one by one.

--

### What we learn

* Aggregate beyond Entity-Boundaries
* Create **dedicated Read Model**
 * find appropriate DataStructure
 * select Event-Types by @EventConsumer Methods

--

### Session 2

1. git clean -fd && git reset --hard session2
1. implement ValuedCustomerReportView
1. pass the Tests

--

### What just happened?

* we added a dedicated Read/Query-Model
 * beyond aggregate boundaries
 * Query-optimized Datastructure
 * PullViews have to actually **pull** the events from the ES at some point.

---

#### EventSourcing Basics
#### Session 3 (Bonuslevel)
## Rolling Snapshot QueryModel

--

## Overview

* ValuedCustomerSupport aggregates ALL depositions in the System
* gets slower & slower
* how to tacle that?

--

### Problematic

every time a Report is needed, a new View has to be created.

	facade.deposit(...);

	ValuedCustomerReportView report1 = new ValuedCustomerReportView(es);
	assertTrue(report1.isValuedCustomer(...));

	facade.deposit(...);

	ValuedCustomerReportView report2 = new ValuedCustomerReportView(es);
	assertTrue(report2.isValuedCustomer(...));

--

## What if?

we could reuse a QueryModel, that is being updated, rather than re-created?

	ValuedCustomerReportView report = new ValuedCustomerReportView(es);

	facade.deposit(...);
	assertTrue(report.isValuedCustomer(...));

	facade.deposit(...);
	assertTrue(report.isValuedCustomer(...));

____

 **discuss** what would be necessary, conceptually?

--

## No, really – **Discuss**

--

### What we just learned?

* Concept of Rolling Snapshot

--

### Session 3

1. git clean -fd && git reset --hard session3
1. look at *View.last*, *View.apply* and *PullView.pullEvents*
1. change ValueCustomerReport appropriately.
1. pass the Tests

--

### What just happened?

* Rolling Snapshot
 * keeps latest
* Eventstore provides query of EventStream from **after** a particular event
* And yes, we can have more snapshots than one, if needed

--

### Have a break.

![Have a KitKat](md/kitkat.jpg)

### Have a KitKat

---

#### EventSourcing Basics
#### Session 4
## Event Design

--

| UseCase Transfer |
|- |
|    |
| As a user, I want to |
| transfer Money from my account to someone else's |
| in order to pay my rent online. |

--

### Acceptance Criteria

* *AccountUnknownException* if receiver or sender account does not exist
* *UnfundedTransferException* if sender does not have enough money (no debt allowed)

--

### What we learn

* Event granularity matters
* Events need to reveal their intent
* Use of a ValidationModel
* Commands can be rejected

--

### Session 4

1. git clean -fd && git reset --hard session4
1. Implement *TransferHandler*
1. pass the Tests

--

### What just happened?

* Granularity: Events belong to ONE Aggregate
 * we need SendTransfer, ReceiveTransfer
* Events reveal intent
 * do not reuse WithdrawnEvent etc, its a different UseCase!

---

#### EventSourcing Basics
#### Session 5 (Bonuslevel)
### Dedicated WriteModel / ValidationModel

--

#### Command validation sometimes needs Context

--

### Your take on Criteria 1?

* *AccountUnknownException* if receiver or sender account does not exist

	private boolean exists(UUID id) {
		return repo.find(id) != null;
	}

Using AccountView just to find out if an Account exists is wasteful.

--

### All we really need to know
### is if the aggregate exists.

--

## Overview

![](md/es-foo-wm.png "overview")

--

### CommandHandler
#### Responsibilities

* validate command
* accept or reject command based on that validation
* emit Messages on accepting

--

### Session 5

1. git clean -fd && git reset --hard session5
1. implement KnownAccountsView
1. pass the Tests

--

### What just happened?

* dedicated WriteModel / ValidationModel
* does not have to be DomainModel, as it does not need behaviour

---

#### EventSourcing Basics
#### Session 6
## Side-Effects

--

* Some Commands may trigger external behavior.
* Replaying that would be problematic.

--

| UseCase Notification |
|- |
|    |
| As a user, I want to |
| be notified by email when I receive a transfer |
| in order to buy champagne asap. |

--

### What we learn

* how/where to model Side-Effect

--

### Session 6

1. git clean -fd && git reset --hard session6
1. use CreditNotificationService to send mail
1. discuss where/how to do it properly
1. hint: see CommandBus.publish()
1. pass the Tests

--

### What just happened?

* CommandBus has to be reliable
* Commands can be Effects, too
* Side-Effects can be modeled as Commands / CommandHandlers

---

# Intermission

--

What about Consistency?

--

Did we relax Consistency compared to a normal CRUD/ORM implementation?

--

# NO!

--

But where we could, how can we take advantage?

---

#### EventSourcing Basics
#### Session 7 (Bonuslevel)
## Push-Views

--

Up to now, all views have been *PullView*s, that call *pullEvents()* to stream events into them.

--

### Pro

* we can define when to update the View's State

--

### Con

* we have to Query the EventStore in order to know, if View's State is stale
 * the more Queries we run, the more catastrophic this is:
   * bad Latency for Queries
   * high Contention on EventStore

--

| UseCase GoldCustomers |
|- |
|    |
| As an accountant, I want to |
| know all the Gold-Customers |
| in order to be extra nice to them. |

--

| Specification Gold Customer |
|- |
|    |
|someone who received a transfer **>=10.000€** |
|at least once|

--

### Acceptance Criteria

* report must be **instant!** (low-latency)
* report must be a collection of Strings "<LASTNAME>, <FIRSTNAME>"
* order is not important
* only Transfers count – Depositions **must not** be examined
* report does not need to include GoldCustomer that received the status in the last few seconds...

--

... which means **Eventual Consistency** is ok

--

![](md/es-foo-push.png "overview")

--

#### What would be necessary to push events to the view?

--

### What we learn

* Use Push-Model for Views
* pros and cons of push vs pull

--

### Session 7

1. git clean -fd && git reset --hard session7
1.  implement GoldCustomers *extends PushView*
1.  pass the Tests

--

### What just happened?

* Implemented a push-View that is updated by processing Events asynchronously
* Push reduces read latency
* introduces eventual consistency
* introduces concurrency
* PushViews mostly unusable as Validation Model (not strictly consistent)

---

One possible solution can be found here

git clean -fd && git reset --hard theend

--

### Links

* O.Wolfs CQRS Slides
 * https://speakerdeck.com/owolf/cqrs-for-great-good-2
* Greg Young's Blog
 * https://goodenoughsoftware.net/
* Axon mature ES Framework
 * http://www.axonframework.org/
* Lagom Modern ES Framework based on Akka
 * https://www.lightbend.com/lagom
* Microsofts CQRS/ES Patterns & Practices
 * https://msdn.microsoft.com/en-us/library/jj554200.aspx

--

## Q & A


text:
module ConveyorBelt

  class Contract

    attr_reader :mass_operation

    def perform target
      raise "You must implement perform(target) on #{self.class}"
    end

    def find target_id
      target_id
    end

    def tie_to_mass_operation mass_operation
      @mass_operation = mass_operation
    end

    def kick_off_all_pending_operations mass_operation
      mass_operation.examined_list
        .select { |x| x['task'].to_s == 'mark_for_execution' }
        .map    { |x| x['target_id'] }
        .reject { |x| mass_operation.succeeded_ids.include? x }
        .each   { |t| mass_operation.operations.select { |o| o.target_id == t }.first.execute }

      mass_operation.examined_list
        .select { |x| x['task'].to_s == 'mark_for_ignoring' }
        .map    { |x| x['target_id'] }
        .reject { |x| mass_operation.ignored_ids.include? x }
        .each   { |t| mass_operation.operations.select { |o| o.target_id == t }.first.ignore }
    end

    def execute target_id
      perform find(target_id)
      mass_operation.succeeded! target_id
    end

    def ignore target_id
      mass_operation.ignored! target_id
    end

    def data
      mass_operation.data
    end

  end

end


text: <input class="radio__control" type="radio" autocomplete="off"/>


text:
MAGENTO MULTI INSTALLER

Downloads and install all magento versions what you need.

Current features:
- Automatically download magento versions what you need
- Unpack versions to you folder
- Install magento versions (and update installator to work with mysql 5.6+ and php 5.4+)
- Install sample data
- Reindex after version install
- Install extensions using modman

How to use:

-  Add this tool to some folder
- `cp builds.txt.example builds.txt` and set up the builds what you need. Just add a versions to new lines. To disable version just add # to the line
- `cp config.php.example config.php` and set up configuration in config.php
- execute `php run.php /path/to/project/` to insall versions to this folder


text:
package com.dailyreminder;

public class AddEvent {

    public String name, hour, notes;
    public int hourita, minute;

    public AddEvent(String name, String hour, String notes, int horita, int minute) {
        this.name = name;
        this.hour = hour;
        this.notes = notes;
        this.hourita = horita;
        this.minute = minute;
    }
}


text:
/*global describe:true, it:true , beforeEach:true*/
'use strict';

var dConsts = require("../../../../models/consts/dispute"),
	should = require('should'),
	DisputeResolutionServ;

describe('Dispute Resolution Serv Tests', function() {

	var req;

	before(function() {
		DisputeResolutionServ = require('../../../../models/wrappers/disputeResolutionServ');
	});

	beforeEach(function() {

		req = {
			user: {
				accountNumber: 1234567890,
				actorInfoVO: {
					actorAccountNumber: "2139379595557968797",
					actorId: "1234",
					actorRiskDetails: {}
				}
			},
			session: {
				actionRequestor: dConsts.actionRequestor.seller
			},
			params: {
				txnId: "553022514C496572Y",
				caseId: "PP-000-000-710-094"
			},
			locality: {
				getCountrySpecifics: function() {
					return {
						countryCode: "US"
					}
				},
				culture: "en-US"
			}
		};
	});

	it('should send message for propose offer with no return and no replace', function(done) {

		var input = {
				    actor_details: {
				        entity: "PAYPAL",
				        actor_type: "1",
				        login_id: "8573727",
				        account_number: "2278764496903208703"
				    },
				    notes: "decline offer",
				    amount: {
				        value: "800",
				        currency: "USD"
				    },
				    return_item: false,
					replace_item: false,
					invoice_id: "1234567890",
				    disputeId: "PP-000-000-710-094"
				}
		DisputeResolutionServ.proposePartialRefund(input, function(err, result) {
			should.not.exist(err);
			should(result.body.response_status).equal('0');
			done();
		});

	});

	it('should send message for propose offer with return', function(done) {

		var input = {
				    actor_details: {
				        entity: "PAYPAL",
				        actor_type: "1",
				        login_id: "8573727",
				        account_number: "2278764496903208703"
				    },
				    notes: "decline offer",
				    amount: {
				        value: "800",
				        currency: "USD"
				    },
				    return_item: true,
					replace_item: false,
					invoice_id: "1234567890",
				    disputeId: "PP-000-000-710-094"
				}
		DisputeResolutionServ.proposePartialRefund(input, function(err, result) {
			should.not.exist(err);
			should(result.body.response_status).equal('0');
			done();
		});

	});

	it('should send message for propose offer with replace', function(done) {

		var input = {
				    actor_details: {
				        entity: "PAYPAL",
				        actor_type: "1",
				        login_id: "8573727",
				        account_number: "2278764496903208703"
				    },
				    notes: "decline offer",
				    amount: {
				        value: "800",
				        currency: "USD"
				    },
				    return_item: false,
					replace_item: true,
					invoice_id: "1234567890",
				    disputeId: "PP-000-000-710-094"
				}
		DisputeResolutionServ.proposePartialRefund(input, function(err, result) {
			should.not.exist(err);
			should(result.body.response_status).equal('0');
			done();
		});

	});

	it('should send message for decline offer', function(done) {

		var input = {
				    actor_details: {
				        entity: "PAYPAL",
				        actor_type: "1",
				        login_id: "8573727",
				        account_number: "2278764496903208703"
				    },
				    notes: "decline offer",
				    amount: {
				        value: "800",
				        currency: "USD"
				    },
				    disputeId: "PP-000-000-710-094"
				}
		DisputeResolutionServ.denyPartialRefund(input, function(err, result) {
			should.not.exist(err);
			should(result.body.response_status).equal('0');
			done();
		});

	});

	it('should send message for accept offer', function(done) {

		var input = {
				    actor_details: {
				        entity: "PAYPAL",
				        actor_type: "1",
				        login_id: "8573727",
				        account_number: "2278764496903208703"
				    },
				    notes: "accept offer",
				    amount: {
				        value: "800",
				        currency: "USD"
				    },
				    disputeId: "PP-000-000-710-094"
				}
		DisputeResolutionServ.acceptPartialRefund(input, function(err, result) {
			should.not.exist(err);
			should(result.body.response_status).equal('0');
			done();
		});

	});

	it('should update the photo evidence email successfully', function(done) {

		var input = {
				    actor_details: {
				        entity: "PAYPAL",
				        actor_type: "1",
				        login_id: "8573727",
				        account_number: "2278764496903208703"
				    },
				    photo_evidence_email: "someone@gmail.com",
					seller_notes: "notes for photo evidence",
				    disputeId: "PP-000-000-710-094"
				}
		DisputeResolutionServ.updateMerchandiseDispute(input, function(err, result) {
			should.not.exist(err);
			should(result.body.response_status).equal('0');
			done();
		});

	});

});


text:
import mongoose from "mongoose"
import Test488 from "./test488.js"

mongoose.connect('mongodb://localhost/test-maker')


text:
package org.apache.doris.analysis;

import org.apache.doris.common.AnalysisException;
import org.apache.doris.mysql.privilege.MockedAuth;
import org.apache.doris.mysql.privilege.PaloAuth;
import org.apache.doris.qe.ConnectContext;

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

import mockit.Mocked;
import mockit.internal.startup.Startup;

public class ShowCreateTableStmtTest {
    private Analyzer analyzer;

    @Mocked
    private PaloAuth auth;
    @Mocked
    private ConnectContext ctx;

    static {
        Startup.initializeIfPossible();
    }

    @Before
    public void setUp() {
        analyzer = AccessTestUtil.fetchAdminAnalyzer(true);
        MockedAuth.mockedAuth(auth);
        MockedAuth.mockedConnectContext(ctx, "root", "192.168.1.1");
    }

    @Test
    public void testNormal() throws AnalysisException {
        ShowCreateTableStmt stmt = new ShowCreateTableStmt(new TableName("testDb", "testTbl"));
        stmt.analyze(analyzer);
        Assert.assertEquals("SHOW CREATE TABLE testCluster:testDb.testTbl", stmt.toString());
        Assert.assertEquals("testCluster:testDb", stmt.getDb());
        Assert.assertEquals("testTbl", stmt.getTable());
        Assert.assertEquals(2, stmt.getMetaData().getColumnCount());
        Assert.assertEquals("Table", stmt.getMetaData().getColumn(0).getName());
        Assert.assertEquals("Create Table", stmt.getMetaData().getColumn(1).getName());
    }

    @Test(expected = AnalysisException.class)
    public void testNoTbl() throws AnalysisException {
        ShowCreateTableStmt stmt = new ShowCreateTableStmt(null);
        stmt.analyze(analyzer);
        Assert.fail("No Exception throws.");
    }
}


text:
<?php
namespace App\Model\Entity;

use Cake\ORM\Entity;

/**
 * Grade Entity.
 */
class Grade extends Entity
{

    /**
     * Fields that can be mass assigned using newEntity() or patchEntity().
     *
     * @var array
     */
    protected $_accessible = [
        'grade_level' => true,
        'country_id' => true,
        'name' => true,
        'country' => true,
    ];
}


text:
                Convocatoria

                        Institución:

                        Sector educativo:

                        Ciudad:

Indexada en:

Áreas de conocimiento

                        Gran Área
                        Área
                        Disciplina

Detalles

                    Descripción:

                    Para más información:
                    Enlace a convocatoria

                        Fecha:

                                    Desde:

                                    Hasta:

        <button class="ui button red" id="button_report_details">Denunciar publicación</button>