text:
require "spec_helper"

describe "an instance generated by a factory with multiple traits" do
  before do
    define_model("User",
                 :name          => :string,
                 :admin         => :boolean,
                 :gender        => :string,
                 :email         => :string,
                 :date_of_birth => :date,
                 :great         => :string)

    FactoryGirl.define do
      factory :user_without_admin_scoping, :class => User do
        admin_trait
      end

      factory :user do
        name "John"

        trait :great do
          great "GREAT!!!"
        end

        trait :admin do
          admin true
        end

        trait :admin_trait do
          admin true
        end

        trait :male do
          name   "Joe"
          gender "Male"
        end

        trait :female do
          name   "Jane"
          gender "Female"
        end

        factory :great_user do
          great
        end

        factory :admin, :traits => [:admin]

        factory :male_user do
          male

          factory :child_male_user do
            date_of_birth { Date.parse("1/1/2000") }
          end
        end

        factory :female, :traits => [:female] do
          trait :admin do
            admin true
            name "Judy"
          end

          factory :female_great_user do
            great
          end

          factory :female_admin_judy, :traits => [:admin]
        end

        factory :female_admin,            :traits => [:female, :admin]
        factory :female_after_male_admin, :traits => [:male, :female, :admin]
        factory :male_after_female_admin, :traits => [:female, :male, :admin]
      end

      trait :email do
        email { "#{name}@example.com" }
      end

      factory :user_with_email, :class => User, :traits => [:email] do
        name "Bill"
      end
    end
  end

  context "the parent class" do
    subject      { FactoryGirl.create(:user) }
    its(:name)   { should == "John" }
    its(:gender) { should be_nil }
    it           { should_not be_admin }
  end

  context "the child class with one trait" do
    subject      { FactoryGirl.create(:admin) }
    its(:name)   { should == "John" }
    its(:gender) { should be_nil }
    it           { should be_admin }
  end

  context "the other child class with one trait" do
    subject      { FactoryGirl.create(:female) }
    its(:name)   { should == "Jane" }
    its(:gender) { should == "Female" }
    it           { should_not be_admin }
  end

  context "the child with multiple traits" do
    subject      { FactoryGirl.create(:female_admin) }
    its(:name)   { should == "Jane" }
    its(:gender) { should == "Female" }
    it           { should be_admin }
  end

  context "the child with multiple traits and overridden attributes" do
    subject      { FactoryGirl.create(:female_admin, :name => "Jill", :gender => nil) }
    its(:name)   { should == "Jill" }
    its(:gender) { should be_nil }
    it           { should be_admin }
  end

  context "the child with multiple traits who override the same attribute" do
    context "when the male assigns name after female" do
      subject      { FactoryGirl.create(:male_after_female_admin) }
      its(:name)   { should == "Joe" }
      its(:gender) { should == "Male" }
      it           { should be_admin }
    end

    context "when the female assigns name after male" do
      subject      { FactoryGirl.create(:female_after_male_admin) }
      its(:name)   { should == "Jane" }
      its(:gender) { should == "Female" }
      it           { should be_admin }
    end
  end

  context "child class with scoped trait and inherited trait" do
    subject      { FactoryGirl.create(:female_admin_judy) }
    its(:name)   { should == "Judy" }
    its(:gender) { should == "Female" }
    it           { should be_admin }
  end

  context "factory using global trait" do
    subject     { FactoryGirl.create(:user_with_email) }
    its(:name)  { should == "Bill" }
    its(:email) { should == "Bill@example.com"}
  end

  context "factory created with alternate syntax for specifying trait" do
    subject      { FactoryGirl.create(:male_user) }
    its(:gender) { should == "Male" }
  end

  context "factory created with alternate syntax where trait name and attribute are the same" do
    subject     { FactoryGirl.create(:great_user) }
    its(:great) { should == "GREAT!!!" }
  end

  context "factory created with alternate syntax where trait name and attribute are the same and attribute is overridden" do
    subject     { FactoryGirl.create(:great_user, :great => "SORT OF!!!") }
    its(:great) { should == "SORT OF!!!" }
  end

  context "child factory created where trait attributes are inherited" do
    subject             { FactoryGirl.create(:child_male_user) }
    its(:gender)        { should == "Male" }
    its(:date_of_birth) { should == Date.parse("1/1/2000") }
  end

  context "factory outside of scope" do
    subject     { FactoryGirl.create(:user_without_admin_scoping) }
    it { expect { subject }.to raise_error(ArgumentError, "Trait not registered: admin_trait") }
  end

  context "child factory using grandparents' trait" do
    subject     { FactoryGirl.create(:female_great_user) }
    its(:great) { should == "GREAT!!!" }
  end
end

describe "traits with callbacks" do
  before do
    define_model("User", :name => :string)

    FactoryGirl.define do
      factory :user do
        name "John"

        trait :great do
          after_create {|user| user.name.upcase! }
        end

        trait :awesome do
          after_create {|user| user.name = "awesome" }
        end

        factory :caps_user, :traits => [:great]
        factory :awesome_user, :traits => [:great, :awesome]

        factory :caps_user_implicit_trait do
          great
        end
      end
    end
  end

  context "when the factory has a trait passed via arguments" do
    subject    { FactoryGirl.create(:caps_user) }
    its(:name) { should == "JOHN" }
  end

  context "when the factory has an implicit trait" do
    subject    { FactoryGirl.create(:caps_user_implicit_trait) }
    its(:name) { should == "JOHN" }
  end

  it "executes callbacks in the order assigned" do
    FactoryGirl.create(:awesome_user).name.should == "awesome"
  end
end

describe "traits added via strategy" do
  before do
    define_model("User", :name => :string, :admin => :boolean)

    FactoryGirl.define do
      factory :user do
        name "John"

        trait :admin do
          admin true
        end

        trait :great do
          after_create {|user| user.name.upcase! }
        end
      end
    end
  end

  context "adding traits in create" do
    subject { FactoryGirl.create(:user, :admin, :great, :name => "Joe") }

    its(:admin) { should be_true }
    its(:name)  { should == "JOE" }

    it "doesn't modify the user factory" do
      subject
      FactoryGirl.create(:user).should_not be_admin
      FactoryGirl.create(:user).name.should == "John"
    end
  end

  context "adding traits in build" do
    subject { FactoryGirl.build(:user, :admin, :great, :name => "Joe") }

    its(:admin) { should be_true }
    its(:name)  { should == "Joe" }
  end

  context "adding traits in attributes_for" do
    subject { FactoryGirl.attributes_for(:user, :admin, :great) }

    its([:admin]) { should be_true }
    its([:name])  { should == "John" }
  end

  context "adding traits in build_stubbed" do
    subject { FactoryGirl.build_stubbed(:user, :admin, :great, :name => "Jack") }

    its(:admin) { should be_true }
    its(:name)  { should == "Jack" }
  end

  context "adding traits in create_list" do
    subject { FactoryGirl.create_list(:user, 2, :admin, :great, :name => "Joe") }

    its(:length) { should == 2 }

    it "creates all the records" do
      subject.each do |record|
        record.admin.should be_true
        record.name.should == "JOE"
      end
    end
  end

  context "adding traits in build_list" do
    subject { FactoryGirl.build_list(:user, 2, :admin, :great, :name => "Joe") }

    its(:length) { should == 2 }

    it "builds all the records" do
      subject.each do |record|
        record.admin.should be_true
        record.name.should == "Joe"
      end
    end
  end
end

describe "traits and dynamic attributes that are applied simultaneously" do
  before do
    define_model("User", :name => :string, :email => :string, :combined => :string)

    FactoryGirl.define do
      trait :email do
        email { "#{name}@example.com" }
      end

      factory :user do
        name "John"
        email
        combined { "#{name} <#{email}>" }
      end
    end
  end

  subject        { FactoryGirl.build(:user) }
  its(:name)     { should == "John" }
  its(:email)    { should == "John@example.com" }
  its(:combined) { should == "John <John@example.com>" }
end

describe "applying inline traits" do
  before do
    define_model("User") do
      has_many :posts
    end

    define_model("Post", :user_id => :integer) do
      belongs_to :user
    end

    FactoryGirl.define do
      factory :user do
        trait :with_post do
          posts { [ Post.new ] }
        end
      end
    end
  end

  it "applies traits only to the instance generated for that call" do
    FactoryGirl.create(:user, :with_post).posts.should_not be_empty
    FactoryGirl.create(:user).posts.should be_empty
    FactoryGirl.create(:user, :with_post).posts.should_not be_empty
  end
end

describe "inline traits overriding existing attributes" do
  before do
    define_model("User", :status => :string)

    FactoryGirl.define do
      factory :user do
        status "pending"

        trait(:accepted) { status "accepted" }
        trait(:declined) { status "declined" }

        factory :declined_user, :traits => [:declined]
        factory :extended_declined_user, :traits => [:declined] do
          status "extended_declined"
        end
      end
    end
  end

  it "returns the default status" do
    FactoryGirl.build(:user).status.should == "pending"
  end

  it "prefers inline trait attributes over default attributes" do
    FactoryGirl.build(:user, :accepted).status.should == "accepted"
  end

  it "prefers traits on a factory over default attributes" do
    FactoryGirl.build(:declined_user).status.should == "declined"
  end

  it "prefers inline trait attributes over traits on a factory" do
    FactoryGirl.build(:declined_user, :accepted).status.should == "accepted"
  end

  it "prefers attributes on factories over attributes from non-inline traits" do
    FactoryGirl.build(:extended_declined_user).status.should == "extended_declined"
  end

  it "prefers inline traits over attributes on factories" do
    FactoryGirl.build(:extended_declined_user, :accepted).status.should == "accepted"
  end

  it "prefers overridden attributes over attributes from traits, inline traits, or attributes on factories" do
    FactoryGirl.build(:extended_declined_user, :accepted, :status => "completely overridden").status.should == "completely overridden"
  end
end

describe "making sure the factory is properly compiled the first time we want to instantiate it" do
  before do
    define_model("User", :role => :string, :gender => :string, :age => :integer)

    FactoryGirl.define do
      factory :user do
        trait(:female) { gender "female" }
        trait(:admin) { role "admin" }

        factory :female_user do
          female
        end
      end
    end
  end

  it "can honor traits on the very first call" do
    user = FactoryGirl.build(:female_user, :admin, :age => 30)
    user.gender.should == 'female'
    user.age.should == 30
    user.role.should == 'admin'
  end
end


text:
package org.quantintel.ql.instruments.options

/**
 * Dividend Vanilla Option is a Single-asset vanilla option (no barries) with
 * discrete dividends.
 *
 * @author Paul Bernard
 */
class DividendVanillaOption {

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:id="@+id/text"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="48dip"
    android:background="?attr/selectableItemBackground"
    android:gravity="center_vertical"
    android:paddingLeft="16dip"
    android:paddingRight="16dip"
    android:textAppearance="@style/TextAppearance.AppCompat.Subhead"
    tools:text="Subregion Header"
    >

</TextView>


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('api', '0012_problemassignment_done_at'),
    ]

    operations = [
        migrations.CreateModel(
            name='ProblemComment',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('content', models.TextField()),
                ('datetime', models.DateTimeField(auto_now=True, auto_now_add=True)),
                ('problem', models.ForeignKey(related_name='comments', to='api.Problem')),
                ('user', models.ForeignKey(related_name='users', to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
<?php

namespace Newscoop;

/**
 * The datetime object class used in the ArticleDatetime to pass date formats
 * @author mihaibalaceanu
 */
class ArticleDatetime
{
    protected $startDate = null;

    protected $endDate = null;

    protected $startTime = null;

    protected $endTime = null;

    protected $recurring = null;

    protected $spawns = array();

    /**
     * @param mixed $format
     * 		array of start_date, end_date, etc. keys
     * 		array with 1 element: start_date => end_date strings - Date and Time formats: http://php.net/manual/en/datetime.formats.php
     * 		string formatted like above and start separated by end with a - (dash) padded with spaces
     * 		also in case of array you can add recurring => [daily|weekly|etc.]
     * @param string $recurring
     * @todo check start < end
     */
    public function __construct($format, $recurring=null)
    {
        if (is_array($format))
        {
            if (array_key_exists('start_date', $format))
            {
                $this->setStartDate($format['start_date']);
                $this->setEndDate(isset($format['end_date']) ? $format['end_date'] : null);
                $this->setStartTime(isset($format['start_time']) ? $format['start_time'] : null);
                $this->setEndTime(isset($format['end_time']) ? $format['end_time'] : null);
                if (isset($format['recurring'])) {
                    $this->recurring = $format['recurring'];
                }
                return;
            }
            $start = key($format);
            $end = current($format);
        }
        elseif (is_string($format))
        {
            list($start, $end) = explode(" - ", $format);
            if (in_array( ($end = trim($end)), array( '1', '0', 'true', 'false'))) {
                $end = (bool) $end;
            }
        }

        $this->setRecurring($recurring);

        if (!( $startTimestamp = strtotime($start))) {
            return;
        }

        $parsedStart = date_parse($start);
        $startHasDate = $parsedStart['month']!==false && $parsedStart['day']!==false;
        $startHasTime = $parsedStart['hour']!==false && $parsedStart['minute']!==false;

        $startDate = strftime('%F', $startTimestamp);

        switch (true)
        {
            // TODO fix midnight for relative formats
            case is_bool($end) && $end : // full day
                $this->setStartDate($startDate);
                $this->setStartTime($startHasTime ? strftime('%T', $startTimestamp) : null);
                $this->setEndDate(null);
                $this->setEndTime(null);
                break;

            case is_string($end) : // ...until date, or just a single time value for the date

                $parsedEnd = date_parse($end);
                $endHasDate = $parsedEnd['month']!==false && $parsedEnd['day']!==false;
                $endHasTime = $parsedEnd['hour']!==false && $parsedEnd['minute']!==false;

                $end = preg_replace("/-\s*recurring:(\w+)/", "", $end);

                $this->setStartDate($startDate);

                if ($endHasDate) {
                    $this->setEndDate(strftime('%F', strtotime($end)));
                }
                if ($endHasTime && ($parsedEnd['hour']!=0 || $parsedEnd['minute']!=0 || $parsedEnd['second']!=0)) {
                    $this->setEndTime(strftime('%T', strtotime($end)));
                }

                if ($startHasTime && ($parsedStart['hour']!=0 || $parsedStart['minute']!=0 || $parsedStart['second']!=0)) {
                    $this->setStartTime(strftime('%T', strtotime($start)));
                }

                break;

            case is_array($end) : // time interval for current date

                $spawn =& $this;
                foreach ($end as $startTime => $endTime)
                {
                    if ($startTime == 'recurring' ) { // TODO dirty fix for reccuring flag take out
                        continue;
                    }
                    $spawn->setStartDate($startDate);
                    $spawn->setEndDate(null);
                    $spawn->setStartTime(strftime('%T', strtotime($startTime)));
                    $spawn->setEndTime(strftime('%T', strtotime($endTime)));

                    $this->spawns[] = clone $spawn;
                    $spawn =& $this->spawns[count($this->spawns)-1];
                };
                array_pop($this->spawns);
                break;
        }
    }

    /**
     * clears spawns
     */
    public function __clone()
    {
        $this->spawns = array();
    }

    /**
     * @param string $value date format
     */
    public function setStartDate($value)
    {
        $this->startDate = is_null($value) ? null : new \DateTime($value);
    }

    /**
     * @param string $value
     */
    public function setStartTime($value)
    {
        $this->startTime = is_null($value) ? null : new \DateTime($value);
    }

    /**
     * @param string $value
     */
    public function setEndDate($value)
    {
        $this->endDate = is_null($value) ? null : new \DateTime($value);
    }

    /**
     * @param string $value
     */
    public function setEndTime($value)
    {
        $this->endTime = is_null($value) ? null : new \DateTime($value);
    }

    /**
     * @return \DateTime
     */
    public function getStartDate()
    {
        return $this->startDate;
    }

    /**
     * @return \DateTime
     */
    public function getStartTime()
    {
        return $this->startTime;
    }

    /**
     * @return \DateTime
     */
    public function getEndDate()
    {
        return $this->endDate;
    }

    /**
     * @return \DateTime
     */
    public function getEndTime()
    {
        return $this->endTime;
    }

    /**
     * Set recurring flag
     * @param string $value daily|weekly|monthly|yearly
     */
    public function setRecurring($value)
    {
        if (!in_array( $value, array('daily', 'weekly', 'monthly', 'yearly'))) {
            return false;
        }
        $this->recurring = $value;
    }

    /**
     * Get if date object is recurring
     */
    public function getRecurring()
    {
        return $this->recurring;
    }

    /**
     * Get other spawned objects from a contruct
     */
    public function getSpawns()
    {
        return $this->spawns;
    }
}


text:
import React from 'react'
import { screen, fireEvent } from '@testing-library/react'
import { renderWithTheme } from '@looker/components-test-utils'
import { mockLineConfig } from '@looker/visualizations-adapters'
import { Tooltips } from './Tooltips'

afterEach(() => {
  jest.resetAllMocks()
})

describe('Tooltips', () => {
  const handleConfigChange = jest.fn()

  it('hidden when tooltips is unsupported', () => {
    const { container } = renderWithTheme(
      <Tooltips
        config={{ type: 'unsupported' as 'line' }}
        onConfigChange={handleConfigChange}
      />
    )

    expect(container).toBeEmptyDOMElement()
  })

  it('toggles tooltips', () => {
    renderWithTheme(
      <Tooltips
        config={{ ...mockLineConfig, tooltips: true }}
        onConfigChange={handleConfigChange}
      />
    )

    fireEvent.click(screen.getByLabelText('Tooltips'))

    expect(handleConfigChange).toHaveBeenLastCalledWith(
      expect.objectContaining({
        tooltips: false,
      })
    )
  })
})


text:
<!DOCTYPE html>

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">

<title>Timeline</title>

<link type="text/css" media="screen" href="./rdoc.css" rel="stylesheet">

    Home
    Classes
    Methods

  <form action="#" method="get" accept-charset="utf-8">

      <input type="text" name="search" placeholder="Search" id="search-field"
             title="Type to search, Up and Down to navigate, Enter to load">

  </form>

Pages

README

Class and Module Index

Timeline

Timeline::ClassMethods

Timeline::Engine

Timeline::ModelAdditions

Timeline::Railtie

This is the API documentation for Timeline.

[Validate]

Generated by RDoc 3.12.

Generated with the Darkfish Rdoc Generator 3.


text:
<?php
require_once __DIR__.'/../database.php';
use Illuminate\Database\Capsule\Manager as Capsule;

// $sv = new FieldinfoservicelistassetdefaultService();
// $rs = $sv->count();
// var_dump($rs);
// exit();

class FieldinfoservicelistassetdefaultService {

	var $databasename = "fieldlogger";
	var $tablename = "field_infoservicelist_assetdefault";

	var $connection;

	/**
	 * The constructor initializes the connection to database. Everytime a request is
	 * received by Zend AMF, an instance of the service class is created and then the
	 * requested method is invoked.
	 */
	public function __construct() {
	}

	/**
	 * Returns all the rows from the table.
	 *
	 * Add authroization or any logical checks for secure access to your data
	 *
	 * @return array
	 */
	public function getAllField_infoservicelist_assetdefault() {

		$rs  = Capsule::select("SELECT * FROM $this->tablename");
		return $s;
	}

	public function getField_infoservicelist_assetdefaultByslistID($slistID) {

		$rs  = Capsule::select("SELECT     *      FROM field_infoservicelist_assetdefault as adefault       LEFT JOIN field_infotoollist tool ON adefault.adefault_toolID = tool.toolID        WHERE adefault_slistID = ?   ORDER BY adefault.adefaultNo DESC",[$slistID]);
		return $s;
	}
	/**
	 * Returns the item corresponding to the value specified for the primary key.
	 *
	 * Add authorization or any logical checks for secure access to your data
	 *
	 *
	 * @return stdClass
	 */
	public function getField_infoservicelist_assetdefaultByID($itemID) {

		$rs  = Capsule::select("SELECT * FROM $this->tablename where adefaultNo=?",[$itemID]);
		return $s;
	}

	/**
	 * Returns the item corresponding to the value specified for the primary key.
	 *
	 * Add authorization or any logical checks for secure access to your data
	 *
	 *
	 * @return stdClass
	 */
	public function createField_infoservicelist_assetdefault($item) {

		$rs  = Capsule::insert("INSERT INTO $this->tablename (adefaultID, adefault_slistID, adefault_toolID, adefault_serialNo, adefault_1, adefault_2, adefault_3, adefault_4, adefault_5) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",[$item->adefaultID, $item->adefault_slistID, $item->adefault_toolID, $item->adefault_serialNo, $item->adefault_1, $item->adefault_2, $item->adefault_3, $item->adefault_4, $item->adefault_5]);
		return $s;
	}

	/**
	 * Updates the passed item in the table.
	 *
	 * Add authorization or any logical checks for secure access to your data
	 *
	 * @param stdClass $item
	 * @return void
	 */
	public function updateField_infoservicelist_assetdefault($item) {

		$rs  = Capsule::update("UPDATE $this->tablename SET adefaultID=?, adefault_slistID=?, adefault_toolID=?, adefault_serialNo=?, adefault_1=?, adefault_2=?, adefault_3=?, adefault_4=?, adefault_5=? WHERE adefaultNo=?",[$item->adefaultID, $item->adefault_slistID, $item->adefault_toolID, $item->adefault_serialNo, $item->adefault_1, $item->adefault_2, $item->adefault_3, $item->adefault_4, $item->adefault_5, $item->adefaultNo]);
		return $s;
	}

	/**
	 * Deletes the item corresponding to the passed primary key value from
	 * the table.
	 *
	 * Add authorization or any logical checks for secure access to your data
	 *
	 *
	 * @return void
	 */
	public function deleteField_infoservicelist_assetdefault($itemID) {

		$rs  = Capsule::delete("DELETE FROM $this->tablename WHERE adefaultNo = ?",[$itemID]);
		return $s;
	}

	/**
	 * Returns the number of rows in the table.
	 *
	 * Add authorization or any logical checks for secure access to your data
	 *
	 *
	 */
	public function count() {
		$rs  = Capsule::select("SELECT COUNT(*) AS COUNT FROM $this->tablename");
		return (int) $rs[0]['COUNT'];
	}

	/**
	 * Returns $numItems rows starting from the $startIndex row from the
	 * table.
	 *
	 * Add authorization or any logical checks for secure access to your data
	 *
	 *
	 *
	 * @return array
	 */
	public function getField_infoservicelist_assetdefault_paged($startIndex, $numItems) {

		$rs  = Capsule::select("SELECT * FROM $this->tablename LIMIT ?, ?",[$startIndex, $numItems]);
		return $s;
	}

}

?>


text:
using System;

public class QuotesInStrings
{
    static void Main(string[] args)
    {
        string str = "The \"use\" of quotations causes difficulties.";

        Console.WriteLine(str);
    }
}


text:
notification-client
===================

Client for Prowls Notification Server


text:
package org.jboss.netty.example.factorial;

import java.math.BigInteger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.CorruptedFrameException;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

/**
 * Decodes the binary representation of a {@link BigInteger} prepended
 * with a magic number ('F' or 0x46) and a 32-bit integer length prefix into a
 * {@link BigInteger} instance.  For example, { 'F', 0, 0, 0, 1, 42 } will be
 * decoded into new BigInteger("42").
 *
 * @author The Netty Project
 * @author Trustin Lee
 *
 * @version $Rev: 2125 $, $Date: 2010-02-02 12:13:15 +0900 (Tue, 02 Feb 2010) $
 */
public class BigIntegerDecoder extends FrameDecoder {

    @Override
    protected Object decode(
            ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
        // Wait until the length prefix is available.
        if (buffer.readableBytes() < 5) {
            return null;
        }

        buffer.markReaderIndex();

        // Check the magic number.
        int magicNumber = buffer.readUnsignedByte();
        if (magicNumber != 'F') {
            buffer.resetReaderIndex();
            throw new CorruptedFrameException(
                    "Invalid magic number: " + magicNumber);
        }

        // Wait until the whole data is available.
        int dataLength = buffer.readInt();
        if (buffer.readableBytes() < dataLength) {
            buffer.resetReaderIndex();
            return null;
        }

        // Convert the received data into a new BigInteger.
        byte[] decoded = new byte[dataLength];
        buffer.readBytes(decoded);

        return new BigInteger(decoded);
    }
}


text:
import React, { Component } from "react";
import PropTypes from "prop-types";
import {
    Image,
    ScrollView,
    StyleSheet,
    Text,
    TouchableHighlight,
    ImageBackground,
    TouchableOpacity,
    View,
    FlatList
} from "react-native";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import * as messageTypes from "../../constants/message-types";
import * as actions from "./actions";
import Message from "../../models/message";
import { defaultStyles } from "../../styles/default-styles";
import coveredBridge from "../../assets/images/covered-bridge2.jpg";

const myStyles = {
    message: {
        marginBottom: 10,
        padding: 5,
        borderWidth: 1,
        borderColor: "#888",
        borderStyle: "solid"
    },
    unread: {
        color: "#111",
        fontSize: 12,
        shadowColor: "#FFF",
        shadowOffset: { width: 1, height: 1 },
        shadowOpacity: 1,
        shadowRadius: 1
    },
    read: {
        color: "#888",
        fontSize: 12,
        shadowColor: "#FFF",
        shadowOffset: { width: 1, height: 1 },
        shadowOpacity: 1,
        shadowRadius: 1
    },
    oldMsg: {
        color: "#888",
        fontSize: 16,
        shadowColor: "#FFF",
        shadowOffset: { width: 1, height: 1 },
        shadowOpacity: 1,
        shadowRadius: 1
    },
    newMsg: {
        fontWeight: "bold",
        color: "#111",
        fontSize: 16,
        shadowColor: "#FFF",
        shadowOffset: { width: 1, height: 1 },
        shadowOpacity: 1,
        shadowRadius: 1
    },
    loadingScreen: {
        justifyContent: "center",
        alignItems: "center"
    }
};
const combinedStyles = Object.assign({}, defaultStyles, myStyles);
const styles = StyleSheet.create(combinedStyles);

type TProps = {
    item: Message,
    toDetail: any => any
}

class MessageItem extends Component<TProps> {

    render() {
        const { item, toDetail } = this.props;
        return (
            <TouchableOpacity key={ item.id } onPress={ toDetail }>
                <View style={ [styles.row, { height: 85 }] }>
                    <View style={ { flex: 1, flexDirection: "row" } }>
                        <Image
                            style={ { width: 50, height: 50, marginRight: 10 } }
                            source={ { uri: item.sender.photoURL } }
                        />
                        <View style={ { flex: 1, flexDirection: "column", alignItems: "stretch" } }>
                            <Text style={ [item.read ? styles.read : styles.unread, {
                                fontSize: 10,
                                textAlign: "left",
                                fontWeight: "bold",
                                height: 13
                            }] }
                            >{item.teamName}</Text>
                            <Text style={ [{ height: 40 }, item.read
                                ? styles.oldMsg : styles.newMsg] }>
                                {item.text.length > 80
                                    ? `${item.text.slice(0, 80)}...`
                                    : item.text}
                            </Text>
                            <Text style={ [item.read ? styles.read : styles.unread, {
                                fontSize: 10,
                                textAlign: "right"
                            }] }>
                                {`--${item.sender.displayName || item.sender.email}`}
                            </Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        );
    }
}

class MessageSummariesScreen extends Component {
    static propTypes = {
        actions: PropTypes.object,
        currentUser: PropTypes.object,
        messages: PropTypes.object,
        navigation: PropTypes.object,
        userHasTeams: PropTypes.bool,
        teamMembersLoaded: PropTypes.bool,
        teamsLoaded: PropTypes.bool,
        messagesLoaded: PropTypes.bool,
        teams: PropTypes.object
    };

    static navigationOptions = {
        title: "Message Board",
        tabBarLabel: "Messages"
    };

    constructor(props) {
        super(props);
        this.toMessageDetail = this.toMessageDetail.bind(this);
        this.toSendMessage = this.toSendMessage.bind(this);
    }

    toSendMessage() {
        return () => {
            this.props.navigation.navigate("NewMessage");
        };
    }

    toMessageDetail(message) {
        const userId = (this.props.currentUser || {}).uid;
        switch (message.type) {
            case messageTypes.INVITATION :
                return () => {
                    this.props.actions.selectTeamById(message.teamId);
                    this.props.navigation.navigate("TeamDetails");
                };
            case messageTypes.REQUEST_TO_JOIN :
                return () => {
                    const membershipId = message.sender.email.uid;
                    const teamId = message.teamId;
                    this.props.actions.readMessage(message, userId);
                    this.props.navigation.navigate("TeamMemberDetails", { teamId, membershipId });
                };
            default :
                return () => {
                    // mark message as read
                    this.props.actions.readMessage(message, userId);
                    // navigate to details screen
                    this.props.navigation.navigate("MessageDetails", { messageId: message.id });
                };
        }
    }

    render() {
        const myMessages = Object.entries(this.props.messages).map(entry => Message.create(entry[1], entry[0])).sort((a, b) => b.created.valueOf() - a.created.valueOf());
        return this.props.userHasTeams || myMessages.length > 0 ? (
            <View style={ styles.frame }>
                <View style={ styles.singleButtonHeader }>
                    {
                        this.props.userHasTeams
                            ? (<TouchableHighlight
                                style={ styles.headerButton }
                                onPress={ () => {
                                    this.props.navigation.navigate("NewMessage");
                                } }>
                                <Text style={ styles.headerButtonText }>{"New Message"}</Text>
                            </TouchableHighlight>)
                            : (
                                <View style={ styles.headerButton }>
                                    <Text style={ styles.headerButtonText }>{"Join or create a team to send messages."}</Text>
                                </View>)
                    }
                </View>
                {myMessages.length > 0
                    ? (
                        <ScrollView style={ styles.scroll }>
                            <View style={ styles.infoBlockContainer }>
                                <FlatList
                                    data={ myMessages }
                                    keyExtractor={ item => item.id }
                                    renderItem={ ({ item }) => (
                                        <MessageItem
                                            item={ item }
                                            toDetail={ this.toMessageDetail(item) }/>) }
                                    style={ styles.infoBlockContainer }
                                />
                            </View>
                        </ScrollView>
                    )
                    : (
                        <ImageBackground source={ coveredBridge } style={ styles.backgroundImage }>
                            <View style={ {
                                marginTop: "20%",
                                paddingLeft: 20,
                                paddingRight: 20,
                                paddingTop: 50,
                                paddingBottom: 50,
                                backgroundColor: "rgba(255,255,255, 0.85)"
                            } }>
                                <Text style={ [styles.textDark, { textAlign: "center", height: 30 }] }>{"Sorry, no messages yet."}</Text>
                            </View>
                        </ImageBackground>
                    )}
            </View>
        ) : (
            <View style={ styles.frame }>
                <ImageBackground source={ coveredBridge } style={ styles.backgroundImage }>
                    <View style={ {
                        marginTop: "20%",
                        paddingLeft: 20,
                        paddingRight: 20,
                        paddingTop: 50,
                        paddingBottom: 50,
                        backgroundColor: "rgba(255,255,255, 0.85)"
                    } }>
                        <Text style={ [styles.textDark, { textAlign: "justify" }] }>
                            {"All your messages will be listed here."}
                        </Text>
                        <Text style={ [styles.textDark, { textAlign: "justify" }] }>
                            {"Before you can send or receive messages you will need to join or create a team."}
                        </Text>
                        <TouchableOpacity
                            style={ styles.button }
                            onPress={ () => {
                                this.props.navigation.navigate("Teams");
                            } }
                        >
                            <Text style={ styles.buttonText }>{"Go to \"My Teams\" >"}</Text>
                        </TouchableOpacity>
                    </View>
                </ImageBackground>
            </View>
        );
    }
}

function mapStateToProps(state) {
    const teams = state.teams.teams || {};
    const mapMessagesToTeamNames = queue => Object.values(queue)
        .map(message => Message.create({ ...message, teamName: (teams[message.teamId] || {}).name }))
        .reduce((obj, message) => ({ ...obj, [message.id]: message }), {});
    const messages = Object.values((state.messages || {}).messages || {}).reduce((obj, queue) => ({ ...obj, ...mapMessagesToTeamNames(queue) }), {});
    const userHasTeams = Object.keys((state.profile || {}).teams || {}).length > 0;
    const userHasMessages = state.messages.length > 0;
    return {
        currentUser: state.login.user,
        messages: messages,
        messagesLoaded: state.messages.loaded,
        userHasTeams,
        userHasMessages,
        teamsLoaded: state.messages.teamsLoaded,
        teamMembersLoaded: state.loading.teamMembersLoaded,
        teams: teams
    };
}

const mapDispatchToProps = (dispatch) => ({
    actions: bindActionCreators(actions, dispatch)
});

export default connect(mapStateToProps, mapDispatchToProps)(MessageSummariesScreen);


text:
package org.apache.skywalking.apm.agent.core.logging.api;

import org.apache.skywalking.apm.agent.core.logging.core.PatternLogResolver;

/**
 * LogManager is the {@link LogResolver} implementation manager. By using {@link LogResolver}, {@link
 * LogManager#getLogger(Class)} returns a {@link ILog} implementation. This module use this class as the main entrance,
 * and block the implementation detail about log-component. In different modules, like server or sniffer, it will use
 * different implementations.
 *
 * <p> If no {@link LogResolver} is registered, return {@link NoopLogger#INSTANCE} to avoid
 * {@link NullPointerException}. If {@link LogManager#setLogResolver(LogResolver)} is called twice, the second will
 * override the first without any warning or exception.
 *
 * <p> Created by xin on 2016/11/10.
 */
public class LogManager {
    private static LogResolver RESOLVER = new PatternLogResolver();

    public static void setLogResolver(LogResolver resolver) {
        LogManager.RESOLVER = resolver;
    }

    public static ILog getLogger(Class<?> clazz) {
        if (RESOLVER == null) {
            return NoopLogger.INSTANCE;
        }
        return LogManager.RESOLVER.getLogger(clazz);
    }

    public static ILog getLogger(String clazz) {
        if (RESOLVER == null) {
            return NoopLogger.INSTANCE;
        }
        return LogManager.RESOLVER.getLogger(clazz);
    }
}


text:
package pipe.controllers;

import pipe.constants.GUIConstants;
import pipe.controllers.application.PipeApplicationController;
import pipe.gui.PetriNetTab;
import pipe.historyActions.MultipleEdit;
import pipe.historyActions.component.AddPetriNetObject;
import pipe.utilities.gui.GuiUtils;
import uk.ac.imperial.pipe.exceptions.PetriNetComponentException;
import uk.ac.imperial.pipe.models.petrinet.*;
import uk.ac.imperial.pipe.naming.MultipleNamer;
import uk.ac.imperial.pipe.naming.PetriNetComponentNamer;
import uk.ac.imperial.pipe.visitor.PasteVisitor;
import uk.ac.imperial.pipe.visitor.component.PetriNetComponentVisitor;

import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.UndoableEdit;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * Class to handle copy and paste functionality
 */
@SuppressWarnings("serial")
public class CopyPasteManager extends javax.swing.JComponent
        implements java.awt.event.MouseListener, java.awt.event.MouseMotionListener, java.awt.event.KeyListener {

    /**
     * Colour of rectangle displayed when pasting
     */
    private static final Paint PASTE_COLOR = new Color(155, 155, 155, 100);

    /**
     * Colour of rectangle outline displayed when pasting
     */
    private static final Color PASTE_COLOR_OUTLINE = new Color(155, 0, 0, 0);

    /**
     * Rectangle displayed which marks the outline of the objects to paste
     */
    private final Rectangle pasteRectangle = new Rectangle(-1, -1);

    /**
     * Petri net tab where pasting takes place
     */
    private final PetriNetTab petriNetTab;

    /**
     * Petri net pasting objects from/to
     */
    private final PetriNet petriNet;

    /**
     * Main PIPE application controller
     */
    private final PipeApplicationController applicationController;

    /**
     * Origin of the selected components to paste (top left corner)
     */
    private final Point rectangleOrigin = new Point();

    /**
     * Listener for undoable events being created
     */
    private final UndoableEditListener listener;

    /**
     * pasteInProgres is true when pasteRectangle is visible (user is doing a
     * paste but still hasn't chosen the position where elements will be pasted).
     */
    private boolean pasteInProgress = false;

    /**
     * Components to paste when paste is clicked.
     * These are set when copied
     */
    private Collection<PetriNetComponent> pasteComponents = new ArrayList<>();

    /**
     * Constructor
     *
     * @param listener              undoable event listener, used to register undo events to
     * @param petriNetTab           current Petri net tab
     * @param net                   underlying Petri net displayed on the Petri net tab
     * @param applicationController main application controller
     */
    public CopyPasteManager(UndoableEditListener listener, PetriNetTab petriNetTab, PetriNet net,
                            PipeApplicationController applicationController) {
        this.petriNetTab = petriNetTab;
        petriNet = net;
        this.applicationController = applicationController;
        addMouseListener(this);
        addMouseMotionListener(this);
        addKeyListener(this);
        this.listener = listener;

    }

    /**
     * Creates new components for the petri net to copy when pasted
     *
     * @param selectedComponents components to copy
     */
    public void copy(Collection<PetriNetComponent> selectedComponents) {
        pasteComponents.clear();
        pasteComponents.addAll(selectedComponents);
        LocationVisitor locationVisitor = new LocationVisitor();

        for (PetriNetComponent component : selectedComponents) {
            try {
                component.accept(locationVisitor);
            } catch (PetriNetComponentException e) {
                GuiUtils.displayErrorMessage(null, e.getMessage());
            }
        }
        Location location = locationVisitor.location;
        pasteRectangle.setRect(location.left, location.top, location.right - location.left,
                location.bottom - location.top);
        rectangleOrigin.setLocation(location.left, location.top);
    }

    /**
     * Shows the paste rectangle on screen
     */
    public void showPasteRectangle() {
        if (!pasteInProgress) {
            petriNetTab.add(this);
            requestFocusInWindow();
            //            if (zoom != petriNetTab.getZoom()) {
            //                updateSize(pasteRectangle, zoom, petriNetTab.getZoom());
            //                zoom = petriNetTab.getZoom();
            //            }

            petriNetTab.setLayer(this, GUIConstants.SELECTION_LAYER_OFFSET);
            repaint();
            pasteInProgress = true;
            updateBounds();
        }
    }

    /**
     * Update the bounds which this object can be displayed at
     */
    private void updateBounds() {
        if (pasteInProgress) {
            PetriNetTab activeTab = applicationController.getActiveTab();
            setBounds(0, 0, activeTab.getWidth(), activeTab.getHeight());
        }
    }

    /**
     * @return if it is possible to perform a paste action
     */
    public boolean pasteEnabled() {
        return !pasteComponents.isEmpty();
    }

    /**
     * Paints the paste rectangle onto the screen
     *
     * @param g paint graphics
     */
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setPaint(PASTE_COLOR);
        g2d.fill(pasteRectangle);
        g2d.setXORMode(PASTE_COLOR_OUTLINE);
        g2d.draw(pasteRectangle);
    }

    /**
     * Dragging the mouse on the screen updates the location of the
     * paste rectangle
     *
     * @param e mouse drag event
     */
    @Override
    public void mouseDragged(MouseEvent e) {
        if (pasteInProgress) {
            updateRect(e.getPoint());
        }
    }

    /**
     * Changes the rectangles location to point
     *
     * @param point new top left point for rectangle
     */
    private void updateRect(Point point) {
        pasteRectangle.setLocation(point);
        repaint();
        updateBounds();
    }

    /**
     * Moving the mouse on the screen updates the location of the
     * paste rectangle
     *
     * @param e mouse move event
     */
    @Override
    public void mouseMoved(MouseEvent e) {
        if (pasteInProgress) {
            updateRect(e.getPoint());
        }
    }

    /**
     * Noop action on click
     *
     * @param e mouse click event
     */
    @Override
    public void mouseClicked(MouseEvent e) {
        //Not needed
    }

    /**
     * Performs the paste action
     *
     * @param e mouse pressed event
     */
    @Override
    public void mousePressed(MouseEvent e) {
        petriNetTab.updatePreferredSize();
        petriNetTab.setLayer(this, GUIConstants.LOWEST_LAYER_OFFSET);
        repaint();
        if (pasteInProgress) {
            paste(petriNetTab);
        }
    }

    /**
     * Noop action
     *
     * @param e mouse released event
     */
    @Override
    public void mouseReleased(MouseEvent e) {
        // Not needed
    }

    /**
     * Noop action
     *
     * @param e mouse entered event
     */
    @Override
    public void mouseEntered(MouseEvent e) {
        // Not needed
    }

    /**
     * Noop action
     *
     * @param e mouse exited event
     */
    @Override
    public void mouseExited(MouseEvent e) {
        // Not needed
    }

    /**
     * Paste pastes the new objects into the petriNet specified in consturction.
     * <p>
     * It first pastes the connectables, and then other components. This ordering is important
     * and will ensure that arcs are created with the right components.
     * </p>
     * @param petriNetTab petri net tab to paste items to
     */
    private void paste(PetriNetTab petriNetTab) {
        pasteInProgress = false;
        petriNetTab.remove(this);

        if (pasteComponents.isEmpty()) {
            return;
        }

        int despX = pasteRectangle.x - rectangleOrigin.x;
        int despY = pasteRectangle.y - rectangleOrigin.y;

        MultipleNamer multipleNamer = new PetriNetComponentNamer(petriNet);
        PasteVisitor pasteVisitor = new PasteVisitor(petriNet, pasteComponents, multipleNamer, despX, despY);

        try {
            for (Connectable component : getConnectablesToPaste()) {
                component.accept(pasteVisitor);
            }
            for (PetriNetComponent component : getNonConnectablesToPaste()) {
                component.accept(pasteVisitor);
            }
        } catch (PetriNetComponentException e) {

            GuiUtils.displayErrorMessage(null, e.getMessage());
        }

        createPasteHistoryItem(pasteVisitor.getCreatedComponents());
    }

    /**
     * @return a collection of the connectable items to paste
     */
    private Collection<Connectable> getConnectablesToPaste() {
        final Collection<Connectable> connectables = new LinkedList<>();
        PetriNetComponentVisitor connectableVisitor = new PlaceTransitionVisitor() {
            @Override
            public void visit(Place place) {
                connectables.add(place);
            }

            @Override
            public void visit(Transition transition) {
                connectables.add(transition);
            }
        };

        for (PetriNetComponent component : pasteComponents) {
            try {
                component.accept(connectableVisitor);
            } catch (PetriNetComponentException e) {
                GuiUtils.displayErrorMessage(null, e.getMessage());
            }
        }
        return connectables;
    }

    /**
     * @return Petri net components that do not inherit from Connectable
     */
    private Collection<PetriNetComponent> getNonConnectablesToPaste() {
        final Collection<PetriNetComponent> components = new LinkedList<>();
        PetriNetComponentVisitor componentVisitor = new NonConnectableVisitor() {
            @Override
            public void visit(Token token) {
                components.add(token);
            }

            @Override
            public void visit(Annotation annotation) {
                components.add(annotation);
            }

            @Override
            public void visit(InboundArc inboundArc) {
                components.add(inboundArc);
            }

            @Override
            public void visit(OutboundArc outboundArc) {
                components.add(outboundArc);
            }
        };

        for (PetriNetComponent component : pasteComponents) {
            try {
                component.accept(componentVisitor);
            } catch (PetriNetComponentException e) {
                GuiUtils.displayErrorMessage(null, e.getMessage());
            }
        }
        return components;
    }

    /**
     * Creates a history item for the new components added to the petrinet
     *
     * @param createdComponents new components that have been created
     */
    private void createPasteHistoryItem(Iterable<PetriNetComponent> createdComponents) {
        List<UndoableEdit> undoableEditList = new LinkedList<>();
        for (PetriNetComponent component : createdComponents) {
            AddPetriNetObject addAction = new AddPetriNetObject(component, petriNet);
            undoableEditList.add(addAction);
        }

        listener.undoableEditHappened(new UndoableEditEvent(this, new MultipleEdit(undoableEditList)));
    }

    /**
     * Noop action
     *
     * @param e key typed event
     */
    @Override
    public void keyTyped(KeyEvent e) {
        // Not needed
    }

    /**
     * Noop action
     *
     * @param e key pressed event
     */
    @Override
    public void keyPressed(KeyEvent e) {
        // Not needed
    }

    /**
     * Noop action
     *
     * @param e key released event
     */
    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
            cancelPaste();
        }
    }

    /**
     * Cancel the paste. This will stop the paste rectangle being displayed but will
     * keep the copied items selected for future pastes
     */
    public void cancelPaste() {
        PetriNetTab tab = applicationController.getActiveTab();
        cancelPaste(tab);
    }

    /**
     * Cancel the paste. This will stop the paste rectangle being displayed but will
     * keep the copied items selected for future pastes
     *
     * @param view tab on which the paste is taking place
     */
    void cancelPaste(PetriNetTab view) {
        pasteInProgress = false;
        view.repaint();
        view.remove(this);
    }

    /**
     * Used for creating anonymous classes that only visit
     * Places and Transition
     */
    private interface PlaceTransitionVisitor extends PlaceVisitor, TransitionVisitor {

    }

    /**
     * Used for creating anonymous classes that visit non connectable classes
     */
    private interface NonConnectableVisitor extends AnnotationVisitor, ArcVisitor, TokenVisitor {

    }

    /**
     * Private class used to set the bounds of a selection rectangle
     * Needed to create a class so that the visitor can change the values
     */
    private static class Location {
        /**
         * Bottom location
         */
        private double bottom = 0;

        /**
         * Right of the rectangle
         */
        private double right = 0;

        /**
         * Top of the rectangle
         */
        private double top = Double.MAX_VALUE;

        /**
         * Left of the rectangle
         */
        private double left = Double.MAX_VALUE;
    }

    /**
     * Used to set the bounds of the rectagle displayed when copy pasting
     */
    private static class LocationVisitor implements PlaceTransitionVisitor {
        /**
         * Location of the rectangle
         */
        private final Location location = new Location();

        /**
         * Adjusts the bounds to include the position of the place
         * @param place
         */
        @Override
        public void visit(Place place) {
            adjustLocation(place);
        }

        /**
         * Changes the bounds of the rectangle to include the connectable
         * @param connectable being bounded
         * @param <T> type of the connectable
         */
        private <T extends Connectable> void adjustLocation(T connectable) {
            if (connectable.getX() < location.left) {
                location.left = connectable.getX();
            }
            if (connectable.getX() + connectable.getWidth() > location.right) {
                location.right = connectable.getX() + connectable.getWidth();
            }
            if (connectable.getY() < location.top) {
                location.top = connectable.getY();
            }
            if (connectable.getY() + connectable.getHeight() > location.bottom) {
                location.bottom = connectable.getY() + connectable.getHeight();
            }
        }

        /**
         * Adjusts the bounds of the rectangle to include the position of the transition
         * @param transition to be included in the bounds
         */
        @Override
        public void visit(Transition transition) {
            adjustLocation(transition);
        }

    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Interface IDataProvider
   </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Interface IDataProvider
   ">
    <meta name="generator" content="docfx 2.32.2.0">

    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="../toc.html">
    <meta property="docfx:tocrel" content="toc.html">

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

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

          Show / Hide Table of Contents

Interface IDataProvider

An interface to provide the HarnessManager with a
mechanism to retrieve data for a MongoDb collection.

Namespace: Harness.Settings

Assembly: Harness.dll

Syntax

public interface IDataProvider

Examples

public class PersonDataProvider : IDataProvider
{
    public IEnumerable<object> GetData()
    {
        return new List<Person>
        {
            new Person {FirstName = "Peter", LastName = "Venkman", Age = 31},
            new Person {FirstName = "Ray", LastName = "Stantz", Age = 32},
            new Person {FirstName = "Egon", LastName = "Spengler", Age = 33}
        };
    }
}

public class Person
{
    public ObjectId Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

Methods

    |
    Improve this Doc

    View Source

GetData()

Gets data from a source as an System.Collections.Generic.IEnumerable<T>.

Declaration

IEnumerable<object> GetData()

Returns

        Type
        Description

        System.Collections.Generic.IEnumerable<System.Object>
        System.Collections.Generic.IEnumerable<T>

                    Improve this Doc

                    View Source

              Back to top

            Copyright © 2015-2017 Microsoft
Generated by DocFX


text:
package cz.sezima.chess.api

import cz.sezima.chess.api.player.Player
import cz.sezima.chess.core.Colors.{Black, White}
import cz.sezima.chess.core.board.Board._
import cz.sezima.chess.core.board.{Board, Square}
import cz.sezima.chess.core.piece.{Move, Pawn, Queen}
import org.scalatest.FunSuite

/**
  * A set of [[Chess]] relevant unit tests.
  */
class ChessTests extends FunSuite {

  val foolsMate: List[Move] = List(
    Pawn(White, Square('f', 2)) ~> Square('f', 3),
    Pawn(Black, Square('e', 7)) ~> Square('e', 5),
    Pawn(White, Square('g', 2)) ~> Square('g', 4),
    Queen(Black, Square('d', 8)) ~> Square('h', 4)
  )

  val player: Player = new Player {
    override def play(board: Board): Move =
      foolsMate(board.history.size)
  }

  test("chess game ends with expected result") {

    // setup
    val expResult: Board =
      replay(foolsMate, Initial)

    // act
    val result: Board =
      Chess.play(player, player)

    // assert
    assert(result.isValid)
    assert(expResult == result)
  }

  test("arbitrary valid board could be used to initiate chess game") {

    // setup
    val nonInit: Board = replay(foolsMate.take(2), Initial)
    val expResult: Board = replay(foolsMate, Initial)

    // act
    val result: Board =
      Chess.play(player, player, nonInit)

    // assert
    assert(result.isValid)
    assert(expResult == result)
  }

  // helpers

  private def replay(moves: List[Move], at: Board): Board =
    moves.reverse.foldRight(Initial)(_.performAt(_).left.get)

}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#CCCCCC" />
            <stroke
                android:width="1dp"
                android:color="#E6E6E6" />
            <corners
                android:radius="3dp" />
            <padding
                android:left="5dp"
                android:top="5dp"
                android:right="5dp"
                android:bottom="5dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:angle="270"
                android:startColor="#dbdbdb"
                android:centerColor="#E6E6E6"
                android:endColor="#dbdbdb"/>
            <corners
                android:radius="4dp" />
            <padding
                android:left="5dp"
                android:top="5dp"
                android:right="5dp"
                android:bottom="5dp" />
        </shape>
    </item>
</selector>


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

[b]Getting asDevelop Configured[/b]

asDevelop requires a little bit of setup to be used for your purposes.

[b]1)[/b] You need a script API dump in the "bin" folder (resembles a C++ header).

[b]2)[/b] You need a compiler plugin if you want to compile.

[b]3)[/b] To use the debugger you need to have implemented the asPEEK daemon in your software.

    <h>[b]API Dump[/b]</h>

The expected API dump resembles a C++ header file. For Urho3D, the "Docs" folder of your Urho3D checkout contains a file called "AngelscriptAPI.h" which is in the correct format.

Copy this "AngelscriptAPI.h" file from your checkout to the "bin" folder where the "asDevelop.exe" executable is located. If you have made modifications to Urho3D use the ScriptCompiler tool of Urho3D to generate a new API dump.

    <h>[b]Compiler Plugin[/b]</h>

asDevelop builds an Urho3D compiler plugin by default and it is an included option in the installer.

To use the Urho3D compiler plugin you just need to copy "ScriptCompiler.exe" from your Urho3D "Tools" folder in bin. This manual step gaurantees that compilation is performed in regards to any custom modifications you have made.

At the application launch screen click the "New Project" button.

    HelpCreate_NewProject.png

You'll be prompted to select a directory that will serve as the project root. For Urho3D projects use the "bin" folder of your Urho3D source-tree.

Content asdf

    <h>[b]Minor Features[/b]</h>

[b]*[/b] Double-click on a resizable sash to expand/collapse it

Content fda

Content lkjl

</help>


text:
KERN=FIXME
ALG=FIXME

CFLAGS?=-O3 -Wall -Wno-unused-label

SRCS=$(KERN).c support.c ../../common/support.c
FILES=$(SRCS) $(KERN).h ../../common/support.h

$(KERN): $(FILES) ../../common/harness.c
	$(CC) $(CFLAGS) -I../../common -o $(KERN) $(SRCS) ../../common/harness.c

run: $(KERN) input.data check.data
	./$(KERN) input.data check.data

generate: $(FILES) generate.c
	$(CC) $(CFLAGS) -I../../common -o generate $(SRCS) generate.c

hls: $(KERN).c $(KERN).h
	vivado_hls hls.tcl

clean:
	rm -f $(KERN)
	rm -f generate


text:
package edu.asu.qstore4s.search.elements.factory;

import edu.asu.qstore4s.search.elements.ISearchSourceReference;

public interface ISearchSourceReferenceFactory {

	ISearchSourceReference createSearchSourceReference();

	ISearchSourceReference createSearchSourceReference(String sourceUri);

}


text:
<?php

class DaException extends Exception
{

    public function __construct($message, $code = 0, Exception $previous = null)
    {
	parent::__construct($message, $code, $previous);
    }

    public function __toString()
    {
	return __CLASS__.": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction()
    {
	echo "A Custom function for this type of exception\n";
    }

}

class FormException extends Exception
{

    public function __construct($message, $code = 0, Exception $previous = null)
    {
	parent::__construct($message, $code, $previous);
    }

    public function __toString()
    {
	return __CLASS__.": [{$this->code}]: {$this->message}\n";
    }

    public function customFunction()
    {
	echo "A Custom function for this type of exception\n";
    }

}


text:
var React = require('react');

var article = require('../data/article')

var AboutComponent = React.createClass({

  componentWillMount: function() {
    this.setState({
      article: article[0]
    });
  },

  render: function() {
    var title = this.state.article.title === '' ? 'About' : this.state.article.title;
    var content = { __html: this.state.article.content };
    return (

{title}

    );
  }

});

module.exports = AboutComponent;


text:
"use strict";

const CSSRuleImpl = require("./CSSRule-impl").implementation;
const CSSKeyframeRule = require("../generated/CSSKeyframeRule");
const CSSRuleList = require("../generated/CSSRuleList");

// https://drafts.csswg.org/cssom/#the-cssimportrule-interface
class CSSKeyframesRuleImpl extends CSSRuleImpl {
  constructor(args, { rule, styleSheet }) {
    super(args, { rule, styleSheet, type: 7 });

    this._rule = rule;

    const createdRules = rule.block.rules &&
      rule.block.rules.map(keyFrameRule => {
        return CSSKeyframeRule.create([], { keyFrameRule, styleSheet });
      });

    this._cssRules = CSSRuleList.create([], { createdRules });
  }

  get name() {

  }
  set name(value) {

  }

  get cssRules() {
    return this._cssRules;
  }
}

module.exports = {
  implementation: CSSKeyframesRuleImpl,
};


text:
package com.microsoftopentechnologies.intellij.serviceexplorer.azure.vm;

import com.microsoftopentechnologies.tooling.msservices.helpers.Name;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.NodeActionEvent;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.NodeActionListener;
import com.microsoftopentechnologies.intellij.wizards.createvm.CreateVMWizard;
import com.microsoftopentechnologies.tooling.msservices.serviceexplorer.azure.vm.VMServiceModule;

@Name("Create VM")
public class CreateVMAction extends NodeActionListener {
    public CreateVMAction(VMServiceModule node) {
        super(node);
    }

    @Override
    public void actionPerformed(NodeActionEvent e) {
        CreateVMWizard createVMWizard = new CreateVMWizard((VMServiceModule) e.getAction().getNode());
        createVMWizard.show();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/frame_button_p" android:state_selected="true"/>
    <item android:drawable="@drawable/frame_button_n" android:state_selected="false"/>

</selector>


text:
define(function(require) {

    // Include utility functions and parent class
    var utility = require('../Helper/utility.js');
    var Vehicle = require('./Vehicle.js')

    // Constructor
    function WaterVehicle() {
        var args = Array.prototype.slice.call(arguments);

        Vehicle.call(this, args);
    }

    // Inheritance of parent
    WaterVehicle.inherit(Vehicle);

    // Property for changing spin direction
    WaterVehicle.prototype.changeSpinDirection = function() {
        this.propulsionUnits.forEach(function(propeller) {
            propeller.changeSpinDirection();
        });
    }

    return WaterVehicle;
})


text:
if [ "$USER" -ne "root" ]; then
    echo "run script as root!"
    exit 1
fi
P=`pwd`
TMP=/tmp/temp-xd-xd
REPO="https://github.com/szymonrychu/puppet-masterless"
echo "adding gpg puppet labs key"
apt-key adv --keyserver pool.sks-keyservers.net --recv-keys 4BD6EC30 -y
echo "adding puppetlabs sources list"
cat > /etc/apt/sources.list.d/puppetlabs.list << EOF
deb-src http://apt.puppetlabs.com wheezy main
deb-src http://apt.puppetlabs.com wheezy dependencies
EOF
echo "updating apt cache"
apt-get update
mkdir $TMP
cd $TMP
echo "building from source facter, hiera and ruby-rgen"
for pkg in facter hiera ruby-rgen
do
    apt-get -y build-dep $pkg
    apt-get -b source $pkg
done
echo "installing virt-what, ruby-json and prepared facter, hiera, ruby-rgen"
apt-get install virt-what ruby-json
dpkg -i facter_*.deb hiera_*.deb ruby-rgen_*.deb
echo "building from source puppet"
apt-get -y build-dep puppet
apt-get -b source puppet
echo "installing augeas-lenses libaugeas0 libaugeas-ruby1.8 ruby-shadow libshadow-ruby1.8 and puppet"
apt-get install augeas-lenses libaugeas0 libaugeas-ruby1.8 ruby-shadow libshadow-ruby1.8
dpkg -i puppet-common_*.deb puppet_*.deb
cd $P
rm -Rf $TMP
mkdir $TMP
cd $TMP
echo "fetching repository"
/usr/bin/env git clone $REPO $TMP
echo "running puppet for first time"
puppet apply --test --modulepath $TMP/modules $TMP/manifests/site.pp $@ 2>&1
echo "done!"


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

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

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

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
         http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

  <!-- a bean for user services -->
  <bean id="userService" class="org.apache.camel.example.rest.UserService"/>

  <camelContext id="myCamel" xmlns="http://camel.apache.org/schema/spring">

    <!-- configure rest to use the camel-servlet component, and use json binding mode -->
    <!-- and tell to output json in pretty print mode -->
    <!-- setup context path and port number that Apache Tomcat will deploy this application with,
         as we use the servlet component, then we need to aid Camel to tell it these details so Camel
         knows the url to the REST services.
         Notice: This is optional, but needed if the RestRegistry should enlist accurate information.
         You can access the RestRegistry from JMX at runtime -->
    <!-- also enable swagger api, using the apiContextPath
         and enable CORS so the swagger-ui web console can access the swagger api docs -->
    <restConfiguration component="servlet" bindingMode="json"
                       contextPath="camel-example-swagger-xml/rest" port="8080"
                       apiContextPath="api-docs" apiContextListing="true"
                       enableCORS="true">

      <!-- we want json output in pretty mode -->
      <dataFormatProperty key="prettyPrint" value="true"/>

      <!-- setup swagger api descriptions -->
      <apiProperty key="base.path" value="rest"/>
      <apiProperty key="api.version" value="1.2.3"/>
      <apiProperty key="api.title" value="User Services"/>
      <apiProperty key="api.description" value="Camel Rest Example with Swagger that provides an User REST service"/>
      <apiProperty key="api.contact.name" value="The Apache Camel team"/>

    </restConfiguration>

    <!-- defines the rest services using the context-path /user -->
    <rest path="/user" consumes="application/json" produces="application/json">
      <description>User rest service</description>

      <!-- this is a rest GET to view an user by the given id -->
      <get uri="/{id}" outType="org.apache.camel.example.rest.User">
        <description>Find user by id</description>
        <param name="id" type="path" description="The id of the user to get" dataType="integer"/>
        <responseMessage message="The user that was found"/>
        <responseMessage code="404" message="User not found"/>
        <route>
          <to uri="bean:userService?method=getUser(${header.id})"/>
          <filter>
            <simple>${body} == null</simple>
            <setHeader headerName="Exchange.HTTP_RESPONSE_CODE">
              <constant>404</constant>
            </setHeader>
          </filter>
        </route>
      </get>

      <!-- this is a rest PUT to create/update an user -->
      <put type="org.apache.camel.example.rest.User">
        <description>Updates or create a user</description>
        <param name="body" type="body" description="The user to update or create"/>
        <to uri="bean:userService?method=updateUser"/>
      </put>

      <!-- this is a rest GET to find all users -->
      <get uri="/findAll" outType="org.apache.camel.example.rest.User[]">
        <description>Find all users</description>
        <responseMessage message="All the users"/>
        <to uri="bean:userService?method=listUsers"/>
      </get>
    </rest>

    <!-- defines the rest services using the context-path /echo -->
    <rest path="/echo" consumes="application/text" produces="application/text">
      <description>Echo rest service</description>

      <get uri="/ping">
        <description>A ping service</description>
        <route>
          <transform>
            <constant>pong</constant>
          </transform>
        </route>
      </get>

    </rest>

  </camelContext>

</beans>


text:
package com.facebook.litho.specmodels.processor;

import java.util.List;
import javax.annotation.processing.Messager;

public class MultiPrintableException extends PrintableException {
  private final List<PrintableException> mExceptions;

  MultiPrintableException(List<PrintableException> exceptions) {
    mExceptions = exceptions;
  }

  @Override
  public void print(Messager messager) {
    for (PrintableException e : mExceptions) {
      e.print(messager);
    }
  }
}


text:
layout: post
title:  Discord is down?
date:    2017-06-08
excerpt: Well, it was. You missed it!
image: /assets/img/covers/discord.png
tag:
  - Linux
  - Networking
---

I received a message from someone at about 3am on June 8th and I mistakenly thought I received it through Discord. In hindsight, that didn't make sense since I didn't actually have Discord running.

Anyway, I started it up and the iconic spinny logo (which I now know is actually just a webm video) appeared...

[![The Discord startup window][1]][1]

[1]: /assets/img/discord/startup.png

and kept spinning... and spinning... and ok, obviously something is up here so it's time to do some investigating 🕵

The first step which you should always do is check out the website to see if they have a status page

[![The Discord website erroring out][2]][2]

[2]: /assets/img/discord/site.png

The same error appeared for [https://status.discordapp.com](https://status.discordapp.com) which defeats the entire purpose of having a status page. Well, perhaps we can confirm what exactly is giving the Discord app trouble by checking out `Console.app`. Oh and shoutout to [@samjarman](https://twitter.com/samjarman) for reminding me the day before that it was a thing.

[![The macOS console app showing Discord errors][3]][3]

[3]: /assets/img/discord/console.png

Well, it's not too surprising considering I couldn't access the main site but as we can see, there's an `HTTP Load Failed` error!

Hmm, at this point, I decided to check if it was just me having this issue. There was no mention of any issues by [@discordapp](https://twitter.com/discordapp) but that doesn't mean there's nothing at all. In times like this, [search.twitter.com](https://search.twitter.com) becomes your best friend.

Sorting by latest, I came across at least a few users:

@discordapp Hey Discord team! I'm current experiencing connection issues from New Zealand can you let me now what up? That would be grand!
— Bj007pro (@BJ007PRO) June 7, 2017

Discord appears to be down... only in New Zealand? @discordapp
— Prens (@Prens1327) June 7, 2017

@discordapp is so down right now, I can't even check https://t.co/FHPEkN0bFT to see where it's down. (Hamilton, New Zealand, ISP: Voyager) pic.twitter.com/QWLL3Oerto
— Harrison Crane (@immortalmewtwo) June 7, 2017

Well, it's not just me then! Now that we know it's not just a local issue, we can start to look further afield. Using a service like [isup.me](https://isup.me) tells us that Discord isn't down for everyone but obviously it's down for others in New Zealand so the issue must lay somewhere in between.

Well, that means we've got a solid case to bust out `traceroute` which will list all the servers that our connection routes through when attempting to reach Discord.

[![The output of traceroute][4]][4]

[4]: /assets/img/discord/traceroute.png

The annoying part with this traceroute is that it completes. That's great of course but it'd be a bit more obvious if it just failed at a specific server. To get around this, I tried the very scientific method of visiting each IP address starting from bottom to top.

The last 2 timed out while all the previous entries returned nothing. That's not bad of course, it just means that those servers aren't serving anything on Port `80` so chances are we can ignore them. Since the last two are attempting to respond with HTML but failing, we can assume that's where the error lays.

The highlighted entry from the screenshot above is the earliest server that times out so it makes sense to assume that's where the problem begins or else it would just route our request on to the next server. Let's see what we can find out about `198.41.236.253`.

[![Running nslookup on the IP address][5]][5]

[5]: /assets/img/discord/nslookup.png

Ahh, a Cloudflare server? That makes sense. For whose who haven't heard of it, Cloudflare provides a few services such as DDoS protection to mitigate attacks and a Content Delivery Network (CDN) for distributing services around the world.

In the case of Discord, Cloudflare would be mirroring their content so we can connect to a local server rather than waiting for our connection to route all the way to the US which wouldn't be as fast.

Now that we know that, it's worth having a look where exactly this Cloudflare is and surprise, surprise, it's located in Auckland!

[![An IP lookup showing the Cloudflare server in Auckland][6]][6]

[6]: /assets/img/discord/location.png

Now it makes sense why Discord isn't mentioning this issue because it's not actually a Discord issue, it's a Cloudflare issue! So, how about we check the Cloudflare status page instead?

[![Cloudflare's status page][7]][7]

[7]: /assets/img/discord/cloudflare.png

Would ya look at that, it's `Re-routed`. That's not explicitly an error but we've got users in New Zealand having issues on the left and a New Zealand server with a status other than `Operational` on the right so I think it's safe to conclude that the issue resides with Cloudflare (the middlemen and middlewomen, geddit?).

After a while, Cloudflare changed back to `Operational` and the entire route changed aside from the first two (my router and ISP respectively) and the final address.

Initially the traffic was passing from my house up to Auckland and then to San Francisco but now it passes through a bunch of [bogon](https://en.wikipedia.org/wiki/Bogon_filtering) addresses and one address owned by [IX Australia](https://www.ix.asn.au/) before popping up at the same Cloudflare address in San Francisco.

Ah well, things are back in order so I can go back to chatting on Discord. I never received any acknowledgement from their Twitter account but I sent an email to their engineering department to follow up.

At least, their mail server told me that engineering was a valid email address. As for how I found that out, well, that's a blog post for another day (or you can just search `telnet smtp`).

If I get a reply back, I'll post an update with their response.


text:
layout: post
title:  "Weekend July 20th: Fairs, Fun, and Staying Home"
date:   2015-07-19
categories: Germany
thumb: /images/FerrisWheel.JPG
backgrounds:
     - /images/NightFair.JPG
---

Describing a relaxing, non travelling weekend in Dortmund and Dusseldorf.

# Back in Dortmund

This weekend I decided to take a much needed break from travelling and stay at home with some friends.
I didn't exactly stay at *home* though because all of my friends from the program are still in Dortmund.
If I haven't told you, I was required to move to Dusseldorf for my internship with SMS.
The train ride from Dusseldorf to Dortmund is about an hour and a half if you are lucky.
For almost the first time in a month and a half, I was lucky! The train ride went without any interruptions.

The first thing that I noticed back in Dortmund is that the town had quickly become small.
After travelling all over Germany and seeing many different areas, Dortmund didn't seem unusually different.
The quaint German houses, the brick lined streets, and the bustling train station were nothing new to me at this point and it was comforting to know that in my travels I have adapted to an entirely different way of life.

It being a weekend, I couldn't take the hanging rail to my dorm. Now that I finally have a camera, I got some good shots of what the forest looks like in between my old dorm and the rest of campus.

![Walk from Dorm to Campus]({{ site.url }}/images/DormWalk.JPG)

# Going out in the City

It was nice to finally see Andy and Wanda again and I was also introduced to Andy's friend Hannah who was visiting from Cambridge.

![Hanging out with friends again!]({{ site.url }}/images/DortmundClubbing.jpg)

Being around the Ruhr fellows was a welcome break from seeing mostly Germans every day.
We found some clubs that were fun and some that were funny that night.
My personal highlight of the night was going to a club that was basically unattended.
We were essentially the only four people on the dance floor when they started blaring a very eery remix of "Fresh Prince of Bel Air", which probably stands as the weirdest thing I have heard in a club.

# Daytime Dortmund

The next day Andy and Hannah decided to go hiking, so Wanda and I ran some errands in Dortmund.
I finally made it to the Post Office so I could send some gifts home to my family.
On the outside of the Post Office were these two amazing statues of Hand People!
They clearly symbolize the Ruhr Area's deindustrialization and the people's fading identification with manual labor, as well as the painful struggle for new work.
Plus, the Hand-People have butts, which is hilarious!

![Hand Statues]({{ site.url }}/images/HandStatues.jpg)

After that we finally made it to the resturaunt that our German teacher Matthaus told us about, the KartoffelLord!
It is a small hipster restuaraunt that only sells potatoes and other vegetarian dishes (for Germany vegetarian is a big deal).
The portions were huge and delicious. I would love to go back.

![Kartoffel]({{ site.url }}/images/KartoffelLord.jpg)

# Dusseldorf Fair

Near dinnertime Wanda and I left for Dusseldorf to go see the amusement park.
This park is held every year, but only for a week or two.
All of the rides are built on the uninhabited side of the Rhein river just for this event, and my coworkers told me that people visit from the Netherlands and France just for the park.

![View from Bridge]({{ site.url }}/images/BridgeView.JPG)
The fair was absolutely packed with people, the train that we caught to the fair practically had people hanging out of the windows.

There was plenty of good food at the fair!
It was mostly traditional German food like giant pieces of meat or unreasonably large sausages or humongous pretzels filled with butter.
I wasn't surprised to find that Germans could pull off fair food really well.

![Olympic Rings]({{ site.url }}/images/OlympicRings.JPG)

Wanda and I went up on the Ferris wheel and on a massive roller coaster called the Olympic Rings.
There were plenty of rides which ranged from little kid bumper cars to spinning, strobing, metal death traps.
The food was cheap but the rides themselves were very expensive, which was the opposite of US parks.

![View from Ferris Wheel]({{ site.url }}/images/FerrisWheel.JPG)
![View From Bridge (Again)]({{ site.url }}/images/NightFair.JPG)

Overall, it was a great day. Sunday was spent relaxing and getting the rest of my things in order. It's always good to sit back and rest before the next adventure.


text:
package sqlstore

import (
	"github.com/go-xorm/xorm"
)

type session struct {
	*xorm.Session
	transaction bool
	complete    bool
}

func newSession(transaction bool, table string) (*session, error) {
	if !transaction {
		return &session{Session: x.Table(table)}, nil
	}
	sess := session{Session: x.NewSession(), transaction: true}
	if err := sess.Begin(); err != nil {
		return nil, err
	}
	sess.Table(table)
	return &sess, nil
}

func (sess *session) Complete() {
	if sess.transaction {
		if err := sess.Commit(); err == nil {
			sess.complete = true
		}
	}
}

func (sess *session) Cleanup() {
	if sess.transaction {
		if !sess.complete {
			sess.Rollback()
		}
		sess.Close()
	}
}


text:
from lbrynet.lbrynet_console.ControlHandlers import CommandHandler, CommandHandlerFactory
from lbrynet.lbrynet_console.ControlHandlers import RecursiveCommandHandler, ModifyPaymentRate
from twisted.internet import defer

class StartRepeater(CommandHandler):
    prompt_description = "Start the blind repeater"

    def __init__(self, console, repeater, settings):
        CommandHandler.__init__(self, console)
        self.repeater = repeater
        self.settings = settings

    def start(self):
        #assert line is None, "Start repeater should not be passed any arguments"
        d = self.settings.save_repeater_status(running=True)
        d.addCallback(lambda _: self.repeater.start())
        d.addCallback(lambda _: self.console.sendLine("Started the repeater"))
        d.chainDeferred(self.finished_deferred)

class StartRepeaterFactory(CommandHandlerFactory):
    control_handler_class = StartRepeater

class StopRepeater(CommandHandler):
    prompt_description = "Stop the blind repeater"

    def __init__(self, console, repeater, settings):
        CommandHandler.__init__(self, console)
        self.repeater = repeater
        self.settings = settings

    def start(self):
        #assert line is None, "Stop repeater should not be passed any arguments"
        d = self.settings.save_repeater_status(running=False)
        d.addCallback(lambda _: self.repeater.stop())
        d.addCallback(lambda _: self.console.sendLine("Stopped the repeater"))
        d.chainDeferred(self.finished_deferred)

class StopRepeaterFactory(CommandHandlerFactory):
    control_handler_class = StopRepeater

class UpdateMaxSpace(CommandHandler):
    prompt_description = "Set the maximum space to be used by the blind repeater"
    line_prompt = "Maximum space (in bytes):"

    def __init__(self, console, repeater, settings):
        CommandHandler.__init__(self, console)
        self.repeater = repeater
        self.settings = settings

    def start(self):
        self.console.sendLine(self.line_prompt)

    def handle_line(self, line):
        d = self._set_max_space(line)
        d.chainDeferred(self.finished_deferred)

    def _set_max_space(self, line):
        max_space = int(line)
        d = self.settings.save_max_space(max_space)
        d.addCallback(lambda _: self.repeater.set_max_space(max_space))
        d.addCallback(lambda _: self.console.sendLine("Set the maximum space to " + str(max_space) + " bytes"))
        return d

class UpdateMaxSpaceFactory(CommandHandlerFactory):
    control_handler_class = UpdateMaxSpace

class AddApprovedPeer(CommandHandler):
    prompt_description = "Add a peer to the approved list of peers to check for valuable blob hashes"
    host_prompt = "Peer host in dotted quad (e.g. 127.0.0.1)"
    port_prompt = "Peer port (e.g. 4444)"

    def __init__(self, console, repeater, peer_manager, settings):
        CommandHandler.__init__(self, console)
        self.repeater = repeater
        self.peer_manager = peer_manager
        self.settings = settings
        self.host_to_add = None

    def start(self):
        self.console.sendLine(self.host_prompt)

    def handle_line(self, line):
        #if line is None:
        #    return False, defer.succeed(self.host_prompt)
        if self.host_to_add is None:
            self.host_to_add = line
            self.console.sendLine(self.port_prompt)
        else:
            self.host_to_add, host = None, self.host_to_add
            d = self._add_peer(host, line)
            d.chainDeferred(self.finished_deferred)

    def _add_peer(self, host, port):
        peer = self.peer_manager.get_peer(host, int(port))
        d = self.settings.save_approved_peer(host, int(port))
        d.addCallback(lambda _: self.repeater.add_approved_peer(peer))
        d.addCallback(lambda _: self.console.sendLine("Successfully added peer"))
        return d

class AddApprovedPeerFactory(CommandHandlerFactory):
    control_handler_class = AddApprovedPeer

class ApprovedPeerChooser(RecursiveCommandHandler):

    def __init__(self, console, repeater, factory_class, *args, **kwargs):
        self.repeater = repeater
        self.factory_class = factory_class
        self.args = args
        RecursiveCommandHandler.__init__(self, console, **kwargs)

    def _get_control_handler_factories(self):
        control_handler_factories = []
        for peer in self.repeater.approved_peers:
            control_handler_factories.append(self.factory_class(peer, *self.args))
        return control_handler_factories

class ApprovedPeerChooserFactory(CommandHandlerFactory):
    def get_prompt_description(self):
        peer = self.args[0]
        return str(peer)

class DeleteApprovedPeerChooser(ApprovedPeerChooser):
    prompt_description = "Remove a peer from the approved list of peers to check for valuable blob hashes"

    def __init__(self, console, repeater, settings):
        ApprovedPeerChooser.__init__(self, console, repeater, DeleteApprovedPeerFactory, repeater,
                                     settings, exit_after_one_done=True)

class DeleteApprovedPeerChooserFactory(CommandHandlerFactory):
    control_handler_class = DeleteApprovedPeerChooser

class DeleteApprovedPeer(CommandHandler):
    prompt_description = "Remove a peer from the approved list of peers to check for valuable blob hashes"

    def __init__(self, console, peer, repeater, settings):
        CommandHandler.__init__(self, console)
        self.repeater = repeater
        self.settings = settings
        self.peer_to_remove = peer

    def start(self):
        d = self._remove_peer()
        d.chainDeferred(self.finished_deferred)

    def _remove_peer(self):
        d = self.settings.remove_approved_peer(self.peer_to_remove.host, int(self.peer_to_remove.port))
        d.addCallback(lambda _: self.repeater.remove_approved_peer(self.peer_to_remove))
        d.addCallback(lambda _: self.console.sendLine("Successfully removed peer"))
        return d

class DeleteApprovedPeerFactory(ApprovedPeerChooserFactory):
    control_handler_class = DeleteApprovedPeer

class ShowApprovedPeers(CommandHandler):
    prompt_description = "Show the list of peers approved to be checked for valuable blob hashes"

    def __init__(self, console, repeater):
        CommandHandler.__init__(self, console)
        self.repeater = repeater

    def start(self):
        #assert line is None, "Show approved peers should not be passed any arguments"
        d = self._show_peers()
        d.chainDeferred(self.finished_deferred)

    def _show_peers(self):
        peer_string = "Approved peers:\n"
        for peer in self.repeater.approved_peers:
            peer_string += str(peer) + "\n"
        self.console.sendLine(peer_string)
        return defer.succeed(None)

class ShowApprovedPeersFactory(CommandHandlerFactory):
    control_handler_class = ShowApprovedPeers

class RepeaterStatus(CommandHandler):
    prompt_description = "Show the repeater's status"

    def __init__(self, console, repeater):
        CommandHandler.__init__(self, console)
        self.repeater = repeater

    def start(self):
        #assert line is None, "Show repeater status should not be passed any arguments"
        self._show_status()
        self.finished_deferred.callback(None)

    def _show_status(self):
        status_string = "Repeater status: " + self.repeater.status() + "\n"

        if self.repeater.stopped is False:
            max_space = self.repeater.progress_manager.max_space
            space_used = 0
            for blob in self.repeater.download_manager.blobs:
                if blob.is_validated():
                    space_used += blob.get_length()

            status_string += "Maximum space: " + str(max_space) + " bytes\n"
            status_string += "Space used: " + str(space_used) + " bytes\n"
        self.console.sendLine(status_string)

class RepeaterStatusFactory(CommandHandlerFactory):
    control_handler_class = RepeaterStatus

class ModifyDataPaymentRate(ModifyPaymentRate):
    prompt_description = "Modify Blind Repeater data payment rate"

    def __init__(self, console, repeater, settings):
        ModifyPaymentRate.__init__(self, console)
        self._prompt_choices['unset'] = (self._unset, "Use the application default data rate")
        self.payment_rate_manager = repeater.payment_rate_manager
        self.settings = settings

    def _unset(self):
        self._set_rate(None)
        return defer.succeed("Using the application default data rate")

    def _set_rate(self, rate):

        def set_data_payment_rate(rate):
            self.payment_rate_manager.min_blob_data_payment_rate = rate

        d = self.settings.save_data_payment_rate(rate)
        d.addCallback(lambda _: set_data_payment_rate(rate))
        return d

    def _get_current_status(self):
        effective_rate = self.payment_rate_manager.get_effective_min_blob_data_payment_rate()
        if self.payment_rate_manager.min_blob_data_payment_rate is None:
            status = "The current data payment rate is set to use the application default, "
            status += str(effective_rate)
        else:
            status = "The current data payment rate is "
            status += str(effective_rate)
        return status

class ModifyDataPaymentRateFactory(CommandHandlerFactory):
    control_handler_class = ModifyDataPaymentRate

class ModifyInfoPaymentRate(ModifyPaymentRate):
    prompt_description = "Modify Blind Repeater valuable info payment rate"

    def __init__(self, console, repeater, settings):
        ModifyPaymentRate.__init__(self, console)
        self.payment_rate_manager = repeater.payment_rate_manager
        self.settings = settings

    def _set_rate(self, rate):

        def set_info_payment_rate(rate):
            self.payment_rate_manager.min_valuable_blob_info_payment_rate = rate

        d = self.settings.save_valuable_info_payment_rate(rate)
        d.addCallback(lambda _: set_info_payment_rate(rate))
        return d

    def _get_current_status(self):
        status = "The current valuable blob info payment rate is "
        status += str(self.payment_rate_manager.min_valuable_blob_info_payment_rate)
        return status

class ModifyInfoPaymentRateFactory(CommandHandlerFactory):
    control_handler_class = ModifyInfoPaymentRate

class ModifyHashPaymentRate(ModifyPaymentRate):
    prompt_description = "Modify Blind Repeater valuable hash payment rate"

    def __init__(self, console, repeater, settings):
        ModifyPaymentRate.__init__(self, console)
        self.payment_rate_manager = repeater.payment_rate_manager
        self.settings = settings

    def _set_rate(self, rate):

        def set_hash_payment_rate(rate):
            self.payment_rate_manager.min_valuable_blob_hash_payment_rate = rate

        d = self.settings.save_valuable_hash_payment_rate(rate)
        d.addCallback(lambda _: set_hash_payment_rate(rate))
        return d

    def _get_current_status(self):
        status = "The current valuable blob hash payment rate is "
        status += str(self.payment_rate_manager.min_valuable_blob_hash_payment_rate)
        return status

class ModifyHashPaymentRateFactory(CommandHandlerFactory):
    control_handler_class = ModifyHashPaymentRate

class ModifyRepeaterOptions(RecursiveCommandHandler):
    prompt_description = "Modify Blind Repeater options"

    def __init__(self, console, repeater, lbry_session, settings):
        self.repeater = repeater
        self.lbry_session = lbry_session
        self.settings = settings
        RecursiveCommandHandler.__init__(self, console)

    def _get_control_handler_factories(self):
        return [ModifyDataPaymentRateFactory(self.repeater, self.settings),
                ModifyInfoPaymentRateFactory(self.repeater, self.settings),
                ModifyHashPaymentRateFactory(self.repeater, self.settings),
                UpdateMaxSpaceFactory(self.repeater, self.settings),
                AddApprovedPeerFactory(self.repeater, self.lbry_session.peer_manager, self.settings),
                DeleteApprovedPeerChooserFactory(self.repeater, self.settings),
                ]

class ModifyRepeaterOptionsFactory(CommandHandlerFactory):
    control_handler_class = ModifyRepeaterOptions


text:
#ifndef XPD_ENVIRONMENT_HPP
#define XPD_ENVIRONMENT_HPP

#include "xpd_mutex.hpp"
#include <string>

namespace xpd
{
    // ==================================================================================== //
    //                                      ENVIRONMENT                                     //
    // ==================================================================================== //

    //! @brief The environment manages xpd global variables and methods.
    class environment
    {
    public:
        //! @brief Initializes the environment.
        static void initialize() xpd_noexcept;

        //! @brief Clears the environment.
        static void  clear() xpd_noexcept;

        //! @brief Gets the major version of Pure Data.
        static unsigned int version_major() xpd_noexcept;

        //! @brief Gets the minor version of Pure Data.
        static unsigned int version_minor() xpd_noexcept;

        //! @brief Gets the bug version of Pure Data.
        static unsigned int version_bug() xpd_noexcept;

        //! @brief Adds a path the search path.
        static void searchpath_add(std::string const& path) xpd_noexcept;

        //! @brief Clears all the search path.
        static void searpath_clear() xpd_noexcept;
    };
}

#endif // XPD_ENVIRONMENT_HPP