text:
@interface PNResponse (test)
@property (nonatomic, strong) NSData *content;
@property (nonatomic, assign) NSUInteger size;
- (void)handleJSONDecodeErrorWithCode:(NSUInteger)errorCode;
- (NSString *)decodedResponse;
- (void)getCallbackFunction:(NSString **)callback requestIdentifier:(NSString **)identifier fromData:(NSData *)responseData;
@end

@interface PNResponseTest : XCTestCase

@end

@implementation PNResponseTest

-(void)tearDown {
	[super tearDown];
	[NSThread sleepForTimeInterval:1.0];
}

-(void)testInitWithContent {
	NSData *data = [@"s_r([])" dataUsingEncoding:NSUTF8StringEncoding];
	PNResponse *response = [[PNResponse alloc] initWithContent: data size: 123 code: 1 lastResponseOnConnection: YES];
	XCTAssertTrue( response != nil, @"");
	XCTAssertTrue( response.content == data, @"");
	XCTAssertTrue( response.size == 123, @"");
	XCTAssertTrue( response.statusCode == 1, @"");
	XCTAssertTrue( response.lastResponseOnConnection == YES, @"");
	XCTAssertTrue( [response.callbackMethod isEqualToString: @"s"] == YES, @"");
	XCTAssertTrue( [response.requestIdentifier isEqualToString: @"r"] == YES, @"");
	XCTAssertTrue( [response.response isKindOfClass: [NSArray class]] == YES, @"");
	XCTAssertTrue( [response.response count] == 0, @"");

	data = [@"s_r({})" dataUsingEncoding:NSUTF8StringEncoding];
	response = [[PNResponse alloc] initWithContent: data size: 123 code: 1 lastResponseOnConnection: YES];
	XCTAssertTrue( response != nil, @"");
	XCTAssertTrue( response.content == data, @"");
	XCTAssertTrue( response.size == 123, @"");
	XCTAssertTrue( response.statusCode == 1, @"");
	XCTAssertTrue( response.lastResponseOnConnection == YES, @"");
	XCTAssertTrue( [response.callbackMethod isEqualToString: @"s"] == YES, @"");
	XCTAssertTrue( [response.requestIdentifier isEqualToString: @"r"] == YES, @"");
	XCTAssertTrue( [response.response isKindOfClass: [NSDictionary class]] == YES, @"");
	XCTAssertTrue( [response.response count] == 0, @"");

	data = [@"(najnajna;dn;)" dataUsingEncoding:NSUTF8StringEncoding];
	response = [[PNResponse alloc] initWithContent: data size: 123 code: 1 lastResponseOnConnection: YES];
	XCTAssertTrue( response != nil, @"");
	XCTAssertTrue( response.content == data, @"");
	XCTAssertTrue( response.size == 0, @"");
	XCTAssertTrue( response.statusCode == 1, @"");
	XCTAssertTrue( response.lastResponseOnConnection == YES, @"");
	XCTAssertTrue( [response.callbackMethod isEqualToString: @""] == YES, @"");
	XCTAssertTrue( response.response == 0, @"");
}

-(void)testHandleJSONDecodeErrorWithCode {
	PNResponse *response = [[PNResponse alloc] init];
	response.content = [@"s_r([])" dataUsingEncoding:NSUTF8StringEncoding];
	response.size = 456;
	[response handleJSONDecodeErrorWithCode: 123];
	XCTAssertTrue( response.size == 0, @"");
	XCTAssertTrue( [response.error isKindOfClass: [PNError class]] == YES, @"");
	XCTAssertTrue( response.error.code == 123, @"");
	XCTAssertTrue( [response.callbackMethod isEqualToString: @"s"] == YES, @"");
	XCTAssertTrue( [response.requestIdentifier isEqualToString: @"r"] == YES, @"");
}

-(void)testDecodedResponse {
	PNResponse *response = [[PNResponse alloc] init];
	response.content = [@"  s_r([])  " dataUsingEncoding:NSUTF8StringEncoding];
	XCTAssertTrue( [[response decodedResponse] isEqualToString: @"s_r([])"] == YES, @"");
}

-(void)testGetCallbackFunction {
	PNResponse *response = [[PNResponse alloc] init];
	NSString *callback = nil;
	NSString *identifier = nil;
	[response getCallbackFunction: &callback requestIdentifier: &identifier fromData:[@"s_r([])" dataUsingEncoding:NSUTF8StringEncoding]];
	XCTAssertTrue( [callback isEqualToString: @"s"] == YES, @"");
	XCTAssertTrue( [identifier isEqualToString: @"r"] == YES, @"");
}

@end


text:
using System;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Subscriptions;

namespace Microsoft.WindowsAzure.Subscriptions
{
    public partial class SubscriptionClient : ServiceClient<SubscriptionClient>, ISubscriptionClient
    {
        private Uri _baseUri;

        /// <summary>
        /// The URI used as the base for all Service Management requests.
        /// </summary>
        public Uri BaseUri
        {
            get { return this._baseUri; }
        }

        private CloudCredentials _credentials;

        /// <summary>
        /// Credentials used to authenticate requests.
        /// </summary>
        public CloudCredentials Credentials
        {
            get { return this._credentials; }
        }

        private ISubscriptionOperations _subscriptions;

        public virtual ISubscriptionOperations Subscriptions
        {
            get { return this._subscriptions; }
        }

        /// <summary>
        /// Initializes a new instance of the SubscriptionClient class.
        /// </summary>
        private SubscriptionClient()
            : base()
        {
            this._subscriptions = new SubscriptionOperations(this);
            this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
        }

        /// <summary>
        /// Initializes a new instance of the SubscriptionClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Credentials used to authenticate requests.
        /// </param>
        /// <param name='baseUri'>
        /// The URI used as the base for all Service Management requests.
        /// </param>
        public SubscriptionClient(CloudCredentials credentials, Uri baseUri)
            : this()
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this._credentials = credentials;
            this._baseUri = baseUri;

            this.Credentials.InitializeServiceClient(this);
        }

        /// <summary>
        /// Initializes a new instance of the SubscriptionClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Credentials used to authenticate requests.
        /// </param>
        public SubscriptionClient(CloudCredentials credentials)
            : this()
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this._credentials = credentials;
            this._baseUri = new Uri("https://management.core.windows.net");

            this.Credentials.InitializeServiceClient(this);
        }
    }
}

redpajama_set_name: RedPajamaGithub


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

namespace CSharpUtils.Extensions
{
	/// <summary>
	/// Contains extension methods for the <see cref="ICollection"/> and <see cref="ICollection{T}"/> interfaces.
	/// </summary>
	public static class CollectionExtensions
	{
		/// <summary>
		/// Adds a range of items to a collection.
		/// </summary>
		/// <typeparam name="T">The type of value.</typeparam>
		/// <param name="source">The source.</param>
		/// <param name="values">The values.</param>
		public static void AddRange<T>(this ICollection<T> source, T[] values)
		{
			if (source == null)
			{
				throw new ArgumentNullException(nameof(source), "Value cannot be null");
			}

			if (values == null)
			{
				throw new ArgumentNullException(nameof(values), "Value cannot be null");
			}

			foreach (var value in values)
			{
				source.Add(value);
			}
		}
	}
}


text:
require 'spec_helper'

describe ColumnNameGenerator do

  it 'First char' do
    ColumnNameGenerator::FIRST.should eq 'A'
  end

  it 'Last char' do
    ColumnNameGenerator::LAST.should eq 'Z'
  end

  it 'Next value' do
    ColumnNameGenerator.tap do |g|
      g.next_to(nil).should eq 'A'
      g.next_to('F').should eq 'G'
      g.next_to('DM').should eq 'DN'
      g.next_to('RZ').should eq 'SA'
      g.next_to('ZZ').should eq 'AAA'
      g.next_to('EDT').should eq 'EDU'
    end
  end

end


text:
p {margin-left: 20px;}
table a img
    {
    margin-left: 4px;
    margin-right: 4px;
    }

.alert {
    background-color: #ece8d3;
    color: #d25;
    margin-bottom: 4px;
}

.notice {
    color: #271;
}

.nav {margin-bottom: 4px;}

.nav > li > a:hover {
    color: #fff;
    background-color: transparent;
}

/* rajouté pour avoir link_to_if et link_to_unless qui affichent le lien en grisé */
.dropdown-menu span.disable {
    clear: both;
    color: #888888;
    display: block;
    font-weight: normal;
    line-height: 18px;
    padding: 3px 20px;
    white-space: nowrap;
}

.table-striped tbody tr:nth-child(2n+1) td, .table-striped tbody tr:nth-child(2n+1) th {
    background-color: #EFEFEF;
}

 .table tbody tr:hover td, .table tbody tr:hover th {
    background-color: #CBEECB;
}

.table thead  th {vertical-align: top; }

table thead  th ul {
      margin-left: 0px;
      margin-bottom: 0px;
      list-style: none inside none;
    }

.numeric , td.numeric, th.numeric, input.numeric{
    text-align: right;
  }

.form-horizontal .form-actions, .form-inline .form-actions {
background-color: #dbffdb;
margin-top: 9px;
padding-top: 0px;
border-top: none;
}

.form-horizontal .control-group {
margin-top: 9px;

}

.form-inline label {
  padding-left: 8px;
}

select[class*="span"] {
  background-color: #fff;

}

.row-fluid select[class*="span"] {
display: inline;
}

.form-horizontal .help-block {
 font-style: italic;
        margin-top: 6px;
        margin-left: 6px;
        font-weight: smaller;
        color: gray;

}

select[disabled] {
background-color: #dbffdb;
}

abbr[title] {
border-bottom: none;
color: red;
}

.help-inline {
font-style: italic;
font-size: smaller
}

/* inséré pour avoir la même couleur dans les liens visités des menus */
li.dropdown a:visited {
 color: #333 !important;
}

li.dropdown a:hover {
 color: #FFF !important;
}


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

namespace Gear
{
    /// <summary>
    /// Represents a player.
    /// </summary>
    public class Player
    {
        #region Properties
        public string Name
        {
            get;
            set;
        }

        public bool IsLocalPlayer
        {
            get;
            set;
        }

        public bool IsBot
        {
            get;
            set;
        }

        public Guid ClientID
        {
            get;
            set;
        }

        public PlayerInfo Metadata { get; set; }
        #endregion
    }
}


text:
package glass.phil.monzo.presentation.transactions.details;

import dagger.Binds;
import dagger.Module;
import dagger.Provides;
import glass.phil.monzo.model.transactions.Transaction;

@Module public abstract class DetailsModule {
  @Provides static Transaction transaction(DetailsFragment fragment) {
    return fragment.transaction();
  }

  @Binds abstract DetailsContract.Presenter presenter(DetailsPresenter presenter);
}


text:
<?php

namespace phpDocumentor\Descriptor\Builder\Reflector\Tags;

use phpDocumentor\Descriptor\Builder\Reflector\AssemblerAbstract;
use phpDocumentor\Descriptor\Tag\PropertyDescriptor;
use phpDocumentor\Reflection\DocBlock\Tag\PropertyTag;

class PropertyAssembler extends AssemblerAbstract
{
    /**
     * Creates a new Descriptor from the given Reflector.
     *
     * @param PropertyTag $data
     *
     * @return PropertyDescriptor
     */
    public function create($data)
    {
        $descriptor = new PropertyDescriptor($data->getName());
        $descriptor->setVariableName($data->getVariableName());
        $descriptor->setDescription($data->getDescription());
        $descriptor->setTypes($data->getTypes());

        return $descriptor;
    }
}


text:
require_relative "../../aws_helper"

describe ManageIQ::Providers::Amazon::CloudManager::Provision::Configuration do
  it "#userdata_payload is Base64 encoded" do
    template = FactoryGirl.build(:customization_template, :script => "#cloud-init")
    provision = ManageIQ::Providers::Amazon::CloudManager::Provision.new
    allow(provision).to receive(:customization_template).and_return(template)
    allow(provision).to receive(:post_install_callback_url).and_return("")
    expect(Base64.decode64(provision.userdata_payload)).to eq(template.script)
  end
end


text:
<?php

namespace Knnf\WhatsupBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * RightsRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class RightsRepository extends EntityRepository
{
	public function fetchPairs(){
		$em = $this->getEntityManager();
		$categories = $em->getRepository('KnnfWhatsupBundle:Rights')->findAll();

		foreach ($categories as $category) {
			$data[$category->getId()] = $category->getName();
		}

		return $data;
	}
}


text:
package com.tinkerpop.blueprints.util.wrappers.event2.listener;

import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.util.wrappers.event.listener.*;

/**
 * Event that fires when a property changes on a vertex.
 *
 * @author Stephen Mallette
 */
public class VertexPropertyChangedEvent extends VertexPropertyEvent {

    public VertexPropertyChangedEvent(final Vertex vertex, final String key, final Object oldValue, final Object newValue) {
        super(vertex, key, oldValue, newValue);
    }

    @Override
    void fire(final GraphChangedListener listener, final Vertex vertex, final String key, final Object oldValue, final Object newValue) {
        listener.vertexPropertyChanged(vertex, key, oldValue, newValue);
    }
}


text:
const char * mustache_version() {
  return MUSTACHE_PACKAGE_VERSION;
}

int mustache_version_int() {
  int maj = 0, min = 0, rev = 0;
  sscanf(MUSTACHE_PACKAGE_VERSION, "%d.%d.%d", &maj, &min, &rev);
  return (rev + (100 * min) + (10000 * maj));
}

namespace mustache {

void Mustache::tokenize(std::string * tmpl, Node * root)
{
  tokenizer.tokenize(tmpl, root);
}

void Mustache::render(Node * node, Data * data, Node::Partials * partials, std::string * output)
{
  renderer.init(node, data, partials, output);
  renderer.render();
}

} // namespace Mustache


text:
===================
Hargreaves equation
===================

The Hargreaves equation (Hargreaves and Samani, 1985) is a simple
evapotranspiration model that only requires a few easily accessible parameters:
mininimum, maximum and mean temperature, and extraterrestrial radiation.

The Hargreaves method is recommended by the FAO (Allen et al, 1998) as an
alternative method for estimating ETo if insufficient meteorological data are
available for the Penman-Monteith method. However, the FAO suggest that using
the Penman-Monteith method with estimated solar radiation, vapor pressure
and wind speed generally provides more accurate estimates than the Hargreaves
equation. This is due to the ability of the estimation equations to
incorporate general climatic characteristics such as high or low wind speed
or high or low relative humidity into the ET\ :sub:`o` estimate made using the
FAO Penman-Monteith method.

The Hargreaves equation has a tendency to under-estimate ET\ :sub:`o`\
under high wind conditions(u2 > 3m/s) and to over-estimate under conditions of
high relative humidity.

The following example uses the Hargreaves model to estimate monthly PET for the
1st of February, 2014, for Aberdeen, Scotland (latitude 57.1526 degrees N).

First, convert latitude to radians and the date to day of the year (Julian
day)::

    >>> import datetime, pyeto
    >>> lat = pyeto.deg2rad(57.1526)  # Convert latitude to radians
    >>> day_of_year = datetime.date(2014, 2, 1).timetuple().tm_yday

To estimate extraterrestrial radiation we first need to calculate
solar declination, sunset hour angle and inverse relative distance Earth-Sun::

    >>> sol_dec = pyeto.sol_dec(day_of_year)            # Solar declination
    >>> sha = pyeto.sunset_hour_angle(lat, sol_dec)
    >>> ird = pyeto.inv_rel_dist_earth_sun(day_of_year)
    >>> et_rad = pyeto.et_rad(lat, sol_dec, sha, ird)   # Extraterrestrial radiation

Finally, we can estimate ET\ :sub:`o`\ , assuming a minimum temperature of
1.3, maximum temperature of 5.6 and mean temperature of 3.8::

    >>> hargreaves(1.3, 5.6, 3.8, et_rad)


text:
package net.lshift.diffa.agent.itest

import org.junit.Assert._
import net.lshift.diffa.agent.itest.support.TestConstants._
import java.lang.String
import support.TestEnvironment
import javax.mail.Session
import java.io.{File, FileInputStream}
import javax.mail.internet.MimeMessage
import util.matching.Regex
import org.slf4j.{Logger, LoggerFactory}
import java.net.URI
import org.junit.{Before, Test}
import net.lshift.diffa.kernel.participants.ParticipantType
import net.lshift.diffa.agent.client.DifferencesRestClient
import scala.collection.JavaConversions._
import java.util.{UUID, Properties}
import org.joda.time.{DateTimeZone, DateTime}
import net.lshift.diffa.kernel.differencing.ZoomLevels._
import net.lshift.diffa.agent.rest.AggregateRequest
import net.lshift.diffa.kernel.differencing.{InvalidAggregateRequestException, ZoomLevels, PairScanState, DifferenceEvent}

/**
 * Tests that can be applied to an environment to validate that differencing functionality works appropriately.
 */
trait CommonDifferenceTests {

  val log:Logger = LoggerFactory.getLogger(getClass)

  val mailDir = System.getProperty("diffa.maildir", System.getProperty("basedir", ".") + "/target/messages")
  log.debug("Using maildir: " + mailDir)

  val messageDir = (new File(mailDir)).getAbsoluteFile

  /**
   * The environment under test.
   */
  def env:TestEnvironment

  @Before
  def deleteMails() = {
    if (messageDir.exists) {
      messageDir.listFiles.foreach(f => f.delete)
    }
  }

  def getReport(from:DateTime, until:DateTime) : Array[DifferenceEvent]= {
    runScanAndWaitForCompletion(yearAgo, today)
    env.diffClient.getEvents(env.pairKey, from, until, 0, 100)
  }

  @Test
  def shouldFindNoDifferencesInEmptyParticipants {
    val diffs = getReport(yearAgo, today)
    assertNotNull(diffs)
    assertTrue(diffs.isEmpty)
  }

  @Test
  def detectionTimeShouldBeMatchTheMostRecentUpdatedTimeOnAParticipatingEntity = {
    val diffs = getVerifiedDiffs()
    assertNotNull(diffs(0))
    val detectionTime = diffs(0).detectedAt
    // TODO On a rainy day, look into why using a millisecond comparison is necessary
    assertEquals(yesterday.getMillis, detectionTime.getMillis)
  }

  @Test
  def shouldFindDifferencesInDifferingParticipants {
    val diffs = getVerifiedDiffs()
    val seqId = diffs(0).seqId

    val detail = env.diffClient.eventDetail(seqId, ParticipantType.UPSTREAM)
    assertNotNull(diffs)

    assertEquals("abcdef", detail)

    val fileList = messageDir.listFiles
    assertNotNull("File list was null for dir: " + messageDir, fileList)
    // #338 This notification test is broken since the default quiet time was set to a non-zero value,
    // but unfortuneately, this requires the config to be dynamically updateable.
    //assertEquals(1, fileList.size)
    //testForLink(fileList(0))
  }

  @Test
  def differencesShouldAggregateAtMultipleLevels = {

    val rightNow = new DateTime(2011,7,8,15,0,0,0, DateTimeZone.UTC)
    val upperBound = rightNow.plusMinutes(1)

    val events = 720 // 12 hours * 60 minutes, i.e. will get split at 8-hourly level, but fits into a daily column
    val columns = 32

    val expectedZoomedViews = Map(
      DAILY          -> List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 720), // 24 hour interval
      EIGHT_HOURLY   -> List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 480), // 0-8h, 8-16h intervals
      FOUR_HOURLY    -> List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 240, 240),  // 8-12h,12-16h
      TWO_HOURLY     -> List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 120, 120, 120, 120, 120, 120),  // 8-10h,10-12h,12-14h,14-16h
      HOURLY         -> List(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60),  // every hour, remembering the extra minute
      HALF_HOURLY    -> List(0, 0, 0, 0, 0, 0, 0, 0, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30),  // every half hour
      QUARTER_HOURLY -> List(15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15)  // every quarter hour
    )
    // Sanity check the test data
    expectedZoomedViews.foreach { case (k, v) => assertEquals("Zoom Level " + k, columns, v.length) }

    resetPair
    env.clearParticipants

    for (i <- 0 until events) {
      val timestamp = rightNow.minusMinutes(i)
      env.upstream.addEntity("id-" + i, yesterday, "ss", timestamp, "abcdef")
    }

    val fullLowerBound = rightNow.minusMinutes(ZoomLevels.lookupZoomLevel(DAILY) * columns)
    runScanAndWaitForCompletion(fullLowerBound, upperBound, 100, 100)

    val requests = expectedZoomedViews.map { case (zoomLevel, expectedBlobs) =>
      val lowerBound = upperBound.minusMinutes(ZoomLevels.lookupZoomLevel(zoomLevel) * columns)
      (zoomLevel.toString) -> AggregateRequest(lowerBound, upperBound, Some(ZoomLevels.lookupZoomLevel(zoomLevel)))
    }.toMap
    val aggregates = env.diffClient.retrieveAggregates(env.pairKey, requests)

    expectedZoomedViews.foreach{ case (zoomLevel, expectedBlobs) => {
      val retrieveAggregates = aggregates(zoomLevel.toString)

      assertEquals("Zoom level %s ".format(zoomLevel), expectedBlobs, retrieveAggregates)
    }}
  }

  @Test
  def differencesShouldSupportAggregateRequestsWithoutBucketing = {

    val rightNow = new DateTime(2011,7,8,15,0,0,0, DateTimeZone.UTC)
    val upperBound = rightNow.plusMinutes(1)

    val events = 720 // 12 hours * 60 minutes, i.e. will get split at 8-hourly level, but fits into a daily column
    val columns = 32

    resetPair
    env.clearParticipants

    for (i <- 0 until events) {
      val timestamp = rightNow.minusMinutes(i)
      env.upstream.addEntity("id-" + i, yesterday, "ss", timestamp, "abcdef")
    }

    val fullLowerBound = rightNow.minusMinutes(ZoomLevels.lookupZoomLevel(DAILY) * columns)
    runScanAndWaitForCompletion(fullLowerBound, upperBound, 100, 100)

    val requests = Map(
      "open-top" -> AggregateRequest(upperBound.minusMinutes(50), null, None),
      "open-bottom" -> AggregateRequest(null, upperBound.minusMinutes(50), None),
      "all" -> AggregateRequest(fullLowerBound, upperBound, None),
      "open-all" -> AggregateRequest(null.asInstanceOf[String], null.asInstanceOf[String], None)
    )
    val aggregates = env.diffClient.retrieveAggregates(env.pairKey, requests)

    assertEquals(List(50), aggregates("open-top"))
    assertEquals(List(events - 50), aggregates("open-bottom"))
    assertEquals(List(events), aggregates("all"))
    assertEquals(List(events), aggregates("open-all"))

    try {
      env.diffClient.retrieveAggregates(env.pairKey, Map("bad" -> AggregateRequest(null.asInstanceOf[String], null.asInstanceOf[String], Some(5))))
      fail("Should have thrown InvalidAggregateRequestException")
    } catch {
      case x:InvalidAggregateRequestException =>
        assertEquals("Both a start and end time must be defined when requesting bucketing", x.getMessage)
    }
  }

  private def resetPair = {
    try {
      env.deletePair
    }
    finally {
      env.createPair
    }
  }

  @Test
  def shouldBeAbleToIgnoreDifference() {
    val diffs = getVerifiedDiffs()
    assertFalse(diffs.isEmpty)

    env.diffClient.ignore(diffs(0).seqId)

    val events = env.diffClient.getEvents(env.pairKey, yearAgo, today, 0, 100)
    assertTrue(events.isEmpty)
  }

  @Test
  def shouldBeAbleToUnignoreDifference() {
    val diffs = getVerifiedDiffs()
    assertFalse(diffs.isEmpty)

    val ignored = env.diffClient.ignore(diffs(0).seqId)
    env.diffClient.unignore(ignored.seqId)

    val events = env.diffClient.getEvents(env.pairKey, yearAgo, today, 0, 100)
    assertEquals(1, events.length)
  }

  @Test
  def shouldFindDifferencesInParticipantsThatBecomeDifferent {
    runScanAndWaitForCompletion(yearAgo, today)
    env.addAndNotifyUpstream("abc", "abcdef", someDate = yesterday, someString = "ss")

    val diffs = env.differencesHelper.pollForAllDifferences(yearAgo, nextYear)

    assertFalse("Expected to find differences in range: %s -> %s".format(yearAgo, nextYear),diffs.isEmpty)
  }

  /**
   * Create a setup where there are two differences, but then run a scan with a view that will only see one of them.
   * The list of differences should only include the difference within the viewed range.
   */
  @Test
  def shouldNotScanOutsideViewBounds {
    runScanAndWaitForCompletion(yearAgo, nextYear)
    env.upstream.addEntity("abc", datetime = yesterday, someString = "ss", body = "abcdef", lastUpdated = new DateTime)
    env.upstream.addEntity("def", datetime = yesterday, someString = "tt", body = "abcdef", lastUpdated = new DateTime)
    runScanAndWaitForCompletion(yearAgo, nextYear, view = Some("tt-only"))

    val events = env.differencesHelper.pollForAllDifferences(yearAgo, nextYear)
    assertEquals(1, events.length)
    assertEquals("def", events(0).objId.id)
  }

  @Test
  def shouldIgnoreRealtimeChangesThatDontConformToConstraints {

    // someString is configured to be a string prefix category that only accepts 'ss' or 'tt'

    runScanAndWaitForCompletion(yearAgo, today)
    env.addAndNotifyUpstream("abc", "abcdef", someDate = yesterday, someString = "abcdef")

    val diffs = env.differencesHelper.pollForAllDifferences(yearAgo, nextYear)

    assertTrue("Expected not to find differences for realtime event", diffs.isEmpty)
  }

  @Test
  def shouldIgnoreScanChangesThatDontConformToConstraints {

    // someString is configured to be a string prefix category that only accepts 'ss'

    env.upstream.addEntity("abc", datetime = today, someString = "abcdef", lastUpdated = new DateTime, body = "abcdef")
    val diffs = getReport(yearAgo, nextYear)

    assertTrue("Expected not to find differences in scan", diffs.isEmpty)
  }

  @Test
  def shouldPageDifferences = {
    val start = new DateTime
    val end = start.plusMinutes(2)

    val size = 10
    for (i <- 1 to size) {
      env.addAndNotifyUpstream("" + i, "" + i, someDate = yesterday, someString = "ss")
    }
    runScanAndWaitForCompletion(yearAgo, today)

    val offset = 5

    val diffs1 = env.differencesHelper.tryAgain((d:DifferencesRestClient) => d.getEvents(env.pairKey, start, end, offset, size))
    val max = size - offset
    val length = diffs1.size
    assertTrue("Diffs was %s, but should have been maximally %s".format(length,max), max >= length)

    // Select the 7th and 8th differences and validate their content
    val subset = 2
    val diffs2 = env.differencesHelper.tryAgain((d:DifferencesRestClient) => d.getEvents(env.pairKey, start, end, 6, subset))

    assertTrue("Diffs was %s, but should have been maximally %s".format(diffs2.length,subset), subset >= diffs2.length)
    // TODO [#224] Put back in
    //assertEquals(subset, diffs2.size)

    // The events aren't guaranteed to come back in any particular order
    //val bySeqId = diffs2.sortBy(evt => evt.seqId)

    //assertEquals("Unexpected sequence %s; expected to see sequence 7, all were: %s".format(bySeqId(0), bySeqId), "7", bySeqId(0).seqId)
    //assertEquals("Unexpected sequence %s; expected to see sequence 8".format(bySeqId(1)), "8", bySeqId(1).seqId)
  }

  @Test
  def walkThroughEventDetails = {
    def guid() = UUID.randomUUID.toString
    val up = guid()
    val down = guid()
    val NO_CONTENT = "Expanded detail not available"

    runScanAndWaitForCompletion(yearAgo, nextYear)
    env.addAndNotifyUpstream("abc", up, someDate = yesterday, someString = "ss")

    val diffs = env.differencesHelper.pollForAllDifferences(yearAgo, nextYear)
    val seqId1 = diffs(0).seqId

    val up1 = env.diffClient.eventDetail(seqId1, ParticipantType.UPSTREAM)
    val down1 = env.diffClient.eventDetail(seqId1, ParticipantType.DOWNSTREAM)

    assertEquals(up, up1)
    assertEquals(NO_CONTENT, down1)

    env.addAndNotifyDownstream("abc", down, someDate = yesterday, someString = "ss")
    Thread.sleep(2000)
    val diffs2 = env.differencesHelper.pollForAllDifferences(yearAgo, nextYear)
    assertEquals(1, diffs2.length)
    val seqId2 = diffs2(0).seqId

    assertTrue("Invalid sequence ids: seqId1 = %s, seqId2 = %s".format(seqId1, seqId2), seqId2 > seqId1)

    val up2 = env.diffClient.eventDetail(seqId2, ParticipantType.UPSTREAM)
    val down2 = env.diffClient.eventDetail(seqId2, ParticipantType.DOWNSTREAM)
    assertEquals(up, up2)
    assertEquals(down, down2)
  }

  @Test
  def shouldNotFindDifferencesInParticipantsWithSameStateThatAgentWasntInformedOf {
    env.upstream.addEntity("abc", yesterday, "ss", yesterday, "abcdef")
    env.downstream.addEntity("abc", yesterday, "ss", yesterday, "abcdef")

    val diffs = getReport(yearAgo, today)

    assertNotNull(diffs)
    assertTrue(diffs.isEmpty)
  }

  @Test
  def shouldReportMatchOnlyAsChangesAreReportedWithinMatchingWindow {

    env.addAndNotifyUpstream("abc", "abcdef", someDate = today, someString = "ss")
    env.addAndNotifyDownstream("abc", "abcdef", someDate = today, someString = "ss")

    val diffs = getReport(yearAgo, today)

    assertNotNull(diffs)
    assertTrue(diffs.isEmpty)

  }

  @Test
  def scanShouldTriggerResend {
    env.withActionsServer {
      env.upstream.addEntity("abc", datetime = today, someString = "ss", lastUpdated = new DateTime, body = "abcdef")
      runScanAndWaitForCompletion(yearAgo, today)

      waitForResendTally("abc", 1)
    }
  }

  @Test
  def scanShouldBeCancellable {
    env.withActionsServer {
      env.upstream.addEntity("abc", datetime = today, someString = "ss", lastUpdated = new DateTime, body = "abcdef")

      // Make the upstream wait 5s before responding so the scan doesn't complete too quickly
      env.upstream.queryResponseDelay = 5000

      // Get into a scanning state
      env.scanningClient.startScan(env.pairKey)
      waitForScanStatus(env.pairKey, PairScanState.SCANNING)

      // Cancel the scan
      env.scanningClient.cancelScanning(env.pairKey)
      waitForScanStatus(env.pairKey, PairScanState.CANCELLED)
    }
  }

  def runScanAndWaitForCompletion(from:DateTime, until:DateTime, n:Int = 30, wait:Int = 100, view:Option[String] = None) {
    env.scanningClient.startScan(env.pairKey, view = view)

    waitForScanStatus(env.pairKey, PairScanState.UP_TO_DATE, n, wait)
  }

  def waitForScanStatus(pairKey:String, state:PairScanState, n:Int = 30, wait:Int = 100) {
    def hasReached(states:Map[String, PairScanState]) = states.getOrElse(pairKey, PairScanState.UNKNOWN) == state

    var i = n
    var scanStatus = env.scanningClient.getScanStatus
    while(!hasReached(scanStatus) && i > 0) {
      Thread.sleep(wait)

      scanStatus = env.scanningClient.getScanStatus
      i-=1
    }
    assertTrue("Unexpected scan state (pair = %s): %s (wanted %s)".format(pairKey, scanStatus, state), hasReached(scanStatus))
  }

  def waitForResendTally(entity:String, count:Int) {
    val timeout = 5000L
    val deadline = System.currentTimeMillis() + timeout

    env.entityResendTally.synchronized {
      while (true) {
        val currentCount = env.entityResendTally.getOrElse(entity, 0)

        if (currentCount == count)
          return

        if (System.currentTimeMillis > deadline) {
          fail("Entity resend tally %s for %s never reached (got to %s)".format(count, entity, currentCount))
        }

        env.entityResendTally.wait(timeout)
      }
    }
  }

  def getVerifiedDiffs() = {
    env.upstream.addEntity("abc", yesterday, "ss", yesterday, "abcdef")

    runScanAndWaitForCompletion(yearAgo, today)
    val diffs = env.differencesHelper.pollForAllDifferences(yearAgo, today)

    assertNotNull(diffs)
    assertFalse(diffs.isEmpty)
    diffs
  }

  def testForLink(f:File) = {
      val s = Session.getInstance(new Properties())
      val msg = new MimeMessage(s,new FileInputStream(f))
      val content = msg.getContent.asInstanceOf[String]

      log.debug("Inspecting content from file: " + f.getAbsolutePath)
      log.debug(content)

      val pattern = new Regex(""".*<a href=\"(.*)\".*""", "link");
      pattern.findFirstMatchIn(content) match {
        case None         => fail("Error extracting link from file: " + f.getAbsolutePath)
        case Some(result) => {
          // Attempt to parse the URL, if it is bogus, let the exception fly
          val uri = new URI(result.group("link"))
        }
      }
    }

}


text:
layout: post

title: Praktikum bei Code for Germany
author: Fiona
excerpt: Wir suchen Verstärkung für unser Team zum nächstmöglichen Zeitpunkt.

images:
- imgname: praktikum.png

---
![praktikum](/assets/blog/praktikum.png)

Wir suchen eine/n Praktikanten/in zum nächstmöglichen Zeitpunkt.

Du interessierst dich für Technologie, Politik, Design und Aktivismus und das Internet ist deine zweite Heimat. Bloggen, schreiben und twittern machen dir Spaß. Du wolltest schon immer mal für eine NGO arbeiten, hast eine eigenständige Arbeitsweise, Lust viel zu lernen und dich weiterzuentwickeln.

Trifft auf dich zu? Dann freuen wir uns darauf, dich kennenzulernen. Wir bieten dir ein spannendes Projekt, viel Freiraum für persönliche Entwicklung, flache Hierarchien und die Möglichkeit auch über das Praktikum hinaus Teil des Teams zu werden. Das Praktikum sehen wir als eine Art Probezeit und freuen uns über langfristige Unterstützung.

Start: Zum nächstmöglichen Zeitpunkt

Zeit: Mindestens 20h/Woche

Gehalt: Das Praktikum wird vergütet.

Ort: Berlin, Büro des Open Knowledge Foundation Deutschland e.V.

**Profil:**

* Du hast bereits Erfahrung im Bereich Kommunikation und Öffentlichkeitsarbeit und dir sind auch privat die gängigen Plattformen bekannt.
* Du hast exzellente Kommunikationsfähigkeiten und verfügst über sehr gute Englischkenntnisse in Wort und Schrift
* Du hast keine Angst vor der Kommandozeile, schonmal mit Html und CSS gearbeitet und idealerweise schon mal ein paar Zeilen Code gelesen und geschrieben
* Plus: Du kennst dich mit mindestens einem Design-Programm aus
* Plus: Du hast im besten Falle deinen Bachelor oder Master abgeschlossen
* Doppelplus: Du willst über dein Praktikum hinaus bei der Open Knowledge Foundation arbeiten

**Wichtig für uns ist**

* Du hast dich mit Code for Germany auseinandergesetzt und kennst das Programm
* Dir sind die Themen Open Data und Civic Tech bekannt und du hast Interesse daran, inhaltlich an diesen Themen zu arbeiten
* Du arbeitest eigenständig und strukturiert, bist proaktiv, kannst Chancen erkennen und hast keine Angst, Initiativen zu ergreifen
* Du arbeitest gerne im Team und in Kollaboration mit Anderen
* Du hast Erfahrung mit administrativen Prozessen und du ergreifst beim Wort "Buchhaltung" nicht panisch die Flucht
* Du hast kein Problem damit, administrative, manchmal nicht so spannende aber wichtige Aufgaben zu übernehmen
* Im Herzen bist du ein Nerd <3

**Wir bieten dir**

* Arbeit in einer etablierten non-profit Organisation, mit einem vielseitigen Projektportfolio
* Die Mitarbeit an einem spannenden Projekt mit einer großartigen Community
* Die Zusammenarbeit mit einem professionellen und sehr netten Team
* Zugang zu unserem deutschen und internationalen Netzwerk
* Die Möglichkeit, dich aktiv mit eigenen Ideen einzubringen
* Die Möglichkeit dich persönlich und professionell weiterzuentwickeln

Wenn du Interesse hast, dann schick uns deine Bewerbung bis zum 31. Mai per E-Mail an **[info@codefor.de](mailto:info@codefor.de)**.

Wir freuen uns auf dich!

Julia & Fiona


text:
title: Load Balancing Algorithm | Kubernetes Ingress
menu:
  docs_{{ .version }}:
    identifier: load-balancing-algorithm
    name: Load Balancing Algorithm
    parent: config-ingress
    weight: 10
product_name: voyager
menu_name: docs_{{ .version }}
section_menu_id: guides
---
> New to Voyager? Please start [here](/docs/concepts/overview.md).

# Configure Load Balancing Algorithm

You can configure a backend to use a specific [load balancing algorithm](https://cbonte.github.io/haproxy-dconv/1.9/configuration.html#balance) using `backend.loadBalanceOn`. You can specify any HAProxy supported options along with arguments.

Ingress Example:

```yaml
apiVersion: voyager.appscode.com/v1
kind: Ingress
metadata:
  name: test-ingress
  namespace: demo
spec:
  defaultBackend:
    service:
      name: test-server
      port:
        number: 80
    loadBalanceOn: roundrobin # configure for default backend
  rules:
  - http:
      port: 8989
      paths:
      - backend:
          service:
            name: test-server
            port:
              number: 8989
          loadBalanceOn: static-rr # configure for http backend
  - tcp:
      port: 4545
      backend:
        service:
          name: test-server
          port:
            number: 4545
        loadBalanceOn: leastconn # configure for tcp backend
```

Generated haproxy.cfg:

```ini
# HAProxy configuration generated by https://github.com/appscode/voyager
# DO NOT EDIT!
global
  daemon
  stats socket /var/run/haproxy.sock level admin expose-fd listeners
  server-state-file global
  server-state-base /var/state/haproxy/
  # log using a syslog socket
  log /dev/log local0 info
  tune.ssl.default-dh-param 2048
  ssl-default-bind-ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK
  lua-load /etc/auth-request.lua
  hard-stop-after 30s
defaults
  log global
  # https://cbonte.github.io/haproxy-dconv/1.7/configuration.html#4.2-option%20abortonclose
  # https://github.com/voyagermesh/voyager/pull/403
  option dontlognull
  option http-server-close
  # Timeout values
  timeout client 50s
  timeout client-fin 50s
  timeout connect 5s
  timeout server 50s
  timeout tunnel 50s
  # Configure error files
  # default traffic mode is http
  # mode is overwritten in case of tcp services
  mode http
frontend http-0_0_0_0-8989
  bind *:8989
  mode http
  option httplog
  option forwardfor
  acl is_proxy_https hdr(X-Forwarded-Proto) https
  acl is_proxy_https ssl_fc
  http-request set-var(req.scheme) str(https) if is_proxy_https
  http-request set-var(req.scheme) str(http) if ! is_proxy_https
  use_backend test-server.demo:8989
  default_backend default-backend
backend test-server.demo:8989
  balance static-rr
  server pod-test-server-47lck 172.17.0.5:8989
frontend tcp-0_0_0_0-4545
  bind *:4545
  mode tcp
  default_backend test-server.demo:4545
backend test-server.demo:4545
  mode tcp
  balance leastconn
  server pod-test-server-47lck 172.17.0.5:4545
backend default-backend
  balance roundrobin
  server pod-test-server-47lck 172.17.0.5:8080
```

Instead of configuring backends you can also specify load balancing algorithm in `defaults` sections. For that, you need to add `balance <algorithm>` in `defaults.cfg` using custom template. See [here](/docs/guides/ingress/configuration/custom-templates.md) for detailed example on custom template.


text:
var c = {
    controller : function() {
        this.onunload = function() {
            console.log("onunload");
        };
    }
};

// Leave controller
var c = {
    controller : function() {
        this.prop = "value";

        this.onunload = function() {
            console.log("onunload");
        };
    }
};

// Arrow fns
var c = {
    controller : function() {
        this.onunload = () => console.log("onunload");
    }
};

// Not using `this`
var c = {
    controller : function() {
        var ctrl = this;

        ctrl.onunload = function() {
            console.log("onunload");
        }
    }
};

// Reference
var c = {
    controller : function() {
        this.onunload = reference;
    }
};

var c = {
    controller : function() {
        otherFunc();

        this.onunload = reference;
    }
};


text:
package stork.ad;

import java.lang.reflect.*;

public interface Unmarshaller<T> {
  // Unmarshal the ad into an instance of a class. May be passed a base
  // instance of the class, if one is present (e.g. when unmarshalling into
  // a field which is already set) or null. This method will also be passed
  // generic parameters, if present, on a best-effort basis.
  public T unmarshal(Ad ad, T base, Type... generics);
}


text:
namespace StockSharp.Charting
{
	using System.ComponentModel.DataAnnotations;

	using StockSharp.Localization;

	/// <summary>
	/// Chart axes types.
	/// </summary>
	public enum ChartAxisType
	{
		/// <summary>
		/// Time.
		/// </summary>
		[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.TimeKey)]
		DateTime,

		/// <summary>
		/// Time without breaks.
		/// </summary>
		[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str1915Key)]
		CategoryDateTime,

		/// <summary>
		/// Number.
		/// </summary>
		[Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str1916Key)]
		Numeric
	}
}


text:
/*
* TLS Cipher Suites
* (C) 2004-2011,2012 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#ifndef BOTAN_TLS_CIPHER_SUITES_H_
#define BOTAN_TLS_CIPHER_SUITES_H_

#include <botan/types.h>
#include <botan/tls_algos.h>
#include <botan/tls_version.h>
#include <string>
#include <vector>

namespace Botan {

namespace TLS {

/**
* Ciphersuite Information
*/
class BOTAN_PUBLIC_API(2,0) Ciphersuite final
   {
   public:
      /**
      * Convert an SSL/TLS ciphersuite to algorithm fields
      * @param suite the ciphersuite code number
      * @return ciphersuite object
      */
      static Ciphersuite by_id(uint16_t suite);

      /**
      * Convert an SSL/TLS ciphersuite name to algorithm fields
      * @param name the IANA name for the desired ciphersuite
      * @return ciphersuite object
      */
      static Ciphersuite from_name(const std::string& name);

      /**
      * Returns true iff this suite is a known SCSV
      */
      static bool is_scsv(uint16_t suite);

      /**
      * Generate a static list of all known ciphersuites and return it.
      *
      * @return list of all known ciphersuites
      */
      static const std::vector<Ciphersuite>& all_known_ciphersuites();

      /**
      * Formats the ciphersuite back to an RFC-style ciphersuite string
      * @return RFC ciphersuite string identifier
      */
      std::string to_string() const { return m_iana_id; }

      /**
      * @return ciphersuite number
      */
      uint16_t ciphersuite_code() const { return m_ciphersuite_code; }

      /**
      * @return true if this is a PSK ciphersuite
      */
      bool psk_ciphersuite() const;

      /**
      * @return true if this is an ECC ciphersuite
      */
      bool ecc_ciphersuite() const;

      /**
       * @return true if this suite uses a CBC cipher
       */
      bool cbc_ciphersuite() const;

      bool signature_used() const;

      /**
      * @return key exchange algorithm used by this ciphersuite
      */
      std::string kex_algo() const { return kex_method_to_string(kex_method()); }

      Kex_Algo kex_method() const { return m_kex_algo; }

      /**
      * @return signature algorithm used by this ciphersuite
      */
      std::string sig_algo() const { return auth_method_to_string(auth_method()); }

      Auth_Method auth_method() const { return m_auth_method; }

      /**
      * @return symmetric cipher algorithm used by this ciphersuite
      */
      std::string cipher_algo() const { return m_cipher_algo; }

      /**
      * @return message authentication algorithm used by this ciphersuite
      */
      std::string mac_algo() const { return m_mac_algo; }

      std::string prf_algo() const
         {
         return kdf_algo_to_string(m_prf_algo);
         }

      /**
      * @return cipher key length used by this ciphersuite
      */
      size_t cipher_keylen() const { return m_cipher_keylen; }

      size_t nonce_bytes_from_handshake() const;

      size_t nonce_bytes_from_record(Protocol_Version version) const;

      Nonce_Format nonce_format() const { return m_nonce_format; }

      size_t mac_keylen() const { return m_mac_keylen; }

      /**
      * @return true if this is a valid/known ciphersuite
      */
      bool valid() const { return m_usable; }

      bool usable_in_version(Protocol_Version version) const;

      bool operator<(const Ciphersuite& o) const { return ciphersuite_code() < o.ciphersuite_code(); }
      bool operator<(const uint16_t c) const { return ciphersuite_code() < c; }

      Ciphersuite() = default;

   private:

      bool is_usable() const;

      Ciphersuite(uint16_t ciphersuite_code,
                  const char* iana_id,
                  Auth_Method auth_method,
                  Kex_Algo kex_algo,
                  const char* cipher_algo,
                  size_t cipher_keylen,
                  const char* mac_algo,
                  size_t mac_keylen,
                  KDF_Algo prf_algo,
                  Nonce_Format nonce_format) :
         m_ciphersuite_code(ciphersuite_code),
         m_iana_id(iana_id),
         m_auth_method(auth_method),
         m_kex_algo(kex_algo),
         m_prf_algo(prf_algo),
         m_nonce_format(nonce_format),
         m_cipher_algo(cipher_algo),
         m_mac_algo(mac_algo),
         m_cipher_keylen(cipher_keylen),
         m_mac_keylen(mac_keylen)
         {
         m_usable = is_usable();
         }

      uint16_t m_ciphersuite_code = 0;

      /*
      All of these const char* strings are references to compile time
      constants in tls_suite_info.cpp
      */
      const char* m_iana_id = nullptr;

      Auth_Method m_auth_method = Auth_Method::ANONYMOUS;
      Kex_Algo m_kex_algo = Kex_Algo::STATIC_RSA;
      KDF_Algo m_prf_algo = KDF_Algo::SHA_1;
      Nonce_Format m_nonce_format = Nonce_Format::CBC_MODE;

      const char* m_cipher_algo = nullptr;
      const char* m_mac_algo = nullptr;

      size_t m_cipher_keylen = 0;
      size_t m_mac_keylen = 0;

      bool m_usable = false;
   };

}

}

#endif


text:
var oboe = require('oboe');
var fs = require('fs');

var vertexToXml = require('./vertexToXml.js');
var edgeToXml = require('./edgeToXml.js');
var util = require('./util.js');

var indent4 = util.indent(4);

function convertFile(inFilePath, outFilePath, schemaInfo, options) {
  var vertexNames = schemaInfo.vertexNames;
  var edgeNames = schemaInfo.edgeNames;
  return new Promise(function(fulfill, reject) {
    extractVerticesEdges(inFilePath, outFilePath, vertexNames, edgeNames, options).
      then(function(result) {
        fulfill(result);
    }).catch(function(err) {
      reject(err);
    });
  });
}

var graphmlHeader = `<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
  <graph id="G" edgedefault="directed">`;

var graphmlFooter = `
  </graph>
</graphml>
`;

/**
 * Return true if json record has type 'd' -- this will exclude built-in orientdb
 * records like OUser.
 */
function isUserDefinedRecord(record) {
  return record['@type'] === 'd';
}

var ridIndices = {};

function indicateVertexHasBeenSeen(record) {
  ridIndices[record['@rid']] = true;
}

function edgeIsOrphan(record) {
  var rid1 = record['in'];
  var rid2 = record['out'];
  return ridIndices[rid1] === undefined || ridIndices[rid2] === undefined;
}

function extractVerticesEdges(inFilePath, outFilePath, vertexNames, edgeNames, options) {
  options = options || {};

  function shouldExtractVertex(record) {
    return isUserDefinedRecord(record) && vertexNames.indexOf(record['@class']) !== -1;
  }

  function shouldExtractEdge(record) {
    return isUserDefinedRecord(record) && edgeNames.indexOf(record['@class']) !== -1;
  }

  var outStream = fs.createWriteStream(outFilePath);
  outStream.write(graphmlHeader);

  var vertexReadstream = fs.createReadStream(inFilePath);
  var edgeReadstream = fs.createReadStream(inFilePath);
  var vertexCount = 0;
  var edgeCount = 0;
  var pruneOrphanEdges = options.pruneOrphanEdges;
  var prunedEdgeCount = 0;

  return new Promise(function(fulfill, reject) {
    vertexReadstream.on('error', function(e) {
      reject(e);
    });
    edgeReadstream.on('error', function(e) {
      reject(e);
    });

    oboe(vertexReadstream)
      .node({
        'records.*': function(record) {
          if (shouldExtractVertex(record)) {
            outStream.write('\n'+indent4(vertexToXml(record)));
            vertexCount++;
            if (pruneOrphanEdges) {
              indicateVertexHasBeenSeen(record);
            }
          }
          return oboe.drop;
        }
      })
      .done(function() {
        oboe(edgeReadstream)
          .node({
            'records.*': function(record) {
              if (shouldExtractEdge(record)) {
                if (pruneOrphanEdges && edgeIsOrphan(record)) {
                  prunedEdgeCount++;
                }
                else {
                  outStream.write('\n'+indent4(edgeToXml(record)));
                  edgeCount++;
                }
              }
              return oboe.drop;
            }
          })
          .done(function() {
            outStream.write(graphmlFooter);
            outStream.end();
          })
      .on('fail', function(e) {
        reject(e);
      });
    }).on('fail', function(e) {
      reject(e);
    });
    outStream.on('finish', function() {
      fulfill({
        edgeCount: edgeCount,
        vertexCount: vertexCount,
        prunedEdgeCount: prunedEdgeCount
      });
    });
  });
}

module.exports = {
  convertFile: convertFile
};


text:
<!DOCTYPE HTML>

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

001package io.ebean.cache;
002
003import io.ebean.config.CurrentTenantProvider;
004
005/**
006 * Configuration used to create ServerCache instances.
007 */
008public class ServerCacheConfig {
009
010  private final ServerCacheType type;
011  private final String cacheKey;
012  private final String shortName;
013  private final ServerCacheOptions cacheOptions;
014  private final CurrentTenantProvider tenantProvider;
015  private final QueryCacheEntryValidate queryCacheEntryValidate;
016
017  public ServerCacheConfig(ServerCacheType type, String cacheKey, String shortName, ServerCacheOptions cacheOptions, CurrentTenantProvider tenantProvider, QueryCacheEntryValidate queryCacheEntryValidate) {
018    this.type = type;
019    this.cacheKey = cacheKey;
020    this.shortName = shortName;
021    this.cacheOptions = cacheOptions;
022    this.tenantProvider = tenantProvider;
023    this.queryCacheEntryValidate = queryCacheEntryValidate;
024  }
025
026  /**
027   * Return the cache type.
028   */
029  public ServerCacheType getType() {
030    return type;
031  }
032
033  /**
034   * Return the name of the cache.
035   */
036  public String getCacheKey() {
037    return cacheKey;
038  }
039
040  /**
041   * Return the short name for the cache.
042   */
043  public String getShortName() {
044    return shortName;
045  }
046
047  /**
048   * Return the tuning options.
049   */
050  public ServerCacheOptions getCacheOptions() {
051    return cacheOptions;
052  }
053
054  /**
055   * Return the current tenant provider.
056   */
057  public CurrentTenantProvider getTenantProvider() {
058    return tenantProvider;
059  }
060
061  /**
062   * Return the service that provides validation for query cache entries.
063   */
064  public QueryCacheEntryValidate getQueryCacheEntryValidate() {
065    return queryCacheEntryValidate;
066  }
067
068  /**
069   * Return true if the cache is a query cache.
070   */
071  public boolean isQueryCache() {
072    return type == ServerCacheType.QUERY;
073  }
074}


text:
#ifndef ESP8266HTTPUPDATE_H_
#define ESP8266HTTPUPDATE_H_

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <WiFiUdp.h>
#include <ESP8266HTTPClient.h>

#ifdef DEBUG_ESP_HTTP_UPDATE
#ifdef DEBUG_ESP_PORT
#define DEBUG_HTTP_UPDATE(...) DEBUG_ESP_PORT.printf( __VA_ARGS__ )
#endif
#endif

#ifndef DEBUG_HTTP_UPDATE
#define DEBUG_HTTP_UPDATE(...)
#endif

/// note we use HTTP client errors too so we start at 100
#define HTTP_UE_TOO_LESS_SPACE              (-100)
#define HTTP_UE_SERVER_NOT_REPORT_SIZE      (-101)
#define HTTP_UE_SERVER_FILE_NOT_FOUND       (-102)
#define HTTP_UE_SERVER_FORBIDDEN            (-103)
#define HTTP_UE_SERVER_WRONG_HTTP_CODE      (-104)
#define HTTP_UE_SERVER_FAULTY_MD5           (-105)
#define HTTP_UE_BIN_VERIFY_HEADER_FAILED    (-106)
#define HTTP_UE_BIN_FOR_WRONG_FLASH         (-107)

enum HTTPUpdateResult {
    HTTP_UPDATE_FAILED,
    HTTP_UPDATE_NO_UPDATES,
    HTTP_UPDATE_OK
};

typedef HTTPUpdateResult t_httpUpdate_return; // backward compatibility

class ESP8266HTTPUpdate
{
public:
    ESP8266HTTPUpdate(void);
    ~ESP8266HTTPUpdate(void);

    void rebootOnUpdate(bool reboot)
    {
        _rebootOnUpdate = reboot;
    }

    // This function is deprecated, use rebootOnUpdate and the next one instead
    t_httpUpdate_return update(const String& url, const String& currentVersion,
                               const String& httpsFingerprint, bool reboot) __attribute__((deprecated));
    t_httpUpdate_return update(const String& url, const String& currentVersion = "");
    t_httpUpdate_return update(const String& url, const String& currentVersion,
                               const String& httpsFingerprint);

    // This function is deprecated, use one of the overloads below along with rebootOnUpdate
    t_httpUpdate_return update(const String& host, uint16_t port, const String& uri, const String& currentVersion,
                               bool https, const String& httpsFingerprint, bool reboot) __attribute__((deprecated));

    t_httpUpdate_return update(const String& host, uint16_t port, const String& uri = "/",
                               const String& currentVersion = "");
    t_httpUpdate_return update(const String& host, uint16_t port, const String& url,
                               const String& currentVersion, const String& httpsFingerprint);

    // This function is deprecated, use rebootOnUpdate and the next one instead
    t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion,
                                     const String& httpsFingerprint, bool reboot) __attribute__((deprecated));
    t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion = "");
    t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint);

    int getLastError(void);
    String getLastErrorString(void);

protected:
    t_httpUpdate_return handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs = false);
    bool runUpdate(Stream& in, uint32_t size, String md5, int command = U_FLASH);

    int _lastError;
    bool _rebootOnUpdate = true;
};

#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_HTTPUPDATE)
extern ESP8266HTTPUpdate ESPhttpUpdate;
#endif

#endif /* ESP8266HTTPUPDATE_H_ */


text:
GLWidget::GLWidget(QWidget *parent) :
    QGLWidget(parent)
{
}

QSize GLWidget::minimumSizeHint() const
{
    return QSize(50, 50);
}

QSize GLWidget::sizeHint() const
{
    return QSize(1600, 900);
}

void GLWidget::initializeGL()
{
    context.reset(new GraphicsContext(*this));
}

void GLWidget::resizeGL(int width, int height)
{
    context->getViewport().onResize(width, height);
}

void GLWidget::paintGL()
{
    context->renderFrame();
}


text:
package org.apache.samza.test.harness;

import org.apache.samza.config.Config;
import org.apache.samza.system.IncomingMessageEnvelope;
import org.apache.samza.system.OutgoingMessageEnvelope;
import org.apache.samza.system.SystemStream;
import org.apache.samza.task.*;

import java.util.AbstractMap;
import java.util.LinkedList;
import java.util.List;

/**
 * A simple test Samza task that buffers all messages in PROCESS.
 * During WINDOWing every message returns the same key
 * and defines the new value to be x10 the original value.
 * k1 = original key
 * v1 = original value
 * (k1, v1) -> (k1, v1*10)
 */
public class TestWindowTask implements StreamTask, InitableTask, WindowableTask {
    private static final String KAFKA_SYSTEM = "kafka";
    private static final String OUTPUT_STREAM_COUNT_TOPIC = "test";
    private SystemStream outputStream;
    private List<AbstractMap.SimpleEntry> counterList = new LinkedList<AbstractMap.SimpleEntry>();

    @Override
    public void init(Config config, TaskContext taskContext) throws Exception {
        outputStream = new SystemStream(KAFKA_SYSTEM, OUTPUT_STREAM_COUNT_TOPIC);
    }

    @SuppressWarnings("unchecked")
    @Override
    public void process(IncomingMessageEnvelope envelope, MessageCollector collector, TaskCoordinator taskCoordinator) throws Exception {
        String key = (String) envelope.getKey();
        Integer value = (Integer) envelope.getMessage();
        counterList.add(new AbstractMap.SimpleEntry<String, Integer>(key, value));
    }

    @Override
    public void window(MessageCollector collector, TaskCoordinator taskCoordinator) throws Exception {
        for (int i = 0; i < counterList.size(); i++) {
            Integer value = (Integer) counterList.get(i).getValue();
            collector.send(new OutgoingMessageEnvelope(outputStream, counterList.get(i).getKey(), value * 10));
        }
        counterList.clear();
    }
}


text:
import Cloud = pxt.Cloud;
import U = pxt.Util;

let iface: pxt.worker.Iface

interface HidDevice {
    vendorId: number; // 9025,
    productId: number; // 589,
    path: string;
    serialNumber: string; // '',
    manufacturer: string; // 'Arduino LLC',
    product: string; // 'Arduino Zero',
    release: number; // 0x4201
}

export class HIDError extends Error {
    constructor(msg: string) {
        super(msg)
        this.message = msg
    }
}

let bridgeByPath: pxt.Map<BridgeIO> = {}

interface OOB {
    op: string;
    result: {
        path: string;
        data?: string;
        isError?: boolean;
        errorMessage?: string;
        errorStackTrace?: string;
    }
}

function onOOB(v: OOB) {
    let b = U.lookup(bridgeByPath, v.result.path)
    if (b) {
        b.onOOB(v)
    } else {
        console.error("Dropping data for " + v.result.path)
    }
}

function init() {
    if (!iface) {
        if (!Cloud.isLocalHost() || !Cloud.localToken)
            return;
        pxt.debug('initializing hid pipe');
        iface = pxt.worker.makeWebSocket(
            `ws://localhost:${pxt.options.wsPort}/${Cloud.localToken}/hid`, onOOB)
    }
}

export function shouldUse() {
    let serial = pxt.appTarget.serial
    return serial && serial.useHF2 && (Cloud.isLocalHost() && !!Cloud.localToken || pxt.winrt.isWinRT());
}

function mkBridgeAsync(): Promise<pxt.HF2.PacketIO> {
    init()
    let raw = false
    if (pxt.appTarget.serial && pxt.appTarget.serial.rawHID)
        raw = true
    let b = new BridgeIO(raw)
    return b.initAsync()
        .then(() => b);
}

pxt.HF2.mkPacketIOAsync = mkBridgeAsync;

class BridgeIO implements pxt.HF2.PacketIO {
    onData = (v: Uint8Array) => { };
    onEvent = (v: Uint8Array) => { };
    onError = (e: Error) => { };
    onSerial = (v: Uint8Array, isErr: boolean) => { };
    public dev: HidDevice;

    constructor(public rawMode = false) {
        if (rawMode)
            this.onEvent = v => this.onData(v)
    }

    onOOB(v: OOB) {
        if (v.op == "serial") {
            this.onSerial(U.fromHex(v.result.data), v.result.isError)
        } else if (v.op == "event") {
            this.onEvent(U.fromHex(v.result.data))
        }
    }

    talksAsync(cmds: pxt.HF2.TalkArgs[]): Promise<Uint8Array[]> {
        return iface.opAsync("talk", {
            path: this.dev.path,
            cmds: cmds.map(c => ({ cmd: c.cmd, data: c.data ? U.toHex(c.data) : "" }))
        })
            .then(resp => {
                return resp.map((v: any) => U.fromHex(v.data))
            })
    }

    error(msg: string) {
        throw new HIDError(U.lf("USB/HID error on device {0} ({1})", this.dev.product, msg))
    }

    reconnectAsync(): Promise<void> {
        return this.initAsync()
    }

    disconnectAsync(): Promise<void> {
        return iface.opAsync("disconnect", {
            path: this.dev.path
        })
    }

    sendPacketAsync(pkt: Uint8Array): Promise<void> {
        if (this.rawMode)
            return iface.opAsync("send", {
                path: this.dev.path,
                data: U.toHex(pkt),
                raw: true
            })
        throw new Error("should use talksAsync()!")
    }

    sendSerialAsync(buf: Uint8Array, useStdErr: boolean): Promise<void> {
        return iface.opAsync("sendserial", {
            path: this.dev.path,
            data: U.toHex(buf),
            isError: useStdErr
        })
    }

    initAsync(): Promise<void> {
        return iface.opAsync("list", {})
            .then((devs0: any) => {
                let devs = devs0.devices as HidDevice[]
                let d0 = devs.filter(d => (d.release & 0xff00) == 0x4200)[0]
                if (pxt.appTarget.serial && pxt.appTarget.serial.rawHID)
                    d0 = devs[0]
                if (d0) {
                    if (this.dev)
                        delete bridgeByPath[this.dev.path]
                    this.dev = d0
                    bridgeByPath[this.dev.path] = this
                }
                else throw new Error("No device connected")
            })
            .then(() => iface.opAsync("init", {
                path: this.dev.path,
                raw: this.rawMode,
            }))
    }
}

let uf2Wrapper: pxt.HF2.Wrapper;
let initPromise: Promise<pxt.HF2.Wrapper>;
let serialHandler: (buf: Uint8Array, isStderr: boolean) => void;

function hf2Async() {
    return pxt.HF2.mkPacketIOAsync()
        .then(h => {
            uf2Wrapper = new pxt.HF2.Wrapper(h);
            if (serialHandler) {
                uf2Wrapper.onSerial = serialHandler;
            }
            return uf2Wrapper.reconnectAsync(true)
                .then(() => uf2Wrapper)
        })
}

export function configureHidSerial(serialCb: (buf: Uint8Array, isStderr: boolean) => void): void {
    serialHandler = serialCb;
    if (uf2Wrapper) {
        uf2Wrapper.onSerial = serialHandler;
    }
}

export function disconnectWrapperAsync(): Promise<void> {
    if (uf2Wrapper) {
        return uf2Wrapper.disconnectAsync();
    }
    return Promise.resolve();
}

export function initAsync(force = false) {
    if (!initPromise) {
        initPromise = hf2Async()
            .catch(err => {
                initPromise = null
                return Promise.reject(err)
            })
    }
    let wrapper: pxt.HF2.Wrapper;
    return initPromise
        .then((w) => {
            wrapper = w;
            if (force) {
                return wrapper.reconnectAsync();
            }
            return Promise.resolve();
        })
        .then(() => wrapper);
}


text:
import pytest
import numpy as np
import nnabla.functions as F
from nbla_test_utils import list_context

ctxs = list_context('HuberLoss')

def ref_huber_loss(x0, x1, delta):
    grad = (x0 - x1)
    q = np.minimum(np.abs(grad), delta)
    l = np.abs(grad) - q
    return q ** 2 + 2 * delta * l

@pytest.mark.parametrize("ctx, func_name", ctxs)
@pytest.mark.parametrize("seed", [313])
@pytest.mark.parametrize("delta", [0.5, 1.0, 2.0])
def test_huber_loss_forward_backward(seed, ctx, func_name, delta):
    from nbla_test_utils import function_tester
    rng = np.random.RandomState(seed)
    inputs = [rng.randn(2, 3, 4).astype(np.float32) * 2 for _ in range(2)]
    function_tester(rng, F.huber_loss, ref_huber_loss, inputs,
                    func_args=[delta],
                    atol_b=1e-2, ctx=ctx, func_name=func_name)

@pytest.mark.parametrize("ctx, func_name", ctxs)
@pytest.mark.parametrize("seed", [313])
@pytest.mark.parametrize("delta", [0.5, 1.0, 1.5])
def test_huber_loss_double_backward(seed, ctx, func_name, delta):
    from nbla_test_utils import cap_ignore_region, backward_function_tester
    rng = np.random.RandomState(seed)
    inputs = [rng.randn(2, 3, 4).astype(np.float32) * 2 for _ in range(2)]
    backward_function_tester(rng, F.huber_loss, inputs,
                             func_args=[delta],
                             atol_accum=1e-2, ctx=ctx)


text:
LeagueSharpUP
===================

This is a copy of LeagueSharp UI.
When i fully finish this project i will edit this file with all data you need to know about project, but for now i will just edit pictures showing you progress of project.
Everyone who wants to help me can contact me via facebook profile: [Click](https://www.facebook.com/vuzimir.samp1)

Picutres
===================

Starup![enter image description here](http://i.imgur.com/EkW23CP.png)
Settings
![enter image description here](http://i.imgur.com/Nm6weP7.png)
MsgBox
![enter image description here](http://i.imgur.com/FzwKe1J.png)
Main Page
![enter image description here](http://i.imgur.com/HWEuzIZ.png)


text:
<?php
/**
 * Created by PhpStorm.
 * User: florian
 * Date: 24/03/15
 * Time: 10:54
 */

namespace eLearn\Bundle\learnBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class LessonType extends AbstractType {
    public function buildForm(FormBuilderInterface $builder , array $options)
    {
        $builder->add('Title');
        $builder->add('content');
        $builder->add('save', 'submit');

    }
    public function  getName()
    {
        return 'title';
    }
}


text:
"""
# Пример 3.8

Б.Я.Советов, Моделирование систем. Практикум: Учеб пособие для вузов/
Б.Я. Советов, С.А. Яковлев.- 2-е изд., перераб. и доп.-М.:Высш. шк., 2003.-295 с.: ил.

В систему массового обслуживания поступают пакеты заявок по равномерному
закону в интервале 5+/- 2 мин.

Обработка заявок осуществляется в одном из четырёх каналов обслуживания,
для которых времена обслуживания составляют:
17+/-2 мин,
12+/-2 мин,
9+/-2 мин,
3+/-2 мин
соответственно.

Необходимо смоделировать работу системы по обработке 100 заявок четырьмя каналами,
когда вновь поступающая заявка обслуживается любым свободным каналом.
------

"""

import sys
import os
import random
import unittest

DIRNAME_MODULE = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))))) + os.sep
sys.path.append(DIRNAME_MODULE)
sys.path.append(DIRNAME_MODULE + "pyss" + os.sep)

from pyss import pyssobject
from pyss.pyss_model import PyssModel
from pyss.segment import Segment

from pyss import generate
from pyss.generate import Generate
from pyss.terminate import Terminate
from pyss import logger
from pyss.table import Table
from pyss.assemble import Assemble
from pyss.qtable import Qtable
from pyss.handle import Handle
from pyss.enter import Enter
from pyss.leave import Leave
from pyss.storage import Storage
from pyss.advance import Advance
from pyss.assign import Assign
from pyss.preempt import Preempt
from pyss.g_return import GReturn
from pyss.facility import Facility
from pyss.seize import Seize
from pyss.release import Release
from pyss.transfer import Transfer
from pyss.tabulate import Tabulate
from pyss.test import Test
from pyss.queue import Queue
from pyss.depart import Depart
from pyss.split import Split
from pyss.test import Test
from pyss.bprint import Bprint
from pyss.gate import Gate
from pyss.pyss_const import *

from pyss.func_discrete import FuncDiscrete
from pyss.func_exponential import Exponential
from pyss.func_normal import Normal
from pyss.plot_func import PlotFunc

from pyss.simpleobject import SimpleObject

def buildModel():
    logger.info("-------------------------------------")

    ### MODEL ----------------------------------
    m = PyssModel()
    sgm = Segment(m)

    #
    m[OPTIONS].setAllFalse()
    m[OPTIONS].printResult = True

    #-----------------------------
    def modificatorFunc001(owner, currentTime):
        return random.uniform(-2.0, 2.0)
    Generate(sgm,
             med_value=5, modificatorFunc=modificatorFunc001,
             first_tx=None,
             max_amount=100,
             priority=1)

    CHAN1 = "CHAN1"
    CHAN2 = "CHAN2"
    CHAN3 = "CHAN3"
    CHAN4 = "CHAN4"
    F1 = "F1"
    F2 = "F2"
    F3 = "F3"
    F4 = "F4"
    TRANSFER001_HANDLER_ON_STATE = "transfer001_handlerOnState"
    def transfer001(o, t):
        f1 = m.findFacility(F1)
        # проверим свободность F1
        if f1.isFree():
            # переход в первый канал
            return m.findBlockByLabel(CHAN1)
        # F1 занят, проверим свободность F2
        f2 = m.findFacility(F2)
        # проверим свободность F1
        if f2.isFree():
            # переход во второй канал
            return m.findBlockByLabel(CHAN2)
        # F1 занят, проверим свободность F2
        f3 = m.findFacility(F3)
        # проверим свободность F1
        if f3.isFree():
            # переход во второй канал
            return m.findBlockByLabel(CHAN3)
        # F1 занят, проверим свободность F2
        f4 = m.findFacility(F4)
        # проверим свободность F1
        if f4.isFree():
            # переход во второй канал
            return m.findBlockByLabel(CHAN4)
        # каналы заняты,
        # транзакт в список задержки, ключ блок transfer
        hazh = str(o)
        m.appendToDelayedList(hazh, t)

        # если какналы освободятся, то вернуть из списка задержанных
        # добавим обработчики освобождения
        if not m.existsHandlerOnStateChange(TRANSFER001_HANDLER_ON_STATE):
            # обработчик события изменения состояний f1 и f2 (см. PyssStateObject)
            def transfer001_handlerOnState(obj, oldState):
                if obj.isFree():
                    t = m.extractFromDelayedListFirst(hazh)
                    if t is not None:
                        m.getCel().put(t)
            f1.addHandlerOnStateChange(TRANSFER001_HANDLER_ON_STATE, transfer001_handlerOnState)
            f2.addHandlerOnStateChange(TRANSFER001_HANDLER_ON_STATE, transfer001_handlerOnState)
            f3.addHandlerOnStateChange(TRANSFER001_HANDLER_ON_STATE, transfer001_handlerOnState)
            f4.addHandlerOnStateChange(TRANSFER001_HANDLER_ON_STATE, transfer001_handlerOnState)
        # это не влияет, транзакт в задержке
        return None

    Transfer(sgm, funcTransfer=transfer001)
    #
    Seize(sgm, CHAN1, facilityName=F1)
    Advance(sgm, meanTime=17.0, modificatorFunc=3.0)
    Release(sgm, facilityName=F1)
    EXIT = "EXIT"
    Transfer(sgm, funcTransfer=EXIT)
    #
    Seize(sgm, CHAN2, facilityName=F2)
    Advance(sgm, meanTime=12.0, modificatorFunc=2.0)
    Release(sgm, facilityName=F2)
    Transfer(sgm, funcTransfer=EXIT)
    #
    Seize(sgm, CHAN3, facilityName=F3)
    Advance(sgm, meanTime=9.0, modificatorFunc=2.0)
    Release(sgm, facilityName=F3)
    Transfer(sgm, funcTransfer=EXIT)
    #
    Seize(sgm, CHAN4, facilityName=F4)
    Advance(sgm, meanTime=3.0, modificatorFunc=2.0)
    Release(sgm, facilityName=F4)
    Transfer(sgm, funcTransfer=EXIT)
    #
    Terminate(sgm, EXIT, deltaTerminate=1)

    return m

def main():
    logger.info("-------------------------------------")

    #-------------------------------
    # Время моделирования
    MAX_TIME = 10000

    ### MODEL ----------------------------------
    m = buildModel()

    ### КАРТИНКИ ----------------------
    # таблицы
#     m.initPlotTable()
#     m.initPlotQueueLifeLine()
#     m.initPlotTransactLifeLine()
#     m.initPlotFacilityLifeLine()

    # РАСЧЁТ --------------------------
    m.start(terminationCount=100, maxTime=MAX_TIME)

    # ПОКАЗ КАРТИНОК ------------------------
    # m.getPlotSubsystem().plotByModules()
    # m.getPlotSubsystem().show()

if __name__ == '__main__':
    main()


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

<!-- See http://www.jboss.org/community/wiki/Multiple1PC for information about local-tx-datasource -->
<!-- $Id: mysql-ds.xml 97536 2009-12-08 14:05:07Z jesper.pedersen $ -->
<!--  Datasource config for MySQL using 3.0.9 available from:
http://www.mysql.com/downloads/api-jdbc-stable.html
-->

<datasources>
  <local-tx-datasource>
    <jndi-name>SgiusaDS</jndi-name>
    <connection-url>jdbc:mysql://localhost:3306/sgiusadb</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>manager</user-name>
    <password>manager</password>

    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <!-- should only be used on drivers after 3.22.1 with "ping" support
    <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
    -->
    <!-- sql to call when connection is created
    <new-connection-sql>some arbitrary sql</new-connection-sql>
      -->
    <!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
    <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
      -->

    <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>

  <local-tx-datasource>
    <jndi-name>SgiusaOrigDS</jndi-name>
    <connection-url>jdbc:mysql://localhost:3306/sgiusaorigdb</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>root</user-name>
    <password></password>

    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <!-- should only be used on drivers after 3.22.1 with "ping" support
    <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
    -->
    <!-- sql to call when connection is created
    <new-connection-sql>some arbitrary sql</new-connection-sql>
      -->
    <!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers
    <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
      -->

    <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>


text:
--CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE SCHEMA rl;

CREATE TABLE IF NOT EXISTS rl.config (
  key VARCHAR(64) UNIQUE NOT NULL,
  value TEXT
);

CREATE TABLE IF NOT EXISTS rl.account (
  account_id UUID PRIMARY KEY,
	email VARCHAR(100) UNIQUE NOT NULL,
  username VARCHAR(30) UNIQUE NOT NULL,
  hash TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS rl.pending_account (
  pending_id SERIAL PRIMARY KEY,
  code VARCHAR(32) NOT NULL,
  email VARCHAR(100) UNIQUE NOT NULL,

  -- Records will expire after some duration.
  ts TIMESTAMP NOT NULL
);

-- A new salt is created periodically and the oldest removed.
-- There are always exactly 2 records in this table.
CREATE TABLE IF NOT EXISTS rl.salt (
  salt TEXT UNIQUE NOT NULL,
  ts TIMESTAMP NOT NULL
);


text:
#ifndef MEM_PRIVATE_H
#define MEM_PRIVATE_H

void mem_init();

//system memory pool. Only in supervisor context
void* sys_alloc(int size);
void* sys_alloc_aligned(int size, int align);
void sys_free(void* ptr);

//allocate stack for thread. Only in supervisor context
void* stack_alloc(int size);
void stack_free(void* ptr);

unsigned int svc_mem_handler(unsigned int num, unsigned int param1, unsigned int param2);

#endif // MEM_PRIVATE_H


text:
__author__ = 'jcorbett'

import glob
import os

# this little gem will import every .py file in this directory
# the advantage is that we can just import slickqaweb.model.systemConfiguration and all the
# types will be added to types.allTypes

compile_steps_path = os.path.dirname(__file__)
compile_steps_path_length = len(compile_steps_path)

modules = []
for name in glob.glob(os.path.join(compile_steps_path,'*.py')):
    if not name.endswith('__init__.py'):
        modules.append(name[compile_steps_path_length + 1:-3])

modules.sort()
for module in modules:
    __import__("slickqaweb.model.systemConfiguration", globals(), locals(), fromlist=[module,])

from .types import AllTypes as SystemConfigurationTypes

import mongoengine
import bson

class BaseSystemConfiguration(mongoengine.DynamicDocument):
    meta = {'collection': 'system-configurations'}
    configurationType = mongoengine.StringField()

    dynamic_types = {
        'typeName': mongoengine.StringField()
    }

def load_system_configuration_type(id):
    assert isinstance(id, bson.ObjectId)
    return BaseSystemConfiguration.objects(id=id).first().configurationType


text:
set -euxo pipefail

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )

# Delete the default catalog if it exists
sh -c "kubectl delete catalogsources operatorhubio-catalog -n olm | true"

kubectl apply -f $SCRIPT_DIR/../olm/testing-resources/catalog.yaml

# Wait for the catalog to be healthy
max_retries=200
c=0
while [[ $(kubectl get catalogsources test-catalog -o jsonpath="{.status.connectionState.lastObservedState}") != "READY" ]]
do
  echo "waiting for the test-catalog to be ready"
  ((c++)) && ((c==max_retries)) && exit -1
  sleep 1
done

kubectl apply -f $SCRIPT_DIR/../olm/testing-resources/operatorgroup.yaml
kubectl apply -f $SCRIPT_DIR/../olm/testing-resources/subscription.yaml


text:
module Twig
  class TokenParser::If < Twig::TokenParser

    # {% if <expression> %}
    # ...
    # {% elseif <expression>%}
    # ...
    # {% else %}
    # ...
    # {% endif %}
    def parse(token)
      lineno = token.lineno
      expr = @parser.expression_parser.parse_expression
      stream = @parser.stream
      stream.expect(:block_end_type)
      body = @parser.subparse([self, :decide_if_fork])
      tests = [expr, body]
      _else = nil
      _end = false
      until _end
        case stream.next.value
        when 'else'.freeze
          stream.expect(:block_end_type)
          _else = @parser.subparse([self, :decide_if_end])
        when 'elseif'.freeze
          expr = @parser.expression_parser.parse_expression
          stream.expect(:block_end_type)
          body = @parser.subparse([self, :decide_if_fork])
          tests << expr << body
        when 'endif'.freeze
          _end = true
        else
          raise Twig::Error::Syntax.new("Unexpected end of template. Twig was looking for the following tags \"else\", \"elseif\", or \"endif\" to close the \"if\" block started at line #{lineno}).", stream.current_token.lineno, stream.filename)
        end
      end
      stream.expect(:block_end_type)
      Twig::Node::If.new(Twig::Node.new(tests), _else, lineno, tag)
    end

    def decide_if_fork(token)
      token.check(['elseif'.freeze, 'else'.freeze, 'endif'.freeze])
    end

    def decide_if_end(token)
      token.check(['endif'.freeze])
    end

    def tag
      'if'.freeze
    end

  end
end


text:
package com.googlecode.kanbanik.client.components.task;

import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.ui.SuggestBox.DefaultSuggestionDisplay;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.googlecode.kanbanik.client.api.Dtos;
import com.googlecode.kanbanik.client.api.ResourceClosingCallback;
import com.googlecode.kanbanik.client.api.ServerCaller;
import com.googlecode.kanbanik.client.components.DatePickerDialog;
import com.googlecode.kanbanik.client.components.ListBoxWithAddEditDelete;
import com.googlecode.kanbanik.client.components.PanelContainingDialog;
import com.googlecode.kanbanik.client.components.PanelContainingDialog.PanelContainingDialolgListener;
import com.googlecode.kanbanik.client.components.common.KanbanikRichTextArea;
import com.googlecode.kanbanik.client.components.task.tag.TagCreatingComponent;
import com.googlecode.kanbanik.client.components.task.tag.TagDeletingComponent;
import com.googlecode.kanbanik.client.components.task.tag.TagEditingComponent;
import com.googlecode.kanbanik.client.managers.ClassOfServicesManager;
import com.googlecode.kanbanik.client.managers.UsersManager;
import com.googlecode.kanbanik.client.messaging.MessageBus;
import com.googlecode.kanbanik.client.messaging.messages.task.ChangeTaskSelectionMessage;
import com.googlecode.kanbanik.client.messaging.messages.task.TaskAddedMessage;
import com.googlecode.kanbanik.client.messaging.messages.task.TaskEditedMessage;
import com.googlecode.kanbanik.client.security.CurrentUser;
import com.googlecode.kanbanik.dto.CommandNames;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.googlecode.kanbanik.client.api.Dtos.ClassOfServiceDto;
import static com.googlecode.kanbanik.client.api.Dtos.TaskDto;

// TODO it start to look really ugly - needs to be cleaned up into ui.xml
public abstract class AbstractTaskEditingComponent {

    private Panel panel;

    private TextArea taskName;

    private Label ticketId;

    private KanbanikRichTextArea description;

    private SuggestBox assigneeEditor;

    private SuggestBox classOfServiceEditor;

    private CheckBox dueDateCheckBox;

    private TextBox dueDateTextBox;

    private ListBoxWithAddEditDelete<Dtos.TaskTag> tagsEditor;

    private PanelContainingDialog dialog;

    private HTML warningMessages;

    private Panel taskDirtyWarningPanel;

    private String name;

    private Map<String, ClassOfServiceDto> classOfServiceToName;

    private Map<String, Dtos.UserDto> userToName;

    private Dtos.BoardDto board;

    private boolean inited = false;
    private Dtos.BoardDto boardDto;

    public AbstractTaskEditingComponent(HasClickHandlers clickHandler, Dtos.BoardDto board) {
        this.name = "Task Details";
        this.board = board;

        clickHandler.addClickHandler(new ShowDialogHandler());
    }

    private void initialize() {
        panel = new FlowPanel();
        taskName = new TextArea();
        ticketId = new Label("");
        dueDateCheckBox = new CheckBox();
        dueDateTextBox = new TextBox();

        tagsEditor = createTagBox();

        warningMessages = new HTML();

        taskDirtyWarningPanel = initTaskDirtyWarningPanel();
        dialog = new PanelContainingDialog(name, panel, taskName, true, 970, 500);

        classOfServiceEditor = new PanelContainingDialogSuggestBox(new MultiWordSuggestOracle(), dialog);
        initSuggestBox(classOfServiceEditor);

        assigneeEditor = new PanelContainingDialogSuggestBox(new MultiWordSuggestOracle(), dialog);
        initSuggestBox(assigneeEditor);

        description = new KanbanikRichTextArea();

        Grid header = new Grid(5, 2);
        header.setWidget(0, 0, new Label("ID"));
        header.setWidget(0, 1, ticketId);

        taskName.setWidth("190px");
        taskName.setHeight("120px");
        taskName.getElement().getStyle().setProperty("resize", "vertical");

        header.setWidget(1, 0, new Label("Short Description"));
        header.setWidget(1, 1, taskName);

        header.setWidget(2, 0, new Label("Class of service"));
        header.setWidget(2, 1, classOfServiceEditor);

        header.setWidget(3, 0, new Label("Assignee"));
        header.setWidget(3, 1, assigneeEditor);

        header.setWidget(4, 0, new Label("Due Date"));

        header.setWidget(4, 1, createDueDatePanel());

        header.setWidth("100%");
        header.getElement().getStyle().setPaddingRight(10, Style.Unit.PX);

        warningMessages.getElement().getStyle().setColor("red");

        FlowPanel controlPanel = new FlowPanel();
        controlPanel.setWidth("100%");
        controlPanel.setHeight("100%");
        controlPanel.getElement().getStyle().setProperty("display", "flex");
        controlPanel.getElement().getStyle().setProperty("flexDirection", "row");
        FlowPanel aroundHeader = new FlowPanel();
        aroundHeader.add(taskDirtyWarningPanel);
        aroundHeader.add(header);
        aroundHeader.add(tagsEditor);
        aroundHeader.setWidth("460px");
        controlPanel.add(aroundHeader);
        controlPanel.add(description);

        panel.add(controlPanel);
        panel.add(warningMessages);
        panel.setWidth("100%");

        dialog.addListener(new AddTaskButtonHandler());
    }

    protected Panel initTaskDirtyWarningPanel() {
        return new FlowPanel();
    }

    private Map<String, ClassOfServiceDto> initClassOfServiceToName(List<ClassOfServiceDto> classesOfService) {
        Map<String, ClassOfServiceDto> res = new HashMap<String, ClassOfServiceDto>();
        for (ClassOfServiceDto classOfService : classesOfService) {
            res.put(classOfService.getName(), classOfService);
        }

        return res;
    }

    private Map<String, Dtos.UserDto> initUserToName(List<Dtos.UserDto> users) {
        Map<String, Dtos.UserDto> res = new HashMap<String, Dtos.UserDto>();
        for (Dtos.UserDto user : users) {
            res.put(user.getUserName(), user);
        }

        return res;
    }

    private Panel createDueDatePanel() {
        final DialogBox datePickerDialog = new DatePickerDialog(dueDateTextBox);

        Panel dueDatePanel = new VerticalPanel();
        dueDatePanel.add(dueDateCheckBox);
        dueDatePanel.add(dueDateTextBox);
        dueDateCheckBox.setValue(false);
        dueDateCheckBox.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                dueDateTextBox.setVisible(dueDateCheckBox.getValue());
            }
        });
        dueDateTextBox.setVisible(false);

        dueDateTextBox.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                datePickerDialog.show();
            }
        });
        return dueDatePanel;
    }

    private void fillOracle(Map<String, String> suggestions, MultiWordSuggestOracle oracle) {
        oracle.addAll(suggestions.keySet());

        List<Suggestion> defaults = new ArrayList<Suggestion>();
        for (Map.Entry<String, String> suggestion : suggestions.entrySet()) {
            defaults.add(new SimpleSuggestion(suggestion));
        }
        oracle.setDefaultSuggestions(defaults);

    }

    private void initSuggestBox(final SuggestBox suggestBox) {
        suggestBox.getValueBox().addFocusHandler(new FocusHandler() {
            @Override
            public void onFocus(FocusEvent event) {
                suggestBox.showSuggestionList();
            }
        });
    }

    protected void setupValues() {
        ticketId.setText(getTicketId());
        taskName.setValue(getTaskName());
        description.setHtml(getDescription());

        classOfServiceToName = initClassOfServiceToName(ClassOfServicesManager.getInstance().getAllWithNone());
        Map<String, String> classOfServiceSuggestionMap = new HashMap<String, String>();
        for (Map.Entry<String, Dtos.ClassOfServiceDto> entry : classOfServiceToName.entrySet()) {
            // enough, no need for description...
            classOfServiceSuggestionMap.put(entry.getKey(), entry.getKey());
        }
        fillOracle(classOfServiceSuggestionMap, (MultiWordSuggestOracle) classOfServiceEditor.getSuggestOracle());
        classOfServiceEditor.setValue(getClassOfServiceAsString());

        userToName = initUserToName(UsersManager.getInstance().getUsers());
        Map<String, String> userSuggestionMap = new HashMap<String, String>();
        for (Map.Entry<String, Dtos.UserDto> entry : userToName.entrySet()) {
            userSuggestionMap.put(entry.getKey(), entry.getKey() + " (" + entry.getValue().getRealName() + ")");
        }
        fillOracle(userSuggestionMap, (MultiWordSuggestOracle) assigneeEditor.getSuggestOracle());
        assigneeEditor.setValue(getUser());

        boolean dueDateSet = getDueDate() != null && !"".equals(getDueDate());
        dueDateCheckBox.setValue(dueDateSet);
        dueDateTextBox.setVisible(dueDateSet);
        dueDateTextBox.setText(getDueDate());

        warningMessages.setText("");

        tagsEditor.setContent(getTags());
    }

    private boolean validate() {
        boolean dueDateValid = validateDueDate();
        boolean classOfServiceValid = validateClassOfService();
        boolean assigneeValid = validateAssignee();
        return dueDateValid && classOfServiceValid && assigneeValid;
    }

    private boolean validateClassOfService() {
        if (classOfServiceToName.containsKey(classOfServiceEditor.getText().trim())) {
            return true;
        }

        addWarningMessage("The given class of service is not defined");
        return false;
    }

    private boolean validateAssignee() {
        if (assigneeEditor.getText() == null || "".equals(assigneeEditor.getText())) {
            // empty is OK
            return true;
        }

        if (userToName.containsKey(assigneeEditor.getText().trim())) {
            return true;
        }

        addWarningMessage("The given assignee is not an existing user");
        return false;
    }

    private boolean validateDueDate() {
        if (!dueDateCheckBox.getValue()) {
            return true;
        }

        String dueDateString = dueDateTextBox.getValue();
        try {
            DateTimeFormat.getFormat(PredefinedFormat.DATE_SHORT).parse(dueDateString);
            return true;
        } catch (IllegalArgumentException e) {
            addWarningMessage("Accepted date format is YYYY-MM-DD");
            return false;
        }

    }

    private void addWarningMessage(String msg) {
        warningMessages.setHTML(SafeHtmlUtils.fromTrustedString(warningMessages.getHTML() + msg + "</br>"));
    }

    protected abstract String getClassOfServiceAsString();

    protected abstract String getUser();

    protected abstract String getTicketId();

    protected abstract String getTaskName();

    protected abstract String getDescription();

    protected abstract String getId();

    protected abstract int getVersion();

    protected abstract TaskDto createBasicDTO();

    protected abstract List<Dtos.TaskTag> getTags();

    private TaskDto createTaskDTO() {
        TaskDto taskDto = createBasicDTO();
        taskDto.setName(taskName.getText());
        taskDto.setDescription(description.getHtml());
        ClassOfServiceDto selectedClassOfService = classOfServiceToName.get(classOfServiceEditor.getValue().trim());
        if (ClassOfServicesManager.getInstance().getDefaultClassOfService().getName().equals(selectedClassOfService.getName())) {
            selectedClassOfService = null;
        }

        taskDto.setClassOfService(selectedClassOfService);
        Dtos.UserDto newUser = userToName.get(assigneeEditor.getValue().trim());
        if (newUser != null) {
            taskDto.setAssignee(newUser);
        } else {
            taskDto.setAssignee(null);
        }

        if (dueDateCheckBox.getValue()) {
            taskDto.setDueDate(dueDateTextBox.getText().trim());
        } else {
            taskDto.setDueDate("");
        }
        taskDto.setId(getId());
        taskDto.setVersion(getVersion());
        taskDto.setBoardId(board.getId());

        taskDto.setTaskTags(tagsEditor.getContent());

        return taskDto;
    }

    protected abstract String getDueDate();

    public void setBoardDto(Dtos.BoardDto boardDto) {
        this.board = boardDto;
    }

    class ShowDialogHandler implements ClickHandler {

        public void onClick(ClickEvent event) {
            event.stopPropagation();
            event.preventDefault();

            if (!inited) {
                initialize();
                inited = true;
            }

            onClicked();
        }

    }

    protected void onClicked() {
        doSetupAndShow();
    }

    protected void doSetupAndShow() {
        GlobalKeyListener.INSTANCE.stop();
        setupValues();
        dialog.center();
        taskName.setFocus(true);
    }

    class AddTaskButtonHandler implements PanelContainingDialolgListener {

        public void okClicked(final PanelContainingDialog dialog) {

            warningMessages.setText("");
            if (!validate()) {
                return;
            }

            final TaskDto taskDto = createTaskDTO();
            taskDto.setSessionId(CurrentUser.getInstance().getSessionId());

            final boolean isNew = taskDto.getId() == null;
            final CommandNames commandName = isNew ? CommandNames.CREATE_TASK : CommandNames.EDIT_TASK;
            taskDto.setCommandName(commandName.name);

            ServerCaller.<TaskDto, TaskDto>sendRequest(
                    taskDto,
                    TaskDto.class,
                    new ResourceClosingCallback<TaskDto>(dialog) {

                        @Override
                        public void success(TaskDto response) {
                            onHideDialog();
                            if (isNew) {
                                MessageBus.sendMessage(new TaskAddedMessage(response, AbstractTaskEditingComponent.this));
                            } else {
                                MessageBus.sendMessage(new TaskEditedMessage(response, AbstractTaskEditingComponent.this));
                            }
                        }
                    }
            );
        }

        public void cancelClicked(PanelContainingDialog dialog) {
            onHideDialog();
        }

    }

    protected void onHideDialog() {
        MessageBus.sendMessage(ChangeTaskSelectionMessage.deselectAll(this));
        GlobalKeyListener.INSTANCE.initialize();
    }

    class SimpleSuggestion implements Suggestion {

        private Map.Entry<String, String> entry;

        public SimpleSuggestion(Map.Entry<String, String> entry) {
            this.entry = entry;
        }

        @Override
        public String getDisplayString() {
            return entry.getValue();
        }

        @Override
        public String getReplacementString() {
            return entry.getKey();
        }

    }

    class PanelContainingDialogSuggestDisplay extends DefaultSuggestionDisplay {

        private PanelContainingDialog dialog;

        public PanelContainingDialogSuggestDisplay(PanelContainingDialog dialog) {
            super();
            this.dialog = dialog;
        }

        public void hideSuggestions() {
            super.hideSuggestions();
            dialog.activateEnterEscapeBinding();
        }
    }

    class PanelContainingDialogSuggestBox extends SuggestBox {

        private PanelContainingDialog dialog;

        public PanelContainingDialogSuggestBox(SuggestOracle oracle, PanelContainingDialog dialog) {
            super(oracle, new TextBox(), new PanelContainingDialogSuggestDisplay(dialog));
            this.dialog = dialog;
        }

        @Override
        public void showSuggestionList() {
            super.showSuggestionList();
            dialog.deactivateEnterEscapeBinding();
        }
    }

    private ListBoxWithAddEditDelete<Dtos.TaskTag> createTagBox() {
        TagCreatingComponent tagCreatingComponent = new TagCreatingComponent();
        TagEditingComponent tagEditingComponent = new TagEditingComponent();
        TagDeletingComponent tagDeletingComponent = new TagDeletingComponent();

        ListBoxWithAddEditDelete<Dtos.TaskTag> listBox = new ListBoxWithAddEditDelete<Dtos.TaskTag>(
                "Tags",

                new ListBoxWithAddEditDelete.IdProvider<Dtos.TaskTag>() {
                    @Override
                    public String getId(Dtos.TaskTag taskTag) {
                        // not nice but nothing more unique around...
                        return taskTag.toString();
                    }
                },

                new ListBoxWithAddEditDelete.LabelProvider<Dtos.TaskTag>() {
                    @Override
                    public String getLabel(Dtos.TaskTag taskTag) {
                        return taskTag.getName();
                    }
                },

                tagCreatingComponent,
                tagEditingComponent,
                tagDeletingComponent,
                new ListBoxWithAddEditDelete.Refresher<Dtos.TaskTag>() {
                    @Override
                    public void refrehs(List<Dtos.TaskTag> items, Dtos.TaskTag newItem, int index) {
                        items.set(index, newItem);
                    }
                }
        );

        tagCreatingComponent.setParent(listBox);
        tagEditingComponent.setParent(listBox);
        tagDeletingComponent.setParent(listBox);

        return listBox;
    }

}