text:
<?php

namespace Thruway\Tests\Unit\Role;

class BrokerTest extends \Thruway\Tests\TestCase
{
    public function testUnsubscribeFromNonExistentSubscription()
    {
        $transport = $this->getMockBuilder('\Thruway\Transport\TransportInterface')
            ->getMock();

        $transport->method("getTransportDetails")->will($this->returnValue(""));

        $session = $this->getMockBuilder('\Thruway\Session')
            ->setMethods(["sendMessage"])
            ->setConstructorArgs([$transport])
            ->getMock();

        $broker = new \Thruway\Role\Broker();

        $session->expects($this->once())
            ->method("sendMessage")
            ->with($this->isInstanceOf('\Thruway\Message\ErrorMessage'));

        $unsubscribeMsg = new \Thruway\Message\UnsubscribeMessage(\Thruway\Common\Utils::getUniqueId(), 0);

        $messegeEvent = new \Thruway\Event\MessageEvent($session, $unsubscribeMsg);
        $broker->handleUnsubscribeMessage($messegeEvent);
    }

    public function testDoNotExcludeMe()
    {
        $transport = $this->getMockBuilder('\Thruway\Transport\TransportInterface')
            ->getMock();

        $transport->expects($this->any())->method("getTransportDetails")->will($this->returnValue(""));

        $session = $this->getMockBuilder('\Thruway\Session')
            ->setMethods(["sendMessage"])
            ->setConstructorArgs([$transport])
            ->getMock();
        /** @var $session \Thruway\Session */
        $session->setRealm(new \Thruway\Realm("testrealm"));

        $broker = new \Thruway\Role\Broker();

        $subscribeMsg = new \Thruway\Message\SubscribeMessage('\Thruway\Session', [], "test_subscription");

        /** @var \Thruway\Message\SubscribedMessage $subscribedMsg */
        $subscribedMsg = null;

        $session->expects($this->exactly(3))
            ->method("sendMessage")
            ->withConsecutive(
                [
                    $this->callback(function ($msg) use (&$subscribedMsg) {
                        $this->isInstanceOf('\Thruway\Message\SubscribedMessage');
                        $subscribedMsg = $msg;
                        return true;
                    })
                ],
                [$this->isInstanceOf('\Thruway\Message\EventMessage')],
                [$this->isInstanceOf('\Thruway\Message\PublishedMessage')]

            );

        $messageEvent = new \Thruway\Event\MessageEvent($session, $subscribeMsg);
        $broker->handleSubscribeMessage($messageEvent );

        $subscriptionId = $subscribedMsg->getSubscriptionId();

        $publishMsg = new \Thruway\Message\PublishMessage(
            \Thruway\Common\Utils::getUniqueId(),
            ['exclude_me' => false, 'acknowledge' => true],
            'test_subscription'
        );

        $messageEvent = new \Thruway\Event\MessageEvent($session, $publishMsg);
        $broker->handlePublishMessage($messageEvent);
    }

    public function testPrefixMatcherValidUris() {

        $prefixMatcher = new \Thruway\Subscription\PrefixMatcher();
        $options = (object)[];

        $this->assertTrue($prefixMatcher->uriIsValid('', $options));
        $this->assertTrue($prefixMatcher->uriIsValid('.', $options));
        $this->assertTrue($prefixMatcher->uriIsValid('one', $options));
        $this->assertTrue($prefixMatcher->uriIsValid('one.', $options));
        $this->assertTrue($prefixMatcher->uriIsValid('one.two', $options));
        $this->assertTrue($prefixMatcher->uriIsValid('one.two.', $options));

        $this->assertFalse($prefixMatcher->uriIsValid('..', $options));
        $this->assertFalse($prefixMatcher->uriIsValid('one..', $options));
        $this->assertFalse($prefixMatcher->uriIsValid('!', $options));
        $this->assertFalse($prefixMatcher->uriIsValid('one..two', $options));
        $this->assertFalse($prefixMatcher->uriIsValid('one..two.', $options));

        $this->assertTrue($prefixMatcher->matches('a', '.', $options));
        $this->assertTrue($prefixMatcher->matches('a', '', $options));
        $this->assertTrue($prefixMatcher->matches('a.b', '.', $options));
        $this->assertTrue($prefixMatcher->matches('a.b', '', $options));
        $this->assertTrue($prefixMatcher->matches('a', 'a', $options));
        $this->assertTrue($prefixMatcher->matches('ab', 'a', $options));
        $this->assertTrue($prefixMatcher->matches('a.b', 'a', $options));
        $this->assertFalse($prefixMatcher->matches('a', 'a.', $options));
        $this->assertTrue($prefixMatcher->matches('a.b', 'a.', $options));
        $this->assertTrue($prefixMatcher->matches('a.b.c', 'a.', $options));
    }

    public function testPrefixMatcher()
    {
        $transport = $this->getMockBuilder('\Thruway\Transport\TransportInterface')
            ->getMock();

        $transport->expects($this->any())->method("getTransportDetails")->will($this->returnValue(""));

        $session = $this->getMockBuilder('\Thruway\Session')
            ->setMethods(["sendMessage"])
            ->setConstructorArgs([$transport])
            ->getMock();
        /** @var $session \Thruway\Session */
        $session->setRealm(new \Thruway\Realm("testrealm"));

        $broker = new \Thruway\Role\Broker();

        $subscribeMsg = new \Thruway\Message\SubscribeMessage('\Thruway\Session',
            (object)["match" => "prefix"],
            "test_subscription");

        /** @var \Thruway\Message\SubscribedMessage $subscribedMsg */
        $subscribedMsg = null;

        $session->expects($this->exactly(6))
            ->method("sendMessage")
            ->withConsecutive(
                [
                    $this->callback(function ($msg) use (&$subscribedMsg) {
                        $this->isInstanceOf('\Thruway\Message\SubscribedMessage');
                        $subscribedMsg = $msg;
                        return true;
                    })
                ],
                [$this->callback(function ($val) {
                    $this->assertInstanceOf('\Thruway\Message\EventMessage', $val);
                    $this->assertEquals("test_subscription", $val->getDetails()->topic);
                    return true;
                })],
                [$this->isInstanceOf('\Thruway\Message\PublishedMessage')],
                [$this->callback(function ($val) {
                    $this->assertInstanceOf('\Thruway\Message\EventMessage', $val);
                    $this->assertEquals("test_subscription.more.uri.parts", $val->getDetails()->topic);
                    return true;
                })],
                [$this->isInstanceOf('\Thruway\Message\PublishedMessage')],
                [$this->isInstanceOf('\Thruway\Message\PublishedMessage')]

            );

        $messageEvent = new \Thruway\Event\MessageEvent($session, $subscribeMsg);
        $broker->handleSubscribeMessage($messageEvent );

        $subscriptionId = $subscribedMsg->getSubscriptionId();

        $publishMsg = new \Thruway\Message\PublishMessage(
            \Thruway\Common\Utils::getUniqueId(),
            ['exclude_me' => false, 'acknowledge' => true],
            'test_subscription'
        );

        $messageEvent = new \Thruway\Event\MessageEvent($session, $publishMsg);
        $broker->handlePublishMessage($messageEvent);

        $publishMsg = new \Thruway\Message\PublishMessage(
            \Thruway\Common\Utils::getUniqueId(),
            ['exclude_me' => false, 'acknowledge' => true],
            'test_subscription.more.uri.parts'
        );

        $messageEvent = new \Thruway\Event\MessageEvent($session, $publishMsg);
        $broker->handlePublishMessage($messageEvent);

        $publishMsg = new \Thruway\Message\PublishMessage(
            \Thruway\Common\Utils::getUniqueId(),
            ['exclude_me' => false, 'acknowledge' => true],
            'some.non.matching.uri'
        );

        $messageEvent = new \Thruway\Event\MessageEvent($session, $publishMsg);
        $broker->handlePublishMessage($messageEvent);
    }

    public function testUnknownPrefixMatcher()
    {
        $transport = $this->getMockBuilder('\Thruway\Transport\TransportInterface')
            ->getMock();

        $transport->expects($this->any())->method("getTransportDetails")->will($this->returnValue(""));

        $session = $this->getMockBuilder('\Thruway\Session')
            ->setMethods(["sendMessage"])
            ->setConstructorArgs([$transport])
            ->getMock();

//        /** @var $session \Thruway\Session */
//        $session->setRealm(new \Thruway\Realm("testrealm"));

        $broker = new \Thruway\Role\Broker();

        $subscribeMsg = new \Thruway\Message\SubscribeMessage(
            12345,
            (object)["match" => "unknown"],
            "test_subscription"
        );

        $session->expects($this->never())->method("sendMessage");

        $event = new \Thruway\Event\MessageEvent($session, $subscribeMsg);
        $broker->handleSubscribeMessage($event);
    }

//    /**
//     * @throws Exception
//     * @expectedException Exception
//     */
//    public function testBadMessageToOnMessage()
//    {
//        $transport = $this->getMockBuilder('\Thruway\Transport\TransportInterface')
//            ->getMock();
//
//        $transport->expects($this->any())->method("getTransportDetails")->will($this->returnValue(""));
//
//        $session = $this->getMockBuilder('\Thruway\Session')
//            ->setMethods(["sendMessage"])
//            ->setConstructorArgs([$transport])
//            ->getMock();
//
//        $broker = new \Thruway\Role\Broker();
//
//        $goodbyeMsg = new \Thruway\Message\GoodbyeMessage([], 'test_reason');
//
//        $broker->onMessage($session, $goodbyeMsg);
//    }

    public function testRemoveRegistration()
    {
        $transport = $this->getMockBuilder('\Thruway\Transport\TransportInterface')
            ->getMock();

        $transport->expects($this->any())->method("getTransportDetails")->will($this->returnValue(""));

        $session = $this->getMockBuilder('\Thruway\Session')
            ->setMethods(["sendMessage"])
            ->setConstructorArgs([$transport])
            ->getMock();
        /** @var $session \Thruway\Session */
        $session->setRealm(new \Thruway\Realm("testrealm"));

        $broker = new \Thruway\Role\Broker();

        $subscribeMsg = new \Thruway\Message\SubscribeMessage(\Thruway\Common\Utils::getUniqueId(), [], "test.topic");

        $messageEvent = new \Thruway\Event\MessageEvent($session, $subscribeMsg);
        $broker->handleSubscribeMessage($messageEvent );

        $subscriptions = $broker->getSubscriptions();
        $this->assertTrue(count($subscriptions) === 1);

        $subscriptions = array_values($subscriptions);

        $messageEvent = new \Thruway\Event\MessageEvent($session, new \Thruway\Message\UnsubscribeMessage(\Thruway\Common\Utils::getUniqueId(), $subscriptions[0]->getId()));

        $broker->handleUnsubscribeMessage($messageEvent);

        $this->assertTrue(count($broker->getSubscriptions()) === 0);

    }

    private function createTransportInterfaceMock() {
        return $this->createMock('\Thruway\Transport\TransportInterface');
    }

    public function testProcessSubscriptionAddedCalled() {
        $registry = $this->getMockBuilder('\Thruway\Subscription\StateHandlerRegistry')
            ->setConstructorArgs(['state.test.realm'])
            ->getMock();

        $registry->expects($this->once())
            ->method('processSubscriptionAdded')
            ->with($this->isInstanceOf('\Thruway\Subscription\Subscription'));

        $broker = new \Thruway\Role\Broker();

        $broker->setStateHandlerRegistry($registry);

        $session = $this->getMockBuilder('\Thruway\Session')
            ->setMethods(['sendMessage'])
            ->setConstructorArgs([$this->createTransportInterfaceMock()])
            ->getMock();

        $session->expects($this->once())
            ->method('sendMessage')
            ->withConsecutive(
                [$this->isInstanceOf('\Thruway\Message\SubscribedMessage')]
            );

        $subscribeMsg = new \Thruway\Message\SubscribeMessage(1, new \stdClass(), 'test.topic');
        $messageEvent = new \Thruway\Event\MessageEvent($session, $subscribeMsg);
        $broker->handleSubscribeMessage($messageEvent);
    }

    public function testEligibleAuthroles() {
        $transport = $this->getMockBuilder('\Thruway\Transport\TransportInterface')
            ->getMock();

        $transport->method("getTransportDetails")->will($this->returnValue(""));

        $session = $this->getMockBuilder('\Thruway\Session')
            ->setMethods(["sendMessage","getAuthenticationDetails"])
            ->setConstructorArgs([$transport])
            ->getMock();

        $authDetails = new \Thruway\Authentication\AuthenticationDetails();
        $authDetails->addAuthRole("test_role1");
        $authDetails->addAuthRole("test_role2");
        $authDetails->setAuthId("test_authid");

        $session->expects($this->any())->method("getAuthenticationDetails")->willReturn($authDetails);

        $broker = new \Thruway\Role\Broker();

        $session->expects($this->exactly(4))
            ->method("sendMessage")
            ->withConsecutive(
                [$this->isInstanceOf('\Thruway\Message\SubscribedMessage')], // response to subscribe
                [$this->callback(function ($msg) {
                    $this->assertInstanceOf('\Thruway\Message\EventMessage', $msg);
                    $this->assertEquals("first publish", $msg->getArguments()[0]);
                    return true;
                })], // response to publish with no options
                // no message when we are not included in authroles
                [$this->callback(function ($msg) {
                    $this->assertInstanceOf('\Thruway\Message\EventMessage', $msg);
                    $this->assertEquals("third publish", $msg->getArguments()[0]);
                    return true;
                })], // when the first authrole is included
                [$this->callback(function ($msg) {
                    $this->assertInstanceOf('\Thruway\Message\EventMessage', $msg);
                    $this->assertEquals("fourth publish", $msg->getArguments()[0]);
                    return true;
                })] // when the second authrole is included
                // nothing on empty array
                // nothing on invalid non-array option
            );

        $subscribeMessage = new \Thruway\Message\SubscribeMessage(1, (object)[], "a.b.c");

        $messageEvent = new \Thruway\Event\MessageEvent($session, $subscribeMessage);
        $broker->handleSubscribeMessage($messageEvent );

        $pubSession = $this->getMockBuilder('\Thruway\Session')
            ->setMethods(["sendMessage"])
            ->setConstructorArgs([$transport])
            ->getMock();

        $pubSession->expects($this->never())
            ->method("sendMessage");

        // test regular publish
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[], "a.b.c", ["first publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);

        // test publish to authrole that is not us
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[
            "_thruway_eligible_authroles" => ["alpha", "bravo", "charlie"]
        ], "a.b.c", ["second publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);

        // test publish to our first authrole
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[
            "_thruway_eligible_authroles" => ["alpha", "bravo", "test_role1", "charlie"]
        ], "a.b.c", ["third publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);

        // test publish to our second authrole
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[
            "_thruway_eligible_authroles" => ["test_role2"]
        ], "a.b.c", ["fourth publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);

        // test publish to empty authrole
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[
            "_thruway_eligible_authroles" => []
        ], "a.b.c", ["fifth publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);

        // test publish to invalid authrole
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[
            "_thruway_eligible_authroles" => "test_authrole2"
        ], "a.b.c", ["sixth publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);
    }

    public function testEligibleAuthids() {
        $transport = $this->getMockBuilder('\Thruway\Transport\TransportInterface')
            ->getMock();

        $transport->method("getTransportDetails")->will($this->returnValue(""));

        $session = $this->getMockBuilder('\Thruway\Session')
            ->setMethods(["sendMessage","getAuthenticationDetails"])
            ->setConstructorArgs([$transport])
            ->getMock();

        $authDetails = new \Thruway\Authentication\AuthenticationDetails();
        $authDetails->addAuthRole("test_role1");
        $authDetails->addAuthRole("test_role2");
        $authDetails->setAuthId("test_authid");

        $session->expects($this->any())->method("getAuthenticationDetails")->willReturn($authDetails);

        $broker = new \Thruway\Role\Broker();

        $session->expects($this->exactly(4))
            ->method("sendMessage")
            ->withConsecutive(
                [$this->isInstanceOf('\Thruway\Message\SubscribedMessage')], // response to subscribe
                [$this->callback(function ($msg) {
                    $this->assertInstanceOf('\Thruway\Message\EventMessage', $msg);
                    $this->assertEquals("first publish", $msg->getArguments()[0]);
                    return true;
                })], // response to publish with no options
                // no message when we are not included in authroles
                [$this->callback(function ($msg) {
                    $this->assertInstanceOf('\Thruway\Message\EventMessage', $msg);
                    $this->assertEquals("third publish", $msg->getArguments()[0]);
                    return true;
                })], // when the first authrole is included
                [$this->callback(function ($msg) {
                    $this->assertInstanceOf('\Thruway\Message\EventMessage', $msg);
                    $this->assertEquals("fourth publish", $msg->getArguments()[0]);
                    return true;
                })] // when the second authrole is included
            // nothing on empty array
            // nothing on invalid non-array option
            );

        $subscribeMessage = new \Thruway\Message\SubscribeMessage(1, (object)[], "a.b.c");

        $messageEvent = new \Thruway\Event\MessageEvent($session, $subscribeMessage);
        $broker->handleSubscribeMessage($messageEvent );

        $pubSession = $this->getMockBuilder('\Thruway\Session')
            ->setMethods(["sendMessage"])
            ->setConstructorArgs([$transport])
            ->getMock();

        $pubSession->expects($this->never())
            ->method("sendMessage");

        // test regular publish
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[], "a.b.c", ["first publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);

        // test publish to authrole that is not us
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[
            "_thruway_eligible_authids" => ["alpha", "bravo", "charlie"]
        ], "a.b.c", ["second publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);

        // test publish to our first authrole
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[
            "_thruway_eligible_authids" => ["alpha", "bravo", "test_authid", "charlie"]
        ], "a.b.c", ["third publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);

        // test publish to our second authrole
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[
            "_thruway_eligible_authids" => ["test_authid"]
        ], "a.b.c", ["fourth publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);

        // test publish to empty authrole
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[
            "_thruway_eligible_authids" => []
        ], "a.b.c", ["fifth publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);

        // test publish to invalid authrole
        $pubMessage = new \Thruway\Message\PublishMessage(2, (object)[
            "_thruway_eligible_authids" => "test_authid"
        ], "a.b.c", ["sixth publish"]);
        $messageEvent = new \Thruway\Event\MessageEvent($pubSession, $pubMessage);
        $broker->handlePublishMessage($messageEvent);
    }
}


text:
- Create a Blank App (Universal Windows) project.
    - Set the `Minimum version` item to Windows 10 Fall Creators Update (1.0.: Build 16299).

      ![Target version](./images/uwp-target-version.png)

- Install ReactiveProperty package from NuGet.

## Edit codes
- Create a MainPageViewModel.cs file.
- Edit files like following.

MainPageViewModel.cs
```csharp
using Reactive.Bindings;
using System;
using System.Linq;
using System.Reactive.Linq;

namespace GettingStartedUWP
{
    public class MainPageViewModel
    {
        public ReactiveProperty<string> Input { get; }
        public ReadOnlyReactiveProperty<string> Output { get; }

        public MainPageViewModel()
        {
            Input = new ReactiveProperty<string>("");
            Output = Input
                .Delay(TimeSpan.FromSeconds(1))
                .Select(x => x.ToUpper())
                .ToReadOnlyReactiveProperty();
        }
    }
}
```

MainPage.xaml.cs
```csharp
using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace GettingStartedUWP
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private MainPageViewModel ViewModel { get; } = new MainPageViewModel();
        public MainPage()
        {
            this.InitializeComponent();
        }
    }
}
```

MainPage.xaml
```xml
<Page x:Class="GettingStartedUWP.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:GettingStartedUWP"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="Input"
                Style="{StaticResource CaptionTextBlockStyle}" />
        <TextBox Text="{x:Bind ViewModel.Input.Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                Margin="5" />
        <TextBlock Text="Output"
                Style="{StaticResource CaptionTextBlockStyle}" />
        <TextBlock Text="{x:Bind ViewModel.Output.Value, Mode=OneWay}"
                Style="{StaticResource BodyTextBlockStyle}"
                Margin="5" />
    </StackPanel>
</Page>
```

## Launch the application

After launching the app, you can see the below window.
The output value was displayed to upper case, after 1sec from the input.

![Launch the app](./images/launch-uwp-app.gif)

redpajama_set_name: RedPajamaGithub


text:
"Just the jumbles, the jumbles!"
                            --S. Bad


text:
Testing Openshift's S2i capability

https://github.com/justindav1s/s2i-ib-tomcat-base.git

Build a base image running Centos7/OpenJDK 7/Tomcat7

Image built from Docker file

run :

make

or

docker build -t ib-services-base .

Run the image locally on docker

docker run -d -p 8080:8080 ib-services-base

Check :

Should get usage message

to run s2i to build something useful :

s2i build . ib-tomcat-base ib-tomcat-jenkins

then

docker run -d -p 8080:8080 ib-tomcat-jenkins

git clone https://github.com/justindav1s/s2i-ib-tomcat-base.git
cd s2i-ib-tomcat-base/
sudo docker build -t ib-tomcat-base .
sudo docker save ib-tomcat-base > ib-tomcat-base.tar
scp ib-tomcat-base.tar fedora@172.31.26.89:~/

sudo docker save ib-tomcat-base > ib-tomcat-base.tar

sudo docker load < ib-tomcat-base.tar

https://docs.openshift.com/enterprise/3.0/install_config/install/docker_registry.html

[fedora@ip-172-31-26-89 ~]$ sudo docker ps | grep origin-docker-registry
4ffcf611ec9e        openshift/origin-docker-registry:v1.2.0 "/bin/sh -c 'DOCKER_R"   51 minutes ago      Up 51 minutes                           k8s_registry.24455285_docker-registry-1-g0a30_default_0d408b03-7110-11e6-b6be-025ed4a15501_56306bfa
[fedora@ip-172-31-26-89 ~]$ docker exec -it 4ffcf611ec9e find /registry
/registry

[root@ip-172-31-26-89 ~]# oc login
Authentication required for https://ip-172-31-26-89.eu-west-1.compute.internal:8443 (openshift)
Username: justin
Password:
Login successful.

You have access to the following projects and can switch between them with 'oc project <projectname>':

  * default (current)
  * jc1
  * logging
  * management-infra
  * openshift
  * openshift-infra
  * test

Using project "default".
[root@ip-172-31-26-89 ~]# oc whoami -t

V2ifkPhcKgwKX3os9SnqP25G9UG1q7gWRotIbJt7i24

docker login -u <username> -e <any_email_address> -p <token_value> <registry_service_host:port>

get <registry_service_host:port> from registry pod in default project from console

docker login -u justin -e justin.davis@ba.com -p V2ifkPhcKgwKX3os9SnqP25G9UG1q7gWRotIbJt7i24 172.30.231.65:5000

docker tag ib-tomcat-base 172.30.231.65:5000/openshift/ib-tomcat-base

docker push 172.30.231.65:5000/openshift/ib-tomcat-base

Now visible amonst "other images"

docker pull centos/postgresql-94-centos7
docker images
oc whoami -t
docker login -u justin -e justin.davis@ba.com -p ........ 172.30.88.121:5000
docker tag centos/postgresql-94-centos7 172.30.88.121:5000/centos/postgresql-94-centos7

docker tag ib-services-base 172.30.88.121:5000/openshift/ib-services-base
docker push 172.30.88.121:5000/openshift/ib-services-base

https://forums.docker.com/t/command-to-remove-all-unused-images/20/5

docker rmi `docker images | awk '{ print $3; }'`


text:
package org.camunda.bpm.platform.example.migration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

import org.camunda.bpm.BpmPlatform;
import org.camunda.bpm.application.PostDeploy;
import org.camunda.bpm.application.ProcessApplication;
import org.camunda.bpm.application.ProcessApplicationDeploymentInfo;
import org.camunda.bpm.application.ProcessApplicationInfo;
import org.camunda.bpm.application.impl.ServletProcessApplication;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.migration.MigrationPlan;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.repository.ProcessDefinitionQuery;

@ProcessApplication
public class ExampleProcessApplication extends ServletProcessApplication {

  private final static Logger LOG = Logger.getLogger(ExampleProcessApplication.class.getName());

  /**
   * <p>Migrates all process instances from the last version of the process definitions
   * deployed by this application to the latest version.
   */
  @PostDeploy
  public void migrateProcessInstances(ProcessApplicationInfo processApplicationInfo) {

    Map<String, List<ProcessApplicationDeploymentInfo>> deploymentsByEngine = organizeDeploymentsByEngine(processApplicationInfo);

    for (String engineName : deploymentsByEngine.keySet()) {
      ProcessEngine processEngine = BpmPlatform.getProcessEngineService().getProcessEngine(engineName);

      List<ProcessDefinition> latestIncludedProcessDefinitions =
          collectLatestProcessDefinitions(processEngine, deploymentsByEngine.get(engineName));

      for (ProcessDefinition latestDefinition : latestIncludedProcessDefinitions) {
        ProcessDefinition previousDefinition = getPreviousVersion(processEngine, latestDefinition);
        if (previousDefinition != null) {
          migrateInstances(processEngine, previousDefinition, latestDefinition);
        }
      }
    }
  }

  protected Map<String, List<ProcessApplicationDeploymentInfo>> organizeDeploymentsByEngine(ProcessApplicationInfo processApplicationInfo) {
    Map<String, List<ProcessApplicationDeploymentInfo>> deploymentsByEngine = new HashMap<String, List<ProcessApplicationDeploymentInfo>>();

    for (ProcessApplicationDeploymentInfo deployment : processApplicationInfo.getDeploymentInfo()) {
      addToMapOfLists(deploymentsByEngine, deployment.getProcessEngineName(), deployment);
    }

    return deploymentsByEngine;
  }

  protected List<ProcessDefinition> collectLatestProcessDefinitions(ProcessEngine processEngine, List<ProcessApplicationDeploymentInfo> list) {
    List<ProcessDefinition> latestDefinitions = processEngine
      .getRepositoryService()
      .createProcessDefinitionQuery()
      .latestVersion()
      .list();

    Set<String> deploymentIds = collectDeploymentIds(list);

    List<ProcessDefinition> latestDefinitionsForApplication = new ArrayList<ProcessDefinition>();

    for (ProcessDefinition latestDefinition : latestDefinitions) {
      if (deploymentIds.contains(latestDefinition.getDeploymentId())) {
        latestDefinitionsForApplication.add(latestDefinition);
      }
    }

    return latestDefinitionsForApplication;
  }

  protected Set<String> collectDeploymentIds(List<ProcessApplicationDeploymentInfo> deploymentInfos) {
    Set<String> deploymentIds = new HashSet<String>();

    for (ProcessApplicationDeploymentInfo deploymentInfo : deploymentInfos) {
      deploymentIds.add(deploymentInfo.getDeploymentId());
    }

    return deploymentIds;
  }

  /**
   * Selects the process definition with the preceding version for the same key and tenant as the argument.
   */
  protected ProcessDefinition getPreviousVersion(ProcessEngine processEngine, ProcessDefinition processDefinition) {

    if (processDefinition.getVersion() <= 1) {
      return null;
    }

    RepositoryService repositoryService = processEngine.getRepositoryService();

    ProcessDefinitionQuery processDefinitionQuery = repositoryService
      .createProcessDefinitionQuery()
      .processDefinitionKey(processDefinition.getKey())
      .processDefinitionVersion(processDefinition.getVersion() - 1);

    if (processDefinition.getTenantId() != null) {
      processDefinitionQuery.tenantIdIn(processDefinition.getTenantId());
    }
    else {
      processDefinitionQuery.withoutTenantId();
    }

    return processDefinitionQuery.singleResult();
  }

  protected void migrateInstances(ProcessEngine processEngine,
      ProcessDefinition sourceDefinition,
      ProcessDefinition targetDefinition) {

    RuntimeService runtimeService = processEngine.getRuntimeService();

    MigrationPlan migrationPlan = runtimeService
      .createMigrationPlan(sourceDefinition.getId(), targetDefinition.getId())
      .mapEqualActivities()
      .build();

    LOG.info("Migrating all process instances from " + sourceDefinition.getId() + " to " + targetDefinition.getId());

    runtimeService
      .newMigration(migrationPlan)
      .processInstanceQuery(runtimeService.createProcessInstanceQuery().processDefinitionId(sourceDefinition.getId()))
      .execute();
    // .executeAsync() for asynchronous execution in a batch (useful for large numbers of instances)
  }

  protected static <S, T> void addToMapOfLists(Map<S, List<T>> map, S key, T value) {
    List<T> list = map.get(key);
    if (list == null) {
      list = new ArrayList<T>();
      map.put(key, list);
    }
    list.add(value);
  }

}


text:
aspnet-cgi-handler
==================


text:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var request = require('request');
var app = express();

// ROUTE REQUIRES
var st = require('./routes/st')
var tnt = require('./routes/tnt')
var tntlast = require('./routes/tnt-last')

// MIDDLEWARES
app.use(logger('common'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
// app.use(json2xls.middleware);

// // PRE-LOGIN ENDPOINTS
app.use('/api', st)
app.use('/api', tnt)
app.use('/api', tntlast)

// POST LOGIN ENDPOINTS

// CATCH ALL FOR HTML 5 MODE (allows UI-Router driven states)
app.get('*', function (req, res) {
  res.redirect('/#' + req.originalUrl)
})

// ERROR HANDLING
app.use(function(req, res, next) {
  var err = new Error("Can't find it: " + err.status);
  err.status = 404;
  next(err);
});

if (app.get('env') === 'development') {
  console.log('That casual '+ app.get('env') +' environment right?')
}

if (app.get('env') === 'production') {
  console.log('That hardcore '+ app.get('env') +' environment right?')
}

app.use(function(err, req, res, next) {
  res.status(err.status || 500);
});

// SERVER CONNECT

var port = process.env.PORT || 8080;

var server = app.listen(port, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log("You're listening to http://localhost:" +port + " home of the internet's smoothest jazz and easy listening" );
});

module.exports = app;


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

namespace GLR.Grammar.String {
    public class Parser : GLR.Parser<string> {
        public Parser(NonTerminal grammar)
            : base(grammar) {
        }

        public Parser(NonTerminal grammar, Action<LogLevel, string> log, LogLevel level = LogLevel.Info)
            : base(grammar, log, level) {
        }

        public bool Parse(string sourceText) {
            return base.Parse(new Source(sourceText));
        }

    }
}


text:
This project use BenchmarkDotnet to measure performance of parts of NBitcoin implementation.

You can generate flamegraph to view with Perfview on Windows with the following command:
```powershell
dotnet run -c Release -- --runtimes netcoreapp2.1 --filter *GolombRiceFilters* --profiler ETW
```

Where `GolombRiceFilters` is the name of the benchmark class you are insterested in.

For generating flamegraph on linux, see [this comment](https://github.com/MetacoSA/NBitcoin/pull/656#issuecomment-462927805).


text:
using DiscountOffers.Extensions;

namespace DiscountOffers.Models
{
    /// <summary>
    /// A product.
    /// </summary>
    public sealed class Product
    {
        /// <summary>
        /// Name of product.
        /// </summary>
        public string Name { get;}

        /// <summary>
        /// Number of alphabets in the product's name.
        /// </summary>
        public int LetterCount { get; }

        /// <summary>
        /// Create a Product object.
        /// </summary>
        /// <param name="name">Name of product.</param>
        public Product(string name)
        {
            Name = name;

            var filtered = name.AlphabetsOnly();
            LetterCount = filtered.Length;
        }

        /// <summary>
        /// Get a string that represents the current object.
        /// </summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString()
        {
            return Name;
        }
    }
}


text:
package org.postgresql.test.jdbc3;

import org.postgresql.test.TestUtil;
import junit.framework.TestCase;
import java.sql.*;

public class DatabaseMetaDataTest extends TestCase
{

    private Connection _conn;

    public DatabaseMetaDataTest(String name)
    {
        super(name);
    }

    protected void setUp() throws Exception
    {
        _conn = TestUtil.openDB();
        if (TestUtil.haveMinimumServerVersion(_conn, "7.3")) {
            Statement stmt = _conn.createStatement();
            stmt.execute("CREATE DOMAIN mydom AS int");
            stmt.execute("CREATE TABLE domtab (a mydom)");
        }
    }

    protected void tearDown() throws Exception
    {
        if (TestUtil.haveMinimumServerVersion(_conn, "7.3")) {
            Statement stmt = _conn.createStatement();
            stmt.execute("DROP TABLE domtab");
            stmt.execute("DROP DOMAIN mydom");
        }
    }

    public void testGetColumnsForDomain() throws Exception
    {
        if (!TestUtil.haveMinimumServerVersion(_conn, "7.3"))
            return;

        DatabaseMetaData dbmd = _conn.getMetaData();

        ResultSet rs = dbmd.getColumns("%","%","domtab", "%");
        assertTrue( rs.next() );
        assertEquals("a", rs.getString("COLUMN_NAME"));
        assertEquals(Types.DISTINCT, rs.getInt("DATA_TYPE"));
        assertEquals("mydom", rs.getString("TYPE_NAME"));
        assertEquals(Types.INTEGER, rs.getInt("SOURCE_DATA_TYPE"));
        assertTrue( !rs.next() );
    }

}


text:
@extends('layouts.app')

@section('content')

tracks

           Add New

        @include('flash::message')

                    @include('tracks.table')

@endsection


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Fitness Bowl</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/agency.css" rel="stylesheet">

    <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation

                    </button>

                        fitnessbowl

                            Services

                            About

                            Story of Bowl

                            Contact

Welcome to Fitness Bowl!

                Tell Me More

Services

Your high nutrition bowl of fitness has been prepared with fresh ingredients by our specialist Chef who has been tasked to give you a delicious balanced diet.

Breakfast

The most important meal of the day, our breakfast is packed with the right amount of Carbohydrates and Vitamins you need to power you for the day.

Lunch

Usually the weakest moment of the day, we ensure your lunch has the right nutrition value to keep your stomach filled to prevent any craving to indulge.

Dinner

The right dinner is important to ensure no fat/energy deposits are made to keep your weight under control. Our heaviest meal will make sure you're full by restoring your vitals from a busy day and helping you get a good nights rest.

About

Lorem ipsum dolor sit amet consectetur.

2009-2011

Our Humble Beginnings

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!

March 2011

An Agency is Born

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!

December 2012

Transition to Full Service

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!

July 2014

Phase Two Expansion

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt ut voluptatum eius sapiente, totam reiciendis temporibus qui quibusdam, recusandae sit vero unde, sed, incidunt et ea quo dolore laudantium consectetur!

                                    Be Part

Of Our

Story!

Contact Us

Lorem ipsum dolor sit amet consectetur.

                    <form name="sentMessage" id="contactForm" novalidate>

                                    <input type="text" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

                                    <input type="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

                                    <input type="tel" class="form-control" placeholder="Your Phone *" id="phone" required data-validation-required-message="Please enter your phone number.">

                                    <textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

                                <button type="submit" class="btn btn-xl">Send Message</button>

                    </form>

                    Copyright © fitness bowl 2015

                            Privacy Policy

                            Terms of Use


text:
package idv.xfl03.quesreg.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;

public class ConfigTool {
	private HashMap<String,String> config=new HashMap<String,String>();
	public ConfigTool(File configFile){
		InputStreamReader isr=null;
		FileInputStream fis=null;
		BufferedReader br=null;
		try {
			fis=new FileInputStream(configFile);
			isr=new InputStreamReader(fis,"UTF-8");
			br=new BufferedReader(isr);
			String s;
			while((s=br.readLine())!=null){
				if(!s.startsWith("#")&&!s.equalsIgnoreCase("")){
					String[] t=s.split("=");
					if(t.length==2){
						config.put(t[0], t[1]);
					}else if(t.length>2){
						config.put(t[0], s.replaceAll(t[0]+"=",""));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				isr.close();
				fis.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public int getLength(){
		return config.size();
	}
	public int getIntConfig(String name,int defaultInt){
		if(config.get(name)==null)
			return defaultInt;
		try{
			return Integer.parseInt(config.get(name));
		}catch(Exception e){
			return defaultInt;
		}
	}
	public String getStringConfig(String name,String defaultString){
		if(config.get(name)==null)
			return defaultString;
		return config.get(name);
	}
	public boolean getBooleanConfig(String name,boolean defaultBoolean){
		if(config.get(name)==null)
			return defaultBoolean;
		return config.get(name).equalsIgnoreCase("true")||config.get(name).equalsIgnoreCase("1");
	}
}


text:
function [noisyness, average, deviation] = detectNoise(block)
% [noisyness, average, deviation] = detectNoise(block)
%
% Given a block of numbers, this algorithm tries to detect
% whether it consists of noise or not. It returns this in
% a range between 0 and 1. Additionally, the algorithm
% Tells the average value of the noise and the maximum deviation.
%
% Let me try an implementation where I check every 3x3 subblock
% concerning its mean value and its standard deviation. If all blocks
% have about the same, I assume it's just noise.

sizeX = size(block, 2);
sizeY = size(block, 1);

average = mean(mean(block));
deviation = 0.5 * (max(max(block)) - min(min(block)));

% I assume that this is just noise and then try to prove
% it otherwise.
noisyness = 1;

subblockSize = 4
numOutliers = 2

subblockMeans = zeros(sizeY-subblockSize+1, sizeX-subblockSize+1);
subblockDevs = subblockMeans;
for x = 1:(sizeX-subblockSize+1)
	for y = 1:(sizeY-subblockSize+1)
		subblock = block(y:(y+subblockSize-1),x:(x+subblockSize-1));
		sortedSubblock = sort(subblock(:));
		partBlock = sortedSubblock(numOutliers+1:end-numOutliers);
		subblockMeans(y, x) = mean(partBlock);
		subblockDevs(y, x) = max(partBlock) - min(partBlock);
	end
end

noisyness  = subblockDevs;
average = subblockMeans;

% This seem to be suitable values, but they largely depend on the
% size of the dataset. Maybe if I use a percentage of outliers????
% Both, deviation of deviation and deviation of means seem to hold information.
mean(subblockDevs(:))  %% This is the expected deviation on large scale.
max(subblockDevs(:)) - min(subblockDevs(:)) %% This is the deviation of the deviation on large scale
max(subblockMeans(:)) - min(subblockMeans(:))  %% This is the deviation of the means on large scale


text:
package org.motechproject.outbox.api.repository;

import org.ektorp.CouchDbConnector;
import org.ektorp.ViewQuery;
import org.joda.time.DateTime;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import org.motechproject.outbox.api.builder.OutboundVoiceMessageBuilder;
import org.motechproject.outbox.api.contract.SortKey;
import org.motechproject.outbox.api.domain.OutboundVoiceMessage;
import org.motechproject.outbox.api.domain.OutboundVoiceMessageStatus;
import org.motechproject.commons.date.util.DateUtil;

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

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;

/**
 * @author yyonkov
 */
@RunWith(MockitoJUnitRunner.class)
public class AllOutboundVoiceMessagesTest {
    @Mock
    private CouchDbConnector db;

    private String EXTERNAL_ID = "001";
    private List<OutboundVoiceMessage> messages = new ArrayList<OutboundVoiceMessage>();

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void sortedBasedOnCreationTime_LatestFirst() {
        AllOutboundVoiceMessages dao = new AllOutboundVoiceMessages(db);

        DateTime now = DateUtil.now();
        OutboundVoiceMessage message1 = buildMessage(now.minusDays(1).toDate(), 0);
        OutboundVoiceMessage message2 = buildMessage(now.toDate(), 0);
        OutboundVoiceMessage message3 = buildMessage(now.plusDays(1).toDate(), 0);

        messages.add(message1);
        messages.add(message2);
        messages.add(message3);

        when(db.queryView(any(ViewQuery.class), any(Class.class))).thenReturn(messages);

        List<OutboundVoiceMessage> pendingMessages = dao.getMessages(EXTERNAL_ID, OutboundVoiceMessageStatus.PENDING, SortKey.CreationTime);
        assertThat(pendingMessages.get(0), is(message3));
        assertThat(pendingMessages.get(1), is(message2));
        assertThat(pendingMessages.get(2), is(message1));
    }

    @Test
    public void sortedBasedOnSequenceNumber() {
        AllOutboundVoiceMessages dao = new AllOutboundVoiceMessages(db);

        DateTime now = DateUtil.now();
        OutboundVoiceMessage message1 = buildMessage(now.minusDays(1).toDate(), 3);
        OutboundVoiceMessage message2 = buildMessage(now.toDate(), 1);
        OutboundVoiceMessage message3 = buildMessage(now.plusDays(1).toDate(), 2);

        messages.add(message1);
        messages.add(message2);
        messages.add(message3);

        when(db.queryView(any(ViewQuery.class), any(Class.class))).thenReturn(messages);

        List<OutboundVoiceMessage> pendingMessages = dao.getMessages(EXTERNAL_ID, OutboundVoiceMessageStatus.PENDING, SortKey.SequenceNumber);
        assertThat(pendingMessages.get(0), is(message2));
        assertThat(pendingMessages.get(1), is(message3));
        assertThat(pendingMessages.get(2), is(message1));

    }

    private OutboundVoiceMessage buildMessage(Date creationTime, long sequenceNumber) {
        return new OutboundVoiceMessageBuilder().withDefaults().withCreationTime(creationTime).withExternalId(EXTERNAL_ID)
                .withSequenceNumber(sequenceNumber).build();
    }
}


text:
package herddb.server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

/**
 * SimpleServer boot test
 *
 * @author enrico.olivelli
 */
public class UseSystemPropertiesFromCommandLineTest {

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void test() throws Exception {
        try {
            File tmpConfFile = folder.newFile("test.server.properties");

            try (InputStream in = UseSystemPropertiesFromCommandLineTest.class.getResourceAsStream("/conf/test.server.properties")) {
                Properties props = new Properties();
                props.load(in);
                props.put(ServerConfiguration.PROPERTY_BASEDIR, folder.newFolder().getAbsolutePath());
                try (FileOutputStream oo = new FileOutputStream(tmpConfFile)) {
                    props.store(oo, "");
                }
            }
            Thread runner = new Thread(() -> {
                ServerMain.main(tmpConfFile.getAbsolutePath(), "-D" + ServerConfiguration.PROPERTY_NODEID + "=my-node-id");
            });
            runner.start();
            while (ServerMain.getRunningInstance() == null
                || !ServerMain.getRunningInstance().isStarted()) {
                Thread.sleep(1000);
                System.out.println("waiting for boot");
            }

            ServerMain.getRunningInstance().getServer().waitForStandaloneBoot();
            assertEquals("my-node-id", ServerMain.getRunningInstance().getServer().getNodeId());

            ServerMain.getRunningInstance().close();
        } finally {
            if (ServerMain.getRunningInstance() != null) {
                ServerMain.getRunningInstance().close();
            }
        }
    }
}


text:
.. Copyright (c) 2007-2019 UShareSoft, All rights reserved

.. _stack-installation-rootuser:

rootUser
========

Within an :ref:`stack-installation`, the ``rootUser`` sub-section describes information for the root user to be created as part of the machine image build. If no root user information is provided, when an instance is provisioned from the machine image, the root user password is prompted.

The definition of a ``rootUser`` section when using YAML is:

.. code-block:: yaml

	---
	rootUser:
	  # the root user definition goes here.

If you are using JSON:

.. code-block:: javascript

	"rootUser": {
	    ...the root user definition goes here.
	}

The valid keys to use within a rootUser are:

* disablePasswordLogin (optional): a boolean to determine whether to disable the ability for the root user to login into a running instance using the root password.
* password (optional): a string providing the root user password. A blank password "" is valid.
* setPassword (mandatory): a boolean to determine whether to preset a password during the build or prompt the user to add a password during first boot of the instance.
* sshKeys (optional): an array of objects providing one or more public ssh keys for the root user. For more information, refer to the :ref:`stack-installation-sshkeys` sub-section.

Sub-sections
------------

The root user sub-sections are:

.. toctree::
   :titlesonly:

   stack-installation-sshkeys

Examples
--------

Basic Example
~~~~~~~~~~~~~

The following example describes the basic root user information.

If you are using YAML:

.. code-block:: yaml

	---
	rootUser:
	  password: welcome-not-a-good-password

If you are using JSON:

.. code-block:: json

	{
	  "rootUser": {
	    "password": "welcome-not-a-good-password"
	  }
	}

Disabling Password Login
~~~~~~~~~~~~~~~~~~~~~~~~

You can easily disable root password login as a security measure by doing the following:

If you are using YAML:

.. code-block:: yaml

	---
	rootUser:
	  password: welcome-not-a-good-password
	  disablePasswordLogin: true

If you are using JSON:

.. code-block:: json

	{
	  "rootUser": {
	    "password": "welcome-not-a-good-password",
	    "disablePasswordLogin": true
	  }
	}


text:
#pragma once
#include <aws/lexv2-models/LexModelsV2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/lexv2-models/model/ImportSummary.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace LexModelsV2
{
namespace Model
{
  class AWS_LEXMODELSV2_API ListImportsResult
  {
  public:
    ListImportsResult();
    ListImportsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ListImportsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
The unique identifier assigned by Amazon Lex to the bot.

     */
    inline const Aws::String& GetBotId() const{ return m_botId; }

    /**
     *
The unique identifier assigned by Amazon Lex to the bot.

     */
    inline void SetBotId(const Aws::String& value) { m_botId = value; }

    /**
     *
The unique identifier assigned by Amazon Lex to the bot.

     */
    inline void SetBotId(Aws::String&& value) { m_botId = std::move(value); }

    /**
     *
The unique identifier assigned by Amazon Lex to the bot.

     */
    inline void SetBotId(const char* value) { m_botId.assign(value); }

    /**
     *
The unique identifier assigned by Amazon Lex to the bot.

     */
    inline ListImportsResult& WithBotId(const Aws::String& value) { SetBotId(value); return *this;}

    /**
     *
The unique identifier assigned by Amazon Lex to the bot.

     */
    inline ListImportsResult& WithBotId(Aws::String&& value) { SetBotId(std::move(value)); return *this;}

    /**
     *
The unique identifier assigned by Amazon Lex to the bot.

     */
    inline ListImportsResult& WithBotId(const char* value) { SetBotId(value); return *this;}

    /**
     *
The version of the bot that was imported. It will always be
     * DRAFT.

     */
    inline const Aws::String& GetBotVersion() const{ return m_botVersion; }

    /**
     *
The version of the bot that was imported. It will always be
     * DRAFT.

     */
    inline void SetBotVersion(const Aws::String& value) { m_botVersion = value; }

    /**
     *
The version of the bot that was imported. It will always be
     * DRAFT.

     */
    inline void SetBotVersion(Aws::String&& value) { m_botVersion = std::move(value); }

    /**
     *
The version of the bot that was imported. It will always be
     * DRAFT.

     */
    inline void SetBotVersion(const char* value) { m_botVersion.assign(value); }

    /**
     *
The version of the bot that was imported. It will always be
     * DRAFT.

     */
    inline ListImportsResult& WithBotVersion(const Aws::String& value) { SetBotVersion(value); return *this;}

    /**
     *
The version of the bot that was imported. It will always be
     * DRAFT.

     */
    inline ListImportsResult& WithBotVersion(Aws::String&& value) { SetBotVersion(std::move(value)); return *this;}

    /**
     *
The version of the bot that was imported. It will always be
     * DRAFT.

     */
    inline ListImportsResult& WithBotVersion(const char* value) { SetBotVersion(value); return *this;}

    /**
     *
Summary information for the imports that meet the filter criteria specified
     * in the request. The length of the list is specified in the
     * maxResults parameter. If there are more imports available, the
     * nextToken field contains a token to get the next page of
     * results.

     */
    inline const Aws::Vector<ImportSummary>& GetImportSummaries() const{ return m_importSummaries; }

    /**
     *
Summary information for the imports that meet the filter criteria specified
     * in the request. The length of the list is specified in the
     * maxResults parameter. If there are more imports available, the
     * nextToken field contains a token to get the next page of
     * results.

     */
    inline void SetImportSummaries(const Aws::Vector<ImportSummary>& value) { m_importSummaries = value; }

    /**
     *
Summary information for the imports that meet the filter criteria specified
     * in the request. The length of the list is specified in the
     * maxResults parameter. If there are more imports available, the
     * nextToken field contains a token to get the next page of
     * results.

     */
    inline void SetImportSummaries(Aws::Vector<ImportSummary>&& value) { m_importSummaries = std::move(value); }

    /**
     *
Summary information for the imports that meet the filter criteria specified
     * in the request. The length of the list is specified in the
     * maxResults parameter. If there are more imports available, the
     * nextToken field contains a token to get the next page of
     * results.

     */
    inline ListImportsResult& WithImportSummaries(const Aws::Vector<ImportSummary>& value) { SetImportSummaries(value); return *this;}

    /**
     *
Summary information for the imports that meet the filter criteria specified
     * in the request. The length of the list is specified in the
     * maxResults parameter. If there are more imports available, the
     * nextToken field contains a token to get the next page of
     * results.

     */
    inline ListImportsResult& WithImportSummaries(Aws::Vector<ImportSummary>&& value) { SetImportSummaries(std::move(value)); return *this;}

    /**
     *
Summary information for the imports that meet the filter criteria specified
     * in the request. The length of the list is specified in the
     * maxResults parameter. If there are more imports available, the
     * nextToken field contains a token to get the next page of
     * results.

     */
    inline ListImportsResult& AddImportSummaries(const ImportSummary& value) { m_importSummaries.push_back(value); return *this; }

    /**
     *
Summary information for the imports that meet the filter criteria specified
     * in the request. The length of the list is specified in the
     * maxResults parameter. If there are more imports available, the
     * nextToken field contains a token to get the next page of
     * results.

     */
    inline ListImportsResult& AddImportSummaries(ImportSummary&& value) { m_importSummaries.push_back(std::move(value)); return *this; }

    /**
     *
A token that indicates whether there are more results to return in a response
     * to the ListImports operation. If the nextToken field
     * is present, you send the contents as the nextToken parameter of a
     * ListImports operation request to get the next page of results.

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
A token that indicates whether there are more results to return in a response
     * to the ListImports operation. If the nextToken field
     * is present, you send the contents as the nextToken parameter of a
     * ListImports operation request to get the next page of results.

     */
    inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }

    /**
     *
A token that indicates whether there are more results to return in a response
     * to the ListImports operation. If the nextToken field
     * is present, you send the contents as the nextToken parameter of a
     * ListImports operation request to get the next page of results.

     */
    inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }

    /**
     *
A token that indicates whether there are more results to return in a response
     * to the ListImports operation. If the nextToken field
     * is present, you send the contents as the nextToken parameter of a
     * ListImports operation request to get the next page of results.

     */
    inline void SetNextToken(const char* value) { m_nextToken.assign(value); }

    /**
     *
A token that indicates whether there are more results to return in a response
     * to the ListImports operation. If the nextToken field
     * is present, you send the contents as the nextToken parameter of a
     * ListImports operation request to get the next page of results.

     */
    inline ListImportsResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
A token that indicates whether there are more results to return in a response
     * to the ListImports operation. If the nextToken field
     * is present, you send the contents as the nextToken parameter of a
     * ListImports operation request to get the next page of results.

     */
    inline ListImportsResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
A token that indicates whether there are more results to return in a response
     * to the ListImports operation. If the nextToken field
     * is present, you send the contents as the nextToken parameter of a
     * ListImports operation request to get the next page of results.

     */
    inline ListImportsResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}

    /**
     *
The locale specified in the request.

     */
    inline const Aws::String& GetLocaleId() const{ return m_localeId; }

    /**
     *
The locale specified in the request.

     */
    inline void SetLocaleId(const Aws::String& value) { m_localeId = value; }

    /**
     *
The locale specified in the request.

     */
    inline void SetLocaleId(Aws::String&& value) { m_localeId = std::move(value); }

    /**
     *
The locale specified in the request.

     */
    inline void SetLocaleId(const char* value) { m_localeId.assign(value); }

    /**
     *
The locale specified in the request.

     */
    inline ListImportsResult& WithLocaleId(const Aws::String& value) { SetLocaleId(value); return *this;}

    /**
     *
The locale specified in the request.

     */
    inline ListImportsResult& WithLocaleId(Aws::String&& value) { SetLocaleId(std::move(value)); return *this;}

    /**
     *
The locale specified in the request.

     */
    inline ListImportsResult& WithLocaleId(const char* value) { SetLocaleId(value); return *this;}

  private:

    Aws::String m_botId;

    Aws::String m_botVersion;

    Aws::Vector<ImportSummary> m_importSummaries;

    Aws::String m_nextToken;

    Aws::String m_localeId;
  };

} // namespace Model
} // namespace LexModelsV2
} // namespace Aws


text:
"""pycountry"""

import os.path

import pycountry.db

LOCALES_DIR = os.path.join(os.path.dirname(__file__), 'locales')
DATABASE_DIR = os.path.join(os.path.dirname(__file__), 'databases')

class Countries(pycountry.db.Database):
    """Provides access to an ISO 3166 database (Countries)."""

    field_map = dict(alpha_2_code='alpha2',
                     alpha_3_code='alpha3',
                     numeric_code='numeric',
                     name='name',
                     official_name='official_name',
                     common_name='common_name')
    data_class_name = 'Country'
    xml_tag = 'iso_3166_entry'

class Scripts(pycountry.db.Database):
    """Providess access to an ISO 15924 database (Scripts)."""

    field_map = dict(alpha_4_code='alpha4',
                     numeric_code='numeric',
                     name='name')
    data_class_name = 'Script'
    xml_tag = 'iso_15924_entry'

class Currencies(pycountry.db.Database):
    """Providess access to an ISO 4217 database (Currencies)."""

    field_map = dict(letter_code='letter',
                     numeric_code='numeric',
                     currency_name='name')
    data_class_name = 'Currency'
    xml_tag = 'iso_4217_entry'

class Languages(pycountry.db.Database):
    """Providess access to an ISO 639-1/2 database (Languages)."""

    field_map = dict(iso_639_2B_code='bibliographic',
                     iso_639_2T_code='terminology',
                     iso_639_1_code='alpha2',
                     name='name')
    data_class_name = 'Language'
    xml_tag = 'iso_639_entry'

class Subdivision(pycountry.db.Data):

    parent_code = None

    def __init__(self, element, **kw):
        super(Subdivision, self).__init__(element, **kw)
        self.type = element.parentNode.attributes.get('type').value
        self.country_code = self.code.split('-')[0]
        if self.parent_code is not None:
            self.parent_code = '%s-%s' % (self.country_code, self.parent_code)

    @property
    def country(self):
        return countries.get(alpha2=self.country_code)

    @property
    def parent(self):
        return subdivisions.get(code=self.parent_code)

class Subdivisions(pycountry.db.Database):

    # Note: subdivisions can be hierarchical to other subdivisions. The
    # parent_code attribute is related to other subdivisons, *not*
    # the country!

    xml_tag = 'iso_3166_2_entry'
    data_class_base = Subdivision
    data_class_name = 'Subdivision'
    field_map = dict(code='code',
                     name='name',
                     parent='parent_code')
    no_index = ['name', 'parent_code']

    def __init__(self, *args, **kw):
        super(Subdivisions, self).__init__(*args, **kw)

        # Add index for the country code.
        self.indices['country_code'] = {}
        for subdivision in self:
            divs = self.indices['country_code'].setdefault(
                subdivision.country_code, set())
            divs.add(subdivision)

countries = Countries(os.path.join(DATABASE_DIR, 'iso3166.xml'))
scripts = Scripts(os.path.join(DATABASE_DIR, 'iso15924.xml'))
currencies = Currencies(os.path.join(DATABASE_DIR, 'iso4217.xml'))
languages = Languages(os.path.join(DATABASE_DIR, 'iso639.xml'))
subdivisions = Subdivisions(os.path.join(DATABASE_DIR, 'iso3166_2.xml'))


text:
package org.ovirt.engine.core.compat;

import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateTime extends Date {
    private static final String[] dayNames = new DateFormatSymbols().getWeekdays();

    public DateTime() {
        this(getMinValue());
    }

    public DateTime(Date argvalue) {
        super(argvalue.getTime());
    }

    public DateTime(long millis) {
        super(millis);
    }

    /**
     * This method resets the datetime object to 00:00:00.000 on the same date
     */
    public DateTime resetToMidnight() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(this);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return new DateTime(cal.getTime());
    }

    public DayOfWeek getDayOfWeek() {
        return DayOfWeek.forValue(this.getDay());
    }

    public String toString(DateFormat dateFormat) {
        return dateFormat.format(this);
    }

    public Date addSeconds(int i) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(this);
        cal.add(Calendar.SECOND, i);
        return cal.getTime();
    }

    public DateTime addDays(int i) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(this);
        cal.add(Calendar.DATE, i);
        return new DateTime(cal.getTime());
    }

    public TimeSpan subtract(Date date) {
        long span = this.getTime() - date.getTime();
        return new TimeSpan(span);
    }

    /**
     * The Min Date in java
     *
     * @return - a date representing - Thu Jan 01 00:00:00 IST 1970
     */
    public static Date getMinValue() {
        GregorianCalendar javaEpochTime = new GregorianCalendar();
        javaEpochTime.clear();
        return javaEpochTime.getTime();
    }

    public static DateTime getNow() {
        return new DateTime(System.currentTimeMillis());
    }

    public Date addMinutes(int i) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(this);
        cal.add(Calendar.MINUTE, i);
        return new DateTime(cal.getTime());
    }

    public static String getDayOfTheWeekAsString(int dayOfTheWeek) {
        return dayNames[dayOfTheWeek];
    }
}


text:
package com.travelport.schema.air_v29_0;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for typeUnitOfMeasure complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="typeUnitOfMeasure">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <attribute name="Value" type="{http://www.w3.org/2001/XMLSchema}float" />
 *       <attribute name="Unit" type="{http://www.w3.org/2001/XMLSchema}string" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "typeUnitOfMeasure")
@XmlSeeAlso({
    Dimension.class
})
public class TypeUnitOfMeasure {

    @XmlAttribute(name = "Value")
    protected Float value;
    @XmlAttribute(name = "Unit")
    protected String unit;

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link Float }
     *
     */
    public Float getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link Float }
     *
     */
    public void setValue(Float value) {
        this.value = value;
    }

    /**
     * Gets the value of the unit property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUnit() {
        return unit;
    }

    /**
     * Sets the value of the unit property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUnit(String value) {
        this.unit = value;
    }

}


text:
FROM python:2
LABEL maintainer="taichunmin@gmail.com"

WORKDIR /root

RUN pip install --no-cache-dir \
    pipreqs \
    aliyun-python-sdk-ecs \
    aliyun-python-sdk-cdn \
    aliyun-python-sdk-rds \
    aliyun-python-sdk-cms \
    aliyun-python-sdk-mts \
    aliyun-python-sdk-vod \
    aliyun-python-sdk-live \
    aliyun-python-sdk-push \
    aliyun-python-sdk-iot \
    aliyun-python-sdk-domain \
    aliyun-python-sdk-httpdns \
    aliyun-python-sdk-green \
    aliyun-python-sdk-emr \
    aliyun-python-sdk-kms \
    aliyun-python-sdk-slb \
    aliyun-python-sdk-cloudphoto \
    aliyun-python-sdk-sas-api \
    aliyun-python-sdk-ons \
    aliyun-python-sdk-vpc \
    aliyun-python-sdk-ram \
    aliyun-python-sdk-sts

CMD ["tail", "-f", "/etc/issue"]


text:
#ifndef INCLUDE_S3RESTFUL_SERVICE_H_
#define INCLUDE_S3RESTFUL_SERVICE_H_

#include "gpcommon.h"
#include "restful_service.h"
#include "s3common_headers.h"
#include "s3exception.h"
#include "s3http_headers.h"
#include "s3log.h"
#include "s3macros.h"
#include "s3params.h"

class S3RESTfulService : public RESTfulService {
   public:
    S3RESTfulService();
    S3RESTfulService(const string& proxy);
    S3RESTfulService(const S3Params& params);
    virtual ~S3RESTfulService();

    ResponseCode head(const string& url, HTTPHeaders& headers);

    Response get(const string& url, HTTPHeaders& headers);

    Response put(const string& url, HTTPHeaders& headers, const S3VectorUInt8& data);

    Response post(const string& url, HTTPHeaders& headers, const vector<uint8_t>& data);

    Response deleteRequest(const string& url, HTTPHeaders& headers);

   private:
    uint64_t lowSpeedLimit;
    uint64_t lowSpeedTime;

    string proxy;

    bool debugCurl;
    bool verifyCert;

    uint64_t chunkBufferSize;
    S3MemoryContext s3MemContext;

    void performCurl(CURL* curl, Response& response);
};

class S3MessageParser {
   public:
    S3MessageParser(const Response& resp);

    ~S3MessageParser();

    const string& getMessage() const {
        return message;
    }
    const string& getCode() const {
        return code;
    }
    string parseS3Tag(const string& tag);

   private:
    xmlParserCtxtPtr xmlptr;
    string message;
    string code;
};

#endif /* INCLUDE_S3RESTFUL_SERVICE_H_ */


text:
// /Copyright (c) Gurmit Teotia. Please see the LICENSE file in the project root folder for license information.

using System;

namespace Guflow.Decider
{
    /// <summary>
    /// Fluent API to schedule the Lambda function in workflow.
    /// </summary>
    public interface IFluentLambdaItem : IFluentWorkflowItem<IFluentLambdaItem>
    {
        /// <summary>
        /// Provide the input for lamdba lambda function. Complex input type are serialized to JSON while for primitive types their string represenation is used.
        /// </summary>
        /// <param name="input">Functor, which will return input for lambda function.</param>
        /// <returns></returns>
        IFluentLambdaItem WithInput(Func<ILambdaItem, object> input);

        /// <summary>
        /// Configure the timeout for lambda function. If lambda function does not finish within this period then SWF will raise <see cref="LambdaTimedoutEvent"/>.
        /// </summary>
        /// <param name="timout">Functor, which will return the timeout for lambda function</param>
        /// <returns></returns>
        IFluentLambdaItem WithTimeout(Func<ILambdaItem, TimeSpan?> timout);

        /// <summary>
        /// Provide the workflow action for when lambda function is successfully completed. By default Guflow will schedule its children.
        /// </summary>
        /// <param name="completedAction">Functor, which will return the workflow action.</param>
        /// <returns></returns>
        IFluentLambdaItem OnCompletion(Func<LambdaCompletedEvent, WorkflowAction> completedAction);

        /// <summary>
        /// Provide the workflow action for when lambda function is failed.  By default Guflow will fail the workflow on <see cref="LambdaFailedEvent"/> event.
        /// </summary>
        /// <param name="failedAction"></param>
        /// <returns></returns>
        IFluentLambdaItem OnFailure(Func<LambdaFailedEvent, WorkflowAction> failedAction);

        /// <summary>
        /// Provide the workflow action for when lambda function's execution is timedout. By default Guflow will fail the workflow on <see cref="LambdaTimedoutEvent"/> event.
        /// </summary>
        /// <param name="timedoutAction"></param>
        /// <returns></returns>
        IFluentLambdaItem OnTimedout(Func<LambdaTimedoutEvent, WorkflowAction> timedoutAction);

        /// <summary>
        /// Provide the workflow action for lamdba scheduling failed event. By default
        /// </summary>
        /// <param name="schedulingFailedAction"></param>
        IFluentLambdaItem OnSchedulingFailed(Func<LambdaSchedulingFailedEvent, WorkflowAction> schedulingFailedAction);

        /// <summary>
        /// Provide the workflow action for when SWF is failed to start the execution of the lamdba function. By default workflow is failed.
        /// </summary>
        /// <param name="startFailedAction"></param>
        /// <returns></returns>
        IFluentLambdaItem OnStartFailed(Func<LambdaStartFailedEvent, WorkflowAction> startFailedAction);

        /// <summary>
        /// Schedule the lambda function only when given expression is evaluated to true.
        /// </summary>
        /// <param name="true">Provide functor to evaluate when scheduling the lambda.</param>
        /// <returns></returns>
        IFluentLambdaItem When(Func<ILambdaItem, bool> @true);

        /// <summary>
        /// Schedule the lambda function only when given expression is evaluated to true.
        /// You also have the option to override triggering workflow action. Refer to Deflow algorithm for more details.
        /// </summary>
        /// <param name="true">Provide functor to evaluate when scheduling the lambda.</param>
        /// <param name="onFalseAction">Provide WorkflowAction when scheduling condition is evaluated to false. By default it will try to schedule the first join item if this is a non startup item.</param>
        /// <returns></returns>
        IFluentLambdaItem When(Func<ILambdaItem, bool> @true, Func<ILambdaItem,WorkflowAction> onFalseAction);
    }
}


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

<title>wdframework.action</title>
<meta name="date" content="2015-06-02">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package wdframework.action

Class Summary

Class
Description

Action

Action Super Class

SearchAction

Sample google search action class

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
<?xml version="1.0" encoding="utf-8"?><!--
   Copyright 2015 sourcestream GmbH

   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.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingBottom="30dp">

    <ImageView
        android:id="@+id/posterPath"
        android:layout_width="fill_parent"
        android:layout_height="330dp"
        android:scaleType="fitXY"
        android:src="@drawable/placeholder_default" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:gravity="top|center"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:gravity="center"
            android:maxLines="2"
            android:textColor="@color/movieListRowTitle"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/releaseDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/movieListRowSub"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/character"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:gravity="center"
            android:maxLines="1"
            android:textColor="@color/movieListRowSub"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/department"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:gravity="center"
            android:maxLines="1"
            android:textColor="@color/movieListRowSub"
            android:textSize="18sp" />
    </LinearLayout>

</LinearLayout>


text:
emcalculator
============

quick stab at a calculator

yeah yeah yeah...i'll move the stuff out of the view later....

This calculator was written for 3 reasons:

* we needed a ***basic*** calculator that was skimable
* it needed to update on *operator*. e.g.	User taps `5 + 5 + 2`. Obviously on `=` the display will ready 12. However on pressing the 2nd `+` we needed this to calculate and update the display so it would read `10` before the user presses the next digit/decimal
* there were 2 keys hard to find in an open source solution

	- **⌫** backspace
	- **+/-** toggle

and there you go.


text:
using System;
using System.Collections.Generic;
using System.IO;
using DiscUtils;
using DiscUtils.BootConfig;
using DiscUtils.Common;
using DiscUtils.Ntfs;
using DiscUtils.Partitions;
using DiscUtils.Registry;

namespace OSClone
{
    class Program : ProgramBase
    {
        // Shared to avoid continual re-allocation of a large buffer
        private static byte[] s_copyBuffer = new byte[10 * 1024 * 1024];

        private static string[] s_excludedFiles = new string[]
        {
            @"\PAGEFILE.SYS", @"\HIBERFIL.SYS", @"\SYSTEM VOLUME INFORMATION"
        };

        private CommandLineParameter _sourceFile;
        private CommandLineParameter _destFile;
        private CommandLineSwitch _labelSwitch;

        private Dictionary<long, string> _uniqueFiles = new Dictionary<long,string>();

        static void Main(string[] args)
        {
            Program program = new Program();
            program.Run(args);
        }

        protected override StandardSwitches DefineCommandLine(CommandLineParser parser)
        {
            _sourceFile = FileOrUriParameter("in_file", "The disk image containing the Operating System image to be cloned.", false);
            _destFile = FileOrUriParameter("out_file", "The path to the output disk image.", false);
            _labelSwitch = new CommandLineSwitch("l", "label", "name", "The volume label for the NTFS file system created.");

            parser.AddParameter(_sourceFile);
            parser.AddParameter(_destFile);
            parser.AddSwitch(_labelSwitch);

            return StandardSwitches.OutputFormatAndAdapterType | StandardSwitches.UserAndPassword | StandardSwitches.DiskSize;
        }

        protected override void DoRun()
        {
            if (DiskSize <= 0)
            {
                DisplayHelp();
                return;
            }

            using (VirtualDisk sourceDisk = VirtualDisk.OpenDisk(_sourceFile.Value, FileAccess.Read, UserName, Password))
            using (VirtualDisk destDisk = VirtualDisk.CreateDisk(OutputDiskType, OutputDiskVariant, _destFile.Value, DiskParameters, UserName, Password))
            {
                if (destDisk is DiscUtils.Vhd.Disk)
                {
                    ((DiscUtils.Vhd.Disk)destDisk).AutoCommitFooter = false;
                }

                // Copy the MBR from the source disk, and invent a new signature for this new disk
                destDisk.SetMasterBootRecord(sourceDisk.GetMasterBootRecord());
                destDisk.Signature = new Random().Next();

                SparseStream sourcePartStream = SparseStream.FromStream(sourceDisk.Partitions[0].Open(), Ownership.None);
                NtfsFileSystem sourceNtfs = new NtfsFileSystem(sourcePartStream);

                // Copy the OS boot code into memory, so we can apply it when formatting the new disk
                byte[] bootCode;
                using (Stream bootStream = sourceNtfs.OpenFile("$Boot", FileMode.Open, FileAccess.Read))
                {
                    bootCode = new byte[bootStream.Length];
                    int totalRead = 0;
                    while (totalRead < bootCode.Length)
                    {
                        totalRead += bootStream.Read(bootCode, totalRead, bootCode.Length - totalRead);
                    }
                }

                // Partition the new disk with a single NTFS partition
                BiosPartitionTable.Initialize(destDisk, WellKnownPartitionType.WindowsNtfs);
                VolumeManager volMgr = new VolumeManager(destDisk);

                string label = _labelSwitch.IsPresent ? _labelSwitch.Value : sourceNtfs.VolumeLabel;
                using (NtfsFileSystem destNtfs = NtfsFileSystem.Format(volMgr.GetLogicalVolumes()[0], label, bootCode))
                {
                    destNtfs.SetSecurity(@"\", sourceNtfs.GetSecurity(@"\"));
                    destNtfs.NtfsOptions.ShortNameCreation = ShortFileNameOption.Disabled;

                    sourceNtfs.NtfsOptions.HideHiddenFiles = false;
                    sourceNtfs.NtfsOptions.HideSystemFiles = false;
                    CopyFiles(sourceNtfs, destNtfs, @"\", true);

                    if (destNtfs.FileExists(@"\boot\BCD"))
                    {
                        // Force all boot entries in the BCD to point to the newly created NTFS partition - does _not_ cope with
                        // complex multi-volume / multi-boot scenarios at all.
                        using (Stream bcdStream = destNtfs.OpenFile(@"\boot\BCD", FileMode.Open, FileAccess.ReadWrite))
                        {
                            using (RegistryHive hive = new RegistryHive(bcdStream))
                            {
                                Store store = new Store(hive.Root);
                                foreach (var obj in store.Objects)
                                {
                                    foreach (var elem in obj.Elements)
                                    {
                                        if (elem.Format == DiscUtils.BootConfig.ElementFormat.Device)
                                        {
                                            elem.Value = DiscUtils.BootConfig.ElementValue.ForDevice(elem.Value.ParentObject, volMgr.GetPhysicalVolumes()[0]);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private void CopyFiles(NtfsFileSystem sourceNtfs, NtfsFileSystem destNtfs, string path, bool subs)
        {
            if (subs)
            {
                foreach (var dir in sourceNtfs.GetDirectories(path))
                {
                    if (!IsExcluded(dir))
                    {
                        int hardLinksRemaining = sourceNtfs.GetHardLinkCount(dir) - 1;
                        bool newDir = false;

                        long sourceFileId = sourceNtfs.GetFileId(dir);
                        string refPath;
                        if (_uniqueFiles.TryGetValue(sourceFileId, out refPath))
                        {
                            // If this is another name for a known dir, recreate the hard link
                            destNtfs.CreateHardLink(refPath, dir);
                        }
                        else
                        {
                            destNtfs.CreateDirectory(dir);
                            newDir = true;

                            FileAttributes fileAttrs = sourceNtfs.GetAttributes(dir);
                            if ((fileAttrs & FileAttributes.ReparsePoint) != 0)
                            {
                                destNtfs.SetReparsePoint(dir, sourceNtfs.GetReparsePoint(dir));
                            }

                            destNtfs.SetAttributes(dir, fileAttrs);

                            destNtfs.SetSecurity(dir, sourceNtfs.GetSecurity(dir));
                        }

                        // File may have a short name
                        string shortName = sourceNtfs.GetShortName(dir);
                        if (!string.IsNullOrEmpty(shortName) && shortName != dir)
                        {
                            destNtfs.SetShortName(dir, shortName);
                            --hardLinksRemaining;
                        }

                        if (newDir)
                        {
                            if (hardLinksRemaining > 0)
                            {
                                _uniqueFiles[sourceFileId] = dir;
                            }
                            CopyFiles(sourceNtfs, destNtfs, dir, subs);
                        }

                        // Set standard information last (includes modification timestamps)
                        destNtfs.SetFileStandardInformation(dir, sourceNtfs.GetFileStandardInformation(dir));
                    }
                }
            }

            foreach (var file in sourceNtfs.GetFiles(path))
            {
                Console.WriteLine(file);

                int hardLinksRemaining = sourceNtfs.GetHardLinkCount(file) - 1;

                long sourceFileId = sourceNtfs.GetFileId(file);

                string refPath;
                if (_uniqueFiles.TryGetValue(sourceFileId, out refPath))
                {
                    // If this is another name for a known file, recreate the hard link
                    destNtfs.CreateHardLink(refPath, file);
                }
                else
                {
                    CopyFile(sourceNtfs, destNtfs, file);

                    if (hardLinksRemaining > 0)
                    {
                        _uniqueFiles[sourceFileId] = file;
                    }
                }

                // File may have a short name
                string shortName = sourceNtfs.GetShortName(file);
                if (!string.IsNullOrEmpty(shortName) && shortName != file)
                {
                    destNtfs.SetShortName(file, shortName);
                }
            }
        }

        private void CopyFile(NtfsFileSystem sourceNtfs, NtfsFileSystem destNtfs, string path)
        {
            if (IsExcluded(path))
            {
                return;
            }

            using (Stream s = sourceNtfs.OpenFile(path, FileMode.Open, FileAccess.Read))
            using (Stream d = destNtfs.OpenFile(path, FileMode.Create, FileAccess.ReadWrite))
            {
                d.SetLength(s.Length);
                int numRead = s.Read(s_copyBuffer, 0, s_copyBuffer.Length);
                while (numRead > 0)
                {
                    d.Write(s_copyBuffer, 0, numRead);
                    numRead = s.Read(s_copyBuffer, 0, s_copyBuffer.Length);
                }
            }

            destNtfs.SetSecurity(path, sourceNtfs.GetSecurity(path));
            destNtfs.SetFileStandardInformation(path, sourceNtfs.GetFileStandardInformation(path));
        }

        private static bool IsExcluded(string path)
        {
            string pathUpper = path.ToUpperInvariant();

            for (int i = 0; i < s_excludedFiles.Length; ++i)
            {
                if (pathUpper == s_excludedFiles[i])
                {
                    return true;
                }
            }

            return false;
        }
    }
}


text:
package com.xinfan.blueblue.activity.send;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.xinfan.blueblue.activity.R;
import com.xinfan.blueblue.activity.base.BaseActivity;

public class AreaSelectActivity extends BaseActivity implements OnClickListener {

	public WriteMessageAreaAdapter areaAdapter;
	public View time_select_layout;

	public ArrayList<AreaListVo> areaList = new ArrayList<AreaListVo>();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.write_message_time_popview_item);

		ListView listview = (ListView) findViewById(R.id.time_listView_select);

		setTitle();

		AreaListVo one = new AreaListVo("1", "附近");
		AreaListVo two = new AreaListVo("2", "本市");
		areaList.add(one);
		areaList.add(two);

		areaAdapter = new WriteMessageAreaAdapter(this, areaList);
		listview.setAdapter(areaAdapter);
		areaAdapter.notifyDataSetChanged();

		listview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				AreaListVo select = areaList.get(arg2);
				WriteMessageActivity.instance.updateAreaSelect(select);
				AreaSelectActivity.this.finish();
			}

		});
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		finish();
		return true;
	}

	public void setTitle(){
		TextView view = (TextView)this.findViewById(R.id.time_listview_title);
		view.setText("请选择消息的有效范围");
	}

	@Override
	public void onClick(View arg0) {

	}

}


text:
package com.cloudcontrolled.api.client.body;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import javax.ws.rs.core.MultivaluedMap;

/**
 * <p>
 * BodyMultivaluedMap class.
 * </p>
 *
 * @author Denis Neuling (denisneuling@gmail.com)
 *
 */
public class BodyMultivaluedMap extends HashMap<String, List<String>> implements MultivaluedMap<String, String> {
	private static final long serialVersionUID = -4545725304226984837L;

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.ws.rs.core.MultivaluedMap#putSingle(java.lang.Object,
	 * java.lang.Object)
	 */
	/** {@inheritDoc} */
	@Override
	public void putSingle(String key, String value) {
		this.add(key, value);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.ws.rs.core.MultivaluedMap#add(java.lang.Object,
	 * java.lang.Object)
	 */
	/** {@inheritDoc} */
	@Override
	public void add(String key, String value) {
		List<String> values = this.get(key);
		if (values == null) {
			this.put(key, new LinkedList<String>());
		}
		this.get(key).add(value);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.ws.rs.core.MultivaluedMap#getFirst(java.lang.Object)
	 */
	/** {@inheritDoc} */
	@Override
	public String getFirst(String key) {
		return this.get(key).iterator().next();
	}

}


text:
@interface RXARCObject : NSObject
- (void)test;
@end


text:
.PHONY: all
all: cjs esm mjs S types

.PHONY: cjs esm types
cjs esm types: %: ./tsconfig/tsconfig.%.json ./src/
	@tsc -p ./tsconfig/tsconfig.$@.json

.PHONY: mjs
mjs: esm
	@./misc/make_mjs.sh

.PHONY: S
S: cjs
	@webpack-cli --config misc/webpack.config.js misc/standalone.js --output-filename S.js --display-modules --display-reasons --profile

.PHONY: test
test: mjs cjs S
	@node misc/require_test.njs
	@node --experimental-modules --es-module-specifier-resolution=node misc/import_test.mjs
	@cp dist/S.js misc && node misc/puppetsta.js
	@concurrently --kill-others -s first "http-server -s -p 7262" "node misc/puppetmjs.js"
	@parcel build misc/parcel.html -d misc/parcel -o parcelout.html --public-url "./" && node misc/puppetpcl.js
	@mocha -r ts-node/register test.ts


text:
        Globally Trending Users

{{::x.attributes.name}}

{{::x.attributes.username}}, {{::x.attributes.coolness}}