text:
// Generated from /POI/java/org/apache/poi/sl/draw/binding/STRectAlignment.java

#pragma once

#include <java/io/fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/sl/draw/binding/fwd-POI.hpp>
#include <java/lang/Enum.hpp>

template<typename ComponentType, typename... Bases> struct SubArray;
namespace java
{
    namespace io
    {
typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray;
    } // io

    namespace lang
    {
typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray;
typedef ::SubArray< ::java::lang::Enum, ObjectArray, ComparableArray, ::java::io::SerializableArray > EnumArray;
    } // lang
} // java

namespace poi
{
    namespace sl
    {
        namespace draw
        {
            namespace binding
            {
typedef ::SubArray< ::poi::sl::draw::binding::STRectAlignment, ::java::lang::EnumArray > STRectAlignmentArray;
            } // binding
        } // draw
    } // sl
} // poi

struct default_init_tag;

class poi::sl::draw::binding::STRectAlignment final
    : public ::java::lang::Enum
{

public:
    typedef ::java::lang::Enum super;

public: /* package */
    static STRectAlignment *TL;
    static STRectAlignment *T;
    static STRectAlignment *TR;
    static STRectAlignment *L;
    static STRectAlignment *CTR;
    static STRectAlignment *R;
    static STRectAlignment *BL;
    static STRectAlignment *B;
    static STRectAlignment *BR;

private:
    ::java::lang::String* value_ {  };
protected:
    void ctor(::java::lang::String* name, int ordinal, ::java::lang::String* v);

public:
    ::java::lang::String* value();
    static STRectAlignment* fromValue(::java::lang::String* v);

    // Generated

private:
    STRectAlignment(::java::lang::String* name, int ordinal, ::java::lang::String* v);
protected:
    STRectAlignment(const ::default_init_tag&);

public:
    static ::java::lang::Class *class_();
    static STRectAlignment* valueOf(::java::lang::String* a0);
    static STRectAlignmentArray* values();

private:
    virtual ::java::lang::Class* getClass0();
};


text:
// Header for CSimpleTitleTable class

#ifndef __CSIMPLETITLETABLE__MULBERRY__
#define __CSIMPLETITLETABLE__MULBERRY__

#include "CTitleTable.h"

// Classes
class CSimpleTitleTable : public CTitleTable
{
public:
	CSimpleTitleTable(JXScrollbarSet* scrollbarSet,
	      JXContainer* enclosure,
	      const HSizingOption hSizing,
	      const VSizingOption vSizing,
	      const JCoordinate x, const JCoordinate y,
	      const JCoordinate w, const JCoordinate h)
	  : CTitleTable(scrollbarSet, enclosure, hSizing, vSizing, x, y, w, h) {}
	virtual ~CSimpleTitleTable() {}

	void LoadTitles(const char* rsrcid, unsigned long count, bool clear_existing = false);
	void AddTitle(const cdstring& title);
	void ChangeTitle(TableIndexT col, const cdstring& title);

protected:
	virtual void	MenuChoice(JIndex col, bool sort_col, JIndex menu_item) {}

};

#endif

redpajama_set_name: RedPajamaGithub


text:
#ifndef _IRTKGRADIENTIMAGE_X_H

#define _IRTKGRADIENTIMAGE_X_H

#include <irtkGradientImage.h>

/**
 * Class for caluclating the gradient of an image in the x-direction.
 */

template <class VoxelType>
class irtkGradientImageX : public irtkGradientImage<VoxelType>
{
  irtkImageFilterMacro(irtkGradientImageX);

protected:

  // Calculate the gradient on a single voxel.
  virtual double Run(int, int, int, int);

public:

  /// Run the convolution filter
  virtual void Run();
};

#endif


text:
package stepdefinitions;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;

import gherkin.formatter.model.Result;

import com.github.shell88.bddvideoannotator.javaadapters.CucumberReportingAdapter;
import com.github.shell88.bddvideoannotator.javaadapters.ServerConnector;
import com.github.shell88.bddvideoannotator.stubjava.StepResult;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class ResultTest {

  CucumberReportingAdapter adapterWithoutConnection;
  StepResult convertedResult;

  @Given("^i have an instance of the BDD-Adapter for Cucumber-JVM without a server connection$")
  public void i_have_an_instance_of_the_BDD_Adapter_for_Cucumber_JVM_without_a_server_connection()
      throws Throwable {
    ServerConnector mockedServerConnector = mock(ServerConnector.class);
    adapterWithoutConnection = new CucumberReportingAdapter(
        mockedServerConnector);
  }

  @When("^Cucumber reports \"(FAILED#AssertionError)\"$")
  public void cucumber_reports_assertion_error(String status) throws Throwable {

    Result res = new Result("FAILED", 0L, new AssertionError(), null);

    StepResult test = adapterWithoutConnection.toServerStepResult(res);
    convertedResult = test;
  }

  @When("^Cucumber reports \"(FAILED|PASSED|SKIPPED|UNDEFINED|PENDING|NOTACUCUMBERSTATUS)\"$")
  public void cucumber_reports_result_without_assertion_error(String status)
      throws Throwable {
    Result res = new Result(status, 0L, "");
    StepResult test = adapterWithoutConnection.toServerStepResult(res);
    convertedResult = test;
  }

  @Then("^the BDD-Adapter should convert it to \"(.*?)\"$")
  public void the_BDD_Adapter_should_convert_it_to(String target)
      throws Throwable {

    assertEquals(StepResult.valueOf(target), convertedResult);

  }

}


text:
import random
from soccerpy.agent import Agent as baseAgent
from soccerpy.world_model import WorldModel

# methods from actionHandler are
# CATCH = "catch"(rel_direction)
# CHANGE_VIEW = "change_view"
# DASH = "dash"(power)
# KICK = "kick"(power, rel_direction)
# MOVE = "move"(x,y) only pregame
# SAY = "say"(you_can_try_cursing)
# SENSE_BODY = "sense_body"
# TURN = "turn"(rel_degrees in 360)
# TURN_NECK = "turn_neck"(rel_direction)

# potentially useful from aima
# learning.py
# mdp
#

class Agent(baseAgent):
    """
    The extended Agent class with specific heuritics
    """

    def think(self):
        """
        Performs a single step of thinking for our agent.  Gets called on every
        iteration of our think loop.
        """

        # DEBUG:  tells us if a thread dies
        if not self.__think_thread.is_alive() or not self.__msg_thread.is_alive():
            raise Exception("A thread died.")

        # take places on the field by uniform number
        if not self.in_kick_off_formation:
            print "the side is", self.wm.side

            # used to flip x coords for other side
            side_mod = 1
            if self.wm.side == WorldModel.SIDE_R:
                side_mod = -1

            if self.wm.uniform_number == 1:
                self.wm.teleport_to_point((-5 * side_mod, 30))
            elif self.wm.uniform_number == 2:
                self.wm.teleport_to_point((-40 * side_mod, 15))
            elif self.wm.uniform_number == 3:
                self.wm.teleport_to_point((-40 * side_mod, 00))
            elif self.wm.uniform_number == 4:
                self.wm.teleport_to_point((-40 * side_mod, -15))
            elif self.wm.uniform_number == 5:
                self.wm.teleport_to_point((-5 * side_mod, -30))
            elif self.wm.uniform_number == 6:
                self.wm.teleport_to_point((-20 * side_mod, 20))
            elif self.wm.uniform_number == 7:
                self.wm.teleport_to_point((-20 * side_mod, 0))
            elif self.wm.uniform_number == 8:
                self.wm.teleport_to_point((-20 * side_mod, -20))
            elif self.wm.uniform_number == 9:
                self.wm.teleport_to_point((-10 * side_mod, 0))
            elif self.wm.uniform_number == 10:
                self.wm.teleport_to_point((-10 * side_mod, 20))
            elif self.wm.uniform_number == 11:
                self.wm.teleport_to_point((-10 * side_mod, -20))

            self.in_kick_off_formation = True

            return

        # determine the enemy goal position
        # self.enemy_goal_pos = None
        # self.own_goal_pos = None
        if self.wm.side == WorldModel.SIDE_R:
            self.enemy_goal_pos = (-55, 0)
            self.own_goal_pos = (55, 0)
        else:
            self.enemy_goal_pos = (55, 0)
            self.own_goal_pos = (-55, 0)

        if not self.wm.is_before_kick_off() or self.wm.is_kick_off_us() or self.wm.is_playon():
            # The main decision loop
            return self.decisionLoop()

    # Heuristics begin

    # check if ball is close to self
    def ball_close(self):
        return self.wm.ball.distance < 10

    # check if enemy goalpost is close enough
    def goalpos_close(self):
        return self.wm.get_distance_to_point(self.enemy_goal_pos) < 20

    # check if path to target's coordinate is clear, by direction
    def is_clear(self, target_coords):
        q = self.wm.get_nearest_enemy()
        if q == None:
            return False
        q_coords = self.wm.get_object_absolute_coords(q)
        qDir = self.wm.get_angle_to_point(q_coords)
        qDist = self.wm.get_distance_to_point(q_coords)

        tDir = self.wm.get_angle_to_point(target_coords)
        tDist = self.wm.get_distance_to_point(target_coords)

        # the closest teammate is closer, or angle is clear
        return tDist < qDist or abs(qDir - tDir) > 20

    # Action decisions start
    #
    # find the ball by rotating if ball not found
    def find_ball(self):
        # find the ball
        if self.wm.ball is None or self.wm.ball.direction is None:
            self.wm.ah.turn(30)
            if not -7 <= self.wm.ball.direction <= 7:
                self.wm.ah.turn(self.wm.ball.direction / 2)

            return

    # look around randomly
    def defaultaction(self):
        # print "def"
        # kick off!
        # if self.wm.is_before_kick_off():
        #     # player 9 takes the kick off
        #     if self.wm.uniform_number == 9:
        #         if self.wm.is_ball_kickable():
        #             # kick with 100% extra effort at enemy goal
        #             self.wm.kick_to(self.enemy_goal_pos, 1.0)
        #         else:
        #             # move towards ball
        #             if self.wm.ball is not None:
        #                 if (self.wm.ball.direction is not None and
        #                         -7 <= self.wm.ball.direction <= 7):
        #                     if self.wm.get_distance_to_point(self.own_goal_pos) < 40:
        #                         return
        #                         # self.wm.ah.dash(50)
        #                     else:
        #                         self.wm.turn_body_to_point(self.own_goal_pos)
        #                         # self.wm.ah.dash(50)
        #                 else:
        #                     self.wm.turn_body_to_point((0, 0))

        #         # turn to ball if we can see it, else face the enemy goal
        #         if self.wm.ball is not None:
        #             self.wm.turn_neck_to_object(self.wm.ball)

        #         return

        # # attack!
        # else:
        #     # find the ball
        #     if self.wm.ball is None or self.wm.ball.direction is None:
        #         self.wm.ah.turn(30)

        #         return

        #     # kick it at the enemy goal
        #     if self.wm.is_ball_kickable():
        #         self.wm.kick_to(self.enemy_goal_pos, 1.0)
        #         return
        #     else:
        #         # move towards ball
        #         if -7 <= self.wm.ball.direction <= 7:
        #             if self.wm.get_distance_to_point(self.own_goal_pos) < 40:
        #                 return
        #                 # self.wm.ah.dash(65)
        #             else:
        #                 self.wm.turn_body_to_point(self.own_goal_pos)
        #                 # self.wm.ah.dash(50)
        #         else:
        #             # face ball
        #             self.wm.ah.turn(self.wm.ball.direction / 2)

                return

    # condition for shooting to the goal
    def shall_shoot(self):
        return self.wm.is_ball_kickable() and self.goalpos_close() and self.is_clear(self.enemy_goal_pos)

    # do shoot
    def shoot(self):
        print "shoot"
        return self.wm.kick_to(self.enemy_goal_pos, 1.0)

    # condition for passing to the closest teammate
    # if can kick ball, teammate is closer to goal, path clear
    def shall_pass(self):
        # self.defaultaction()
        p = self.wm.get_nearest_teammate()
        if p == None:
            return False
        p_coords = self.wm.get_object_absolute_coords(p)
        pDistToGoal = self.wm.euclidean_distance(p_coords, self.enemy_goal_pos)
        myDistToGoal = self.wm.get_distance_to_point(self.enemy_goal_pos)
        # kickable, pass closer to goal, path is clear
        return self.wm.is_ball_kickable() and pDistToGoal < myDistToGoal and self.is_clear(p_coords)

    # do passes
    def passes(self):
        print "pass"
        p = self.wm.get_nearest_teammate()
        if p == None:
            return False
        p_coords = self.wm.get_object_absolute_coords(p)
        dist = self.wm.get_distance_to_point(p_coords)
        power_ratio = 2*dist/55.0
        # kick to closest teammate, power is scaled
        return self.wm.kick_to(p_coords, power_ratio)

    # condition for dribbling, if can't shoot or pass
    def shall_dribble(self):
        # find the ball
        # self.find_ball()
        # if self.wm.ball is None or self.wm.ball.direction is None:
            # self.wm.ah.turn(30)
        return self.wm.is_ball_kickable()

    # dribble: turn body, kick, then run towards ball
    def dribble(self):
        print "dribbling"
        self.wm.kick_to(self.enemy_goal_pos, 1.0)
        self.wm.turn_body_to_point(self.enemy_goal_pos)
        self.wm.align_neck_with_body()
        if self.wm.get_distance_to_point(self.own_goal_pos) < 40:
            self.wm.ah.dash(50)
        else:
            self.wm.turn_body_to_point(self.own_goal_pos)
            self.wm.ah.dash(50)
        return

    # if enemy has the ball, and not too far move towards it
    def shall_move_to_ball(self):
        # while self.wm.ball is None:
            # self.find_ball()
        # self.wm.align_neck_with_body()
        return self.wm.is_ball_owned_by_enemy() and self.wm.ball.distance < 10 and self.wm.get_distance_to_point(self.own_goal_pos) < 10

    # move to ball, if enemy owns it
    def move_to_ball(self):
        print "move_to_ball"
        if self.wm.get_distance_to_point(self.own_goal_pos) < 10:
            self.wm.ah.dash(60)
        else:
            self.wm.turn_body_to_point(self.own_goal_pos)
            self.wm.ah.dash(50)
        return

    # defensive, when ball isn't ours, and has entered our side of the field
    def shall_move_to_defend(self):
        # self.defaultaction()
        if self.wm.ball is not None or self.wm.ball.direction is not None:
            b_coords = self.wm.get_object_absolute_coords(self.wm.ball)
            return self.wm.is_ball_owned_by_enemy() and self.wm.euclidean_distance(self.own_goal_pos, b_coords) < 55.0
        return False

    # defend
    def move_to_defend(self):
        print "move_to_defend"
        q = self.wm.get_nearest_enemy()
        if q == None:
            return False
        q_coords = self.wm.get_object_absolute_coords(q)
        qDir = self.wm.get_angle_to_point(q_coords)
        qDistToOurGoal = self.wm.euclidean_distance(self.own_goal_pos, q_coords)
        # if close to the goal, aim at it
        if qDistToOurGoal < 55:
            self.wm.turn_body_to_point(q_coords)
        # otherwise aim at own goalpos, run there to defend
        else:
            self.wm.turn_body_to_point(self.own_goal_pos)

        self.wm.align_neck_with_body()
        if self.wm.get_distance_to_point(self.own_goal_pos) < 40:
            self.wm.ah.dash(80)
        else:
            self.wm.turn_body_to_point(self.own_goal_pos)
            self.wm.ah.dash(50)
        return

    # when our team has ball, and self is not close enough to goalpos. advance to enemy goalpos
    def shall_move_to_enemy_goalpos(self):
        return self.wm.is_ball_owned_by_us() and not self.goalpos_close()

    # if our team has the ball n u r striker
    def move_to_enemy_goalpos(self):
        print "move_to_enemy_goalpos"
        if self.wm.is_ball_kickable():
            # kick with 100% extra effort at enemy goal
            self.wm.kick_to(self.enemy_goal_pos, 1.0)
        self.wm.turn_body_to_point(self.enemy_goal_pos)
        self.wm.align_neck_with_body()
        if self.wm.get_distance_to_point(self.own_goal_pos) < 40:
            self.wm.ah.dash(70)
        else:
            self.wm.turn_body_to_point(self.own_goal_pos)
            self.wm.ah.dash(50)
        return

    def decisionLoop(self):
        try:
            self.find_ball()
            if self.wm.get_distance_to_point(self.own_goal_pos) > 5:
                # print "overstepping"
                self.wm.turn_body_to_point(self.own_goal_pos)
                self.wm.turn_body_to_point(self.own_goal_pos)
                self.wm.turn_body_to_point(self.own_goal_pos)
                self.wm.ah.dash(30)
                return
            elif self.shall_move_to_ball():
                return self.move_to_ball()
            elif self.shall_move_to_defend():
                return self.move_to_defend()
            else:
                return self.defaultaction()
        except:
            # print "exceptions thrown, using fallback"
            self.defaultaction()

# by role: striker, defender
# do the same preconds, but def on role diff actions
# 1.
# shoot:
# close enuf to ball and to self.enemy_goal_pos
# if self.wm.ball.distance < 10 and self.get_distance_to_point(self.enemy_goal_pos) < 20 and self.is_ball_kickable():

# shoot
# pass
# move

# striker:
#

# strategy: ordered
# 1. close to ball: grab, carry toward goal, pass or shoot
# 2. ain't, move to enemy (if enemy has ball), goal (if we have ball n jersey num), ball (if enemy n closest, or jersey num)
# 3.

# conditions shd be:
# shoot: ball aint none, ball kickable, close to goalpos

# Enum fields
# self.get_distance_to_point(self.enemy_goal_pos)
# self.get_angle_to_point(self.enemy_goal_pos)
# self.wm.ball.distance
# self.wm.ball.direction
# p = self.get_nearest_teammate()
# p.distance
# p.direction
# q = self.get_neatest_enemy()
# q.distance
# q.direction
# self.is_ball_owned_by_us
# self.is_ball_owned_by_enemy
# self.is_ball_kickable

# actions and their triggers
# shoot
# pass
# move

# print dir(WorldModel(''))
# print dir(Agent())

# va = 1
# print None or va[0]
# print random.randrange(-30,30)


text:
<?php

namespace source\modules\system\models\config;

use source\libs\Common;
use source\models\ConfigForm;
use source\modules\system\SystemInfo;

class BasicConfig extends ConfigForm
{

    public function _init() {
        $this->setBelongModule(new SystemInfo());
    }

    public $site_logo;
    public $site_name;
    public $site_description;
    public $site_about;
    public $site_url;
    public $site_email;

    public $lang;
    public $icp;
    public $stat;

    public $status;

    public function rules() {
        return [
            [['site_logo', 'site_name', 'site_description', 'site_about', 'site_url', 'lang', 'icp', 'stat', ], 'string'],
            [['site_email'], 'email'],
            [['status'], 'boolean'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'site_logo' => '网站logo',
            'site_name' => '网站名称',
            'site_description' => '网站描述',
            'site_about' => '关于',
            'site_email' => '站点Email',
            'lang' => '站点语言',
            'icp' => '备案号',
            'stat' => '统计代码',
            'status' => '站点状态',
        ];
    }

}


text:
import * as React from 'react'

export default () =>

This is my component


text:
package workers

import (
	"github.com/customerio/gospec"
	. "github.com/customerio/gospec"
)

func QueueSpec(c gospec.Context) {
	was := Config.Namespace
	Config.Namespace = "prod:"

	c.Specify("QueueSize", func() {
		c.Specify("returns the actual size of the queue", func() {
			for i := 1; i <= 10; i++ {
				Enqueue("queue1", "Compare", []string{"foo", "bar"})
				queueSize, err := QueueSize("queue1")
				c.Expect(err, Equals, nil)
				c.Expect(queueSize, Equals, i)
			}
		})
	})

	c.Specify("ScheduledQueueSize", func() {
		c.Specify("returns the number of scheduled jobs", func() {
			for i := 1; i <= 10; i++ {
				EnqueueIn("queue2", "Compare", 10, []string{"foo", "bar"})
				queueSize, err := ScheduledQueueSize()
				c.Expect(err, Equals, nil)
				c.Expect(queueSize, Equals, i)
			}
		})
	})

	Config.Namespace = was
}


text: console.log("I was already hashed!");


text:
package im.AfriChat.runtime;

import im.AfriChat.runtime.cocoa.CocoaLifecycleProvider;

public class LifecycleRuntimeProvider extends CocoaLifecycleProvider {

}


text:
<?php

namespace Blog\DB;

use Intahwebz\TableMap\SQLTableMap;

class BlogPostTable extends SQLTableMap
{
    public function getTableDefinition()
    {
        $tableDefinition = array(
            'schema' => 'basereality',
            'tableName' => 'blogPost',
            'columns' => array(
                array('blogPostID', 'primary' => true, 'autoInc' => true ),
                array('contentID', 'type' => 'i', 'foreignKey' => 'content'),
                array('title'),
                array('isActive', 'type' => 'i', 'default' => 0),
                array('blogPostTextID', 'type' => 'i', 'foreignKey' => 'blogPostText'),
            ),
        );

        return $tableDefinition;
    }
}


text:
package conf

import (
	"errors"
	"io/ioutil"
	"log"
	"os"
	"time"

	"github.com/BurntSushi/toml"
	"github.com/davecgh/go-spew/spew"
)

type MysqlConfiguration struct {
	ConnectionString string `toml:"connection-string"`
	Select           string `toml:"select"`
}

type MqttConfiguration struct {
	ListenAddress string `toml:"listen-address"`
	Cert          string `toml:"cert"`
	Key           string `toml:"key"`
}

type InfluxConfiguration struct {
	Host     string `toml:"host"`
	User     string `toml:"user"`
	Pass     string `toml:"pass"`
	Database string `toml:"database"`
}

type LibratoConfiguration struct {
	Email string `toml:"email"`
	Token string `toml:"token"`
}

type Configuration struct {
	BackendServers []string `toml:"backend-servers"`
	User           string   `toml:"user"`
	Pass           string   `toml:"pass"`

	// typically us-west | us-east
	// prepended to metrics
	Region string `toml:"region"`

	// typically develop | beta | prod
	// prepended to metrics
	Environment string `toml:"env"`

	ReadTimeout int `toml:"read-timeout"`

	MqttStoreMysql MysqlConfiguration   `toml:"mqtt-store"`
	Mqtt           MqttConfiguration    `toml:"mqtt"`
	Influx         InfluxConfiguration  `toml:"influx"`
	Librato        LibratoConfiguration `toml:"librato"`
}

func (c *Configuration) GetReadTimeout() time.Duration {
	return time.Second * time.Duration(c.ReadTimeout)
}

func (c *Configuration) envOverrides() {

	if backendUser := os.Getenv("BACKEND_USER"); backendUser != "" {
		c.User = backendUser
	}

	if backendPass := os.Getenv("BACKEND_PASS"); backendPass != "" {
		c.Pass = backendPass
	}

}

func (c *Configuration) validate() error {

	if len(c.BackendServers) == 0 {
		return errors.New("At least one backend servers required.")
	}

	return nil
}

func (c *Configuration) assignDefaults() {

	if c.Region == "" {
		c.Region = "us-east"
	}

	if c.Environment == "" {
		c.Environment = "develop"
	}

	if c.Mqtt.ListenAddress == "" {
		c.Mqtt.ListenAddress = ":1883"
	}

	if c.User == "" {
		c.User = "guest"
	}

	if c.Pass == "" {
		c.Pass = "guest"
	}

	// need a way to merge defaults..
	if c.MqttStoreMysql.ConnectionString == "" {
		c.MqttStoreMysql.ConnectionString = "root:@tcp(127.0.0.1:3306)/mqtt"
	}

	if c.MqttStoreMysql.Select == "" {
		c.MqttStoreMysql.Select = "select uid, mqtt_id from users where mqtt_id = ?"
	}

}

func LoadConfiguration(fileName string) *Configuration {
	config, err := parseTomlConfiguration(fileName)
	if err != nil {
		log.Println("Couldn't parse configuration file: " + fileName)
		panic(err)
	}
	return config
}

func parseTomlConfiguration(filename string) (*Configuration, error) {
	body, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	tomlConfiguration := &Configuration{}
	_, err = toml.Decode(string(body), tomlConfiguration)
	if err != nil {
		return nil, err
	}
	log.Println(spew.Sprintf("sql = %v", tomlConfiguration))

	tomlConfiguration.assignDefaults()
	tomlConfiguration.envOverrides()

	err = tomlConfiguration.validate()

	if err != nil {
		return nil, err
	}

	return tomlConfiguration, nil
}


text:
namespace DentistSpace.Data.Models
{
    using System;
    using DentistSpace.Data.Common.Models;

    public class Image : BaseModel<int>
    {
        public Guid Title { get; set; }
    }
}


text:
package com.xgimi.commonhelper;
import java.util.Collections;
import java.util.List;
import com.mstar.android.tvapi.common.TvManager;

public class PowerManager {
    public static int getAdcLevel(List list, int i, int j) {
        Collections.sort(list);
        for (int k = 0; k < i; k++) {
            list.remove(0);
            list.remove(-1 + list.size());
        }
        int l = 0;
        for (int i1 = 0; i1 < list.size(); i1++)
            l += ((Integer) list.get(i1)).intValue();
        int j1 = Math.round((float) l / (float) list.size());
        if (isAdOnline()) j1 -= 5;
        int k1 = Math.round(100 * (35 - (174 - j - j1)) / 35F);
        if (k1 > 100) k1 = 100;
        else if (k1 < 0) return 0;
        return k1;
    }
    public static int getBatteryADCvalue() {
        byte byte0;
        short word0;
        if (XgimiDevice.isZ3MP()) byte0 = 4;
        else if (XgimiDevice.isZ4Air()) byte0 = 3;
        else return 0;
        try {
            word0 = TvManager.getInstance().getSarAdcLevel(byte0);
        } catch (Exception exception) {
            exception.printStackTrace();
            return 0;
        }
        return word0;
    }
    public static boolean isAdOnline() {
        int i;
        try {
            i = TvManager.getInstance().getGpioDeviceStatus(149);
        } catch (Exception exception) {
            exception.printStackTrace();
            return false;
        }
        return i <= 0;
    }
    public static void ShutDown() {
        XgimiKey.sendOneKeyDownUp(26);
    }
    public PowerManager() {}
}


text:
#import "WHSelectionViewController.h"

@interface WHSelectionViewController ()

@end

NSString  * const cellId = @"CellID";

@implementation WHSelectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellId];

    if (!self.refreshControl) {
        [self setupRefreshControl];
    }
}

- (void)setList:(NSArray *)list {
    _list = list;

    [self.tableView reloadData];
}

- (void)setupRefreshControl {
    self.refreshControl = [[UIRefreshControl alloc] initWithFrame:CGRectZero];
    [self.refreshControl addTarget:self
                            action:@selector(didRefresh:)
                  forControlEvents:UIControlEventValueChanged];
}

- (void)didRefresh:(id)sender {
    __weak typeof(self) weakSelf = self;

    [self setRefreshActive:YES];
    [self.delegate selectionViewController:self didSelectRefreshWithRefreshHandler:^(NSArray *list, NSError *error) {
        if (list) {
            weakSelf.list = list;
        }

        [weakSelf setRefreshActive:NO];
    }];
}

- (void)setRefreshActive:(BOOL)active {
    if (!self.refreshControl) {
        [self setupRefreshControl];
    }

    if (active) {
        [self.refreshControl beginRefreshing];
    } else {
        [self.refreshControl endRefreshing];
    }
}

- (void)setSelectedListItem:(id)selectedListItem {
    _selectedListItem = selectedListItem;

    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    id listItem = self.list[indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.textLabel.text = listItem;

    UITableViewCellAccessoryType accessory = UITableViewCellAccessoryNone;

    if (listItem == self.selectedListItem) {
        accessory = UITableViewCellAccessoryCheckmark;
    }

    cell.accessoryType = accessory;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray *indexpaths = nil;

    if (self.selectedListItem) {
        id previousObject = self.selectedListItem;

        indexpaths = @[[NSIndexPath indexPathForRow:[self.list indexOfObject:previousObject] inSection:0],
                       [NSIndexPath indexPathForRow:indexPath.row inSection:0]];
    } else {
        indexpaths = @[[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
    }

    self.selectedListItem = self.list[indexPath.row];

    [self.tableView reloadRowsAtIndexPaths:indexpaths withRowAnimation:UITableViewRowAnimationNone];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.delegate selectionViewController:self didSelectModelObject:self.selectedListItem];
    });
}

@end


text:
<?php

namespace Molajo\Resource\Proxy;

use CommonApi\Exception\RuntimeException;
use CommonApi\Resource\ResourceInterface;
use stdClass;

/**
 * Resource Scheme Class
 *
 * @package    Molajo
 * @copyright  2014-2015 Amy Stephen. All rights reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @since      1.0.0
 */
trait SchemeTrait
{
    /**
     * Saved Namespace Array for yet to be defined Resource Adapters
     *
     * @var    array
     * @since  1.0.0
     */
    protected $namespace_array = array();

    /**
     * Requested Scheme
     *
     * @var    string
     * @since  1.0.0
     */
    protected $requested_scheme;

    /**
     * Name of requested resource adapter
     *
     * @var    object  CommonApi\Resource\ResourceInterface
     * @since  1.0.0
     */
    protected $requested_adapter;

    /**
     * Scheme Instance
     *
     * @var    object  CommonApi\Resource\SchemeInterface
     * @since  1.0.0
     */
    protected $scheme;

    /**
     * Define scheme, allowable file extensions and adapter instance
     *
     * @param   string            $scheme_name
     * @param   ResourceInterface $adapter
     * @param   array             $extensions
     *
     * @return  $this
     * @since   1.0.0
     */
    public function setScheme($scheme_name, ResourceInterface $adapter, array $extensions = array())
    {
        $this->scheme->setScheme($scheme_name, $adapter, $extensions);

        $this->getScheme($scheme_name);

        $this->requested_adapter->setResourceGetCallback($this->get_resource_callback);

        $this->setAdapterNamespaces();

        return $this;
    }

    /**
     * Get Scheme
     *
     * @param   string $scheme_name
     *
     * @return  null|object
     * @since   1.0.0
     */
    public function getScheme($scheme_name)
    {
        $this->requested_scheme = ucfirst(strtolower($scheme_name));

        $response = $this->scheme->getScheme($this->requested_scheme);

        if ($response === null) {
            throw new RuntimeException('Resource getScheme Scheme not found for request: ' . $this->requested_scheme);
        }

        $this->requested_adapter = $response->adapter;

        return $response;
    }

    /**
     * Set namespace prefixes for Adapter
     *
     * @return  $this
     * @since   1.0.0
     */
    public function setAdapterNamespaces()
    {
        if (count($this->namespace_array) === 0) {
            return $this;
        }

        foreach ($this->namespace_array as $row) {
            $this->requested_adapter->setNamespace($row->namespace_prefix, $row->base_directory, $row->prepend);
        }

        return $this;
    }

    /**
     * Map a namespace prefix to a filesystem path
     *
     * @param   string  $namespace_prefix
     * @param   string  $base_directory
     * @param   boolean $prepend
     *
     * @return  $this
     * @since   1.0.0
     */
    protected function saveNamespaceArray($namespace_prefix, $base_directory, $prepend = true)
    {
        $row                   = new stdClass();
        $row->namespace_prefix = $namespace_prefix;
        $row->base_directory   = $base_directory;
        $row->prepend          = $prepend;

        $this->namespace_array[] = $row;

        return $this;
    }

    /**
     * Verify if resource namespace is defined
     *
     * @param   string $resource_namespace
     * @param   array  $options
     *
     * @return  array
     * @since   1.0.0
     */
    protected function locateScheme($resource_namespace, array $options = array())
    {
        $this->getUriScheme($resource_namespace);

        $resource_namespace = $this->removeUriScheme($resource_namespace);

        $this->getScheme($this->requested_scheme);

        $options['scheme_name'] = $this->requested_scheme;

        return array('resource_namespace' => $resource_namespace, 'options' => $options);
    }

    /**
     * Set Uri Scheme
     *
     * @param   string $uri
     *
     * @return  $this
     * @since   1.0.0
     * @throws  \CommonApi\Exception\RuntimeException
     */
    protected function getUriScheme($uri)
    {
        $this->requested_scheme = parse_url($uri, PHP_URL_SCHEME);

        if ($this->requested_scheme === false) {
            throw new RuntimeException('Resource Scheme must define scheme:// with resource requests');
        }

        return $this;
    }

    /**
     * Set Uri Scheme removeUriScheme
     *
     * @param   string $uri
     * @param   string $scheme
     *
     * @return  string
     * @since   1.0.0
     */
    protected function removeUriScheme($uri)
    {
        return substr($uri, strpos($uri, $this->requested_scheme) + strlen($this->requested_scheme) + 3, 9999);
    }
}


text:
package com.haulmont.cuba.security.entity;

import com.haulmont.chile.core.annotations.NamePattern;
import com.haulmont.cuba.core.entity.AbstractSearchFolder;
import com.haulmont.cuba.core.entity.StandardEntity;
import com.haulmont.cuba.core.entity.annotation.SystemLevel;

import javax.persistence.*;

/**
 * A filter component settings.
 */
@Entity(name = "sec$Filter")
@Table(name = "SEC_FILTER")
@NamePattern("%s|name")
@SystemLevel
public class FilterEntity extends StandardEntity {

    @Column(name = "COMPONENT")
    protected String componentId;

    @Column(name = "NAME", length = 255)
    protected String name;

    @Column(name = "CODE", length = 200)
    protected String code;

    @Column(name = "XML")
    @Lob
    protected String xml;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    protected User user;

    @Column(name = "GLOBAL_DEFAULT")
    protected Boolean globalDefault = false;

    @Transient
    protected Boolean isDefault = false;

    @Transient
    protected Boolean applyDefault = false;

    @Transient
    protected AbstractSearchFolder folder;

    @Transient
    protected Boolean isSet = false;

    public String getComponentId() {
        return componentId;
    }

    public void setComponentId(String componentId) {
        this.componentId = componentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getXml() {
        return xml;
    }

    public void setXml(String xml) {
        this.xml = xml;
    }

    public Boolean getIsDefault() {
        return isDefault;
    }

    public void setIsDefault(Boolean aDefault) {
        isDefault = aDefault;
    }

    public Boolean getApplyDefault(){
        return applyDefault;
    }

    public void setApplyDefault(Boolean applyDefault){
        this.applyDefault=applyDefault;
    }

    public AbstractSearchFolder getFolder() {
        return folder;
    }

    public void setFolder(AbstractSearchFolder folder) {
        this.folder = folder;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Boolean getIsSet(){
        return isSet;
    }

    public void setIsSet(Boolean isSet){
        this.isSet=isSet;
    }

    public Boolean getGlobalDefault() {
        return globalDefault;
    }

    public void setGlobalDefault(Boolean globalDefault) {
        this.globalDefault = globalDefault;
    }
}


text:
@interface ADMonthModeFlowCalendarViewLayout : ADFlowCalendarCollectionViewLayout

@end


text:
<?php

namespace Eloquent\Typhoon\CodeAnalysis\Issue\ParameterIssue;

use Eloquent\Typhoon\CodeAnalysis\Issue\AbstractParameterRelatedIssue;
use Eloquent\Typhoon\CodeAnalysis\Issue\IssueVisitorInterface;
use Eloquent\Typhoon\CodeAnalysis\Issue\ParameterIssueInterface;
use Eloquent\Typhoon\TypeCheck\TypeCheck;

class DocumentedParameterUndefined extends AbstractParameterRelatedIssue implements ParameterIssueInterface
{
    /**
     * @param IssueVisitorInterface $visitor
     *
     * @return mixed
     */
    public function accept(IssueVisitorInterface $visitor)
    {
        TypeCheck::get(__CLASS__)->accept(func_get_args());

        return $visitor->visitDocumentedParameterUndefined($this);
    }
}


text:
package de.tototec.sbuild.internal

import java.util.Locale
import scala.reflect.ClassTag
import scala.reflect.classTag
import java.util.MissingResourceException
import java.util.ResourceBundle
import java.text.MessageFormat
import java.util.jar.JarInputStream
import java.io.File
import java.io.FileInputStream
import scala.collection.mutable.WeakHashMap
import de.tototec.sbuild.Logger

trait I18nMarker {
  @inline def marktr(msgid: String): String = msgid
  @inline def marktrc(context: String, msgid: String): String = msgid
  @inline def notr(msgid: String, params: Any*): String = params match {
    case Seq() => msgid
    case _ => MessageFormat.format(msgid, params.map(_.asInstanceOf[AnyRef]): _*)
  }
}

trait I18n extends I18nMarker {
  def tr(msgid: String, params: Any*): String
  def trn(msgid: String, msgidPlural: String, n: Long, params: Any*): String
  def trc(context: String, msgid: String, params: Any*): String
  def trcn(context: String, msgid: String, msgidPlural: String, n: Long, params: Any*): String
  def locale: Locale
  def preparetr(msgid: String, params: Any*): PreparedI18n
}

trait PreparedI18n {
  def tr: String
  def notr: String
}

object I18n extends I18nMarker {

  private[this] val log = Logger[I18n.type]

  val CatalogBaseName = "I18n-Catalog"

  var missingTranslationDecorator: Option[String => String] = None

  private[this] val packageToCatalogBaseNameMap = WeakHashMap[Package, Option[String]]()

  def apply[T: ClassTag]: I18n = apply(Locale.getDefault)
  def apply[T: ClassTag](locale: Locale): I18n = {

    val runtimeClass = classTag[T].runtimeClass

    val manifestCatalogBaseName = packageToCatalogBaseNameMap.get(runtimeClass.getPackage()) match {
      case Some(baseNameOption) =>
        baseNameOption
      case None => try {
        log.debug("About to lookup the manifest for class: " + runtimeClass)
        val jarLoc = runtimeClass.getProtectionDomain().getCodeSource().getLocation()
        val jarFile = new File(jarLoc.toURI())
        log.debug("JAR location: " + jarFile)
        val stream = new JarInputStream(new FileInputStream(jarFile))
        val baseNameOption = try {
          Option(stream.getManifest().getMainAttributes().getValue(CatalogBaseName))
        } finally {
          stream.close
          None
        }
        log.debug("Determined manifest entry for message catalog basename: " + baseNameOption)
        synchronized { packageToCatalogBaseNameMap += runtimeClass.getPackage() -> baseNameOption }
        baseNameOption
      }
    }

    val catalogBaseName = manifestCatalogBaseName match {
      case Some(baseName) =>
        log.debug("Using message catalog basename from Manifest: " + baseName)
        baseName
      case None =>
        val baseName = runtimeClass.getPackage.getName + ".Messages"
        log.debug("Using message catalog basename derived from package name: " + baseName)
        baseName
    }

    new I18nImpl(catalogBaseName, runtimeClass.getClassLoader(), locale, None)
  }
}

class I18nImpl(catalogBaseName: String, classLoader: ClassLoader, override val locale: Locale, missingTranslationDecorator: Option[String => String]) extends I18n {

  private[this] lazy val log = Logger[I18nImpl]

  override def toString = getClass.getSimpleName + "(catalogBaseName=" + catalogBaseName + ",locale=" + locale + ")"

  private[this] def translate(msgid: String): String = try {
    ResourceBundle.getBundle(catalogBaseName, locale, classLoader).getString(msgid)
  } catch {
    case e: MissingResourceException =>
      log.trace("Could not find msgid \"" + msgid + "\" in: " + this, e)
      missingTranslationDecorator match {
        case None => I18n.missingTranslationDecorator match {
          case None => msgid
          case Some(miss) => miss(msgid)
        }
        case Some(miss) => miss(msgid)
      }
  }

  override def tr(msgid: String, params: Any*): String = notr(translate(msgid), params: _*)

  override def trn(msgid: String, msgidPlural: String, n: Long, params: Any*): String = tr(n match {
    case 1 => msgid
    case _ => msgidPlural
  }, params: _*)

  override def trc(context: String, msgid: String, params: Any*): String = tr(msgid, params: _*)

  override def trcn(context: String, msgid: String, msgidPlural: String, n: Long, params: Any*): String = trn(msgid, msgidPlural, n, params: _*)

  @inline override def preparetr(msgid: String, params: Any*): PreparedI18n = new PreparedI18n {
    override def tr: String = I18nImpl.this.tr(msgid, params: _*)
    override def notr: String = I18nImpl.this.notr(msgid, params: _*)
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>canvaspaint</title>

    <link href="//Microsoft.WinJS.2.0.Preview.RC/css/ui-dark.css" rel="stylesheet" />

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

            <button class="win-backbutton" aria-label="Back" disabled></button>

                Canvas Painting Example

            <canvas id="tutorial" width="640" height="480"></canvas>


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

namespace Octarine.Lys.Process
{
    /// <summary>
    /// Represents an operation with two additional parameters.
    /// </summary>
    public class TwoParametrizedOperation<T1, T2> : SimpleOperation
    {
        /// <summary>
        /// Initializes a new parametrized operation.
        /// </summary>
        /// <param name="type">The operation type.</param>
        /// <param name="sourcePosition">The position of the associated instruction in the source code.</param>
        /// <param name="parameter1">The first additional parameter.</param>
        /// <param name="parameter2">The second additional parameter.</param>
        public TwoParametrizedOperation(OperationType type, long sourcePosition, T1 parameter1, T2 parameter2)
            : base(type, sourcePosition)
        {
            if (parameter1 == null) throw new ArgumentNullException("parameter1");
            if (parameter2 == null) throw new ArgumentNullException("parameter2");

            this.Parameter1 = parameter1;
            this.Parameter2 = parameter2;
        }

        /// <summary>
        /// Gets the first additional operation parameter.
        /// </summary>
        public T1 Parameter1 { get; private set; }

        /// <summary>
        /// Gets the second additional operation parameter.
        /// </summary>
        public T2 Parameter2 { get; private set; }

        /// <summary>
        /// Gets meta data associated to this operation (for instance, parameters).
        /// </summary>
        /// <remarks>This method returns a collection consisting of this.Parameter1 and this.Parameter2.</remarks>
        public override IEnumerable<object> GetMetaData()
        {
            yield return this.Parameter1;
            yield return this.Parameter2;
        }

        public override string ToString()
        {
            return base.ToString() + " (" + this.Parameter1 + ", " + this.Parameter2 + ")";
        }

    }
}


text:
const MemberAttributionAssetsService = require('./service');
const memberAttributionAssets = new MemberAttributionAssetsService();

module.exports = memberAttributionAssets;


text:
package chapters.appenders;

import java.io.FileWriter;
import java.io.IOException;

import org.slf4j.Logger;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.FileAppender;
import ch.qos.logback.core.util.StatusPrinter;

public class IOPerformance extends Thread {
  static String MSG = "ABCDEGHIJKLMNOPQRSTUVWXYZabcdeghijklmnopqrstuvwxyz1234567890";
  static String LOG_FILE;
  public static String PARALLEL_FILE;

  static int NUM_THREADS = 1;
  static long l;
  long len;
  boolean immediateFlush;
  Logger logger;
  LoggerContext context;
  double throughput;

  public IOPerformance(boolean _immediateFlush, long _len) {
    this.len = _len;
    this.immediateFlush = _immediateFlush;
    context = new LoggerContext();
    logger = context.getLogger("logger-" + getName());

    // A FileAppender is created according to the buffering and
    // immediate flush setting of this IO instance.
    FileAppender<ILoggingEvent> fa = new FileAppender<ILoggingEvent>();
    fa.setName("FILE");
    PatternLayoutEncoder pa = new PatternLayoutEncoder();
    pa.setPattern("%r %5p %c [%t] - %m%n");
    pa.setContext(context);
    pa.start();
    fa.setEncoder(pa);

    fa.setFile(LOG_FILE);
    fa.setAppend(true);
    fa.setContext(context);
    fa.start();

    ((ch.qos.logback.classic.Logger) logger).addAppender(fa);

    StatusPrinter.print(context);
  }

  public static void main(String[] argv) throws Exception {
    if (argv.length != 3) {
      usage("Wrong number of arguments.");
    }

    l = Integer.parseInt(argv[0]);
    LOG_FILE = argv[1];
    PARALLEL_FILE = argv[2];

    // ----------------------------------------------------
    // first test with immediate flushing
    perfCase(true, l);

    // ----------------------------------------------------
    // Second test with no immediate flushing
    perfCase(false, l);

    // There is no fourth test as buffered IO and immediate flushing
    // do not make sense.
  }

  static void usage(String msg) {
    System.err.println(msg);
    System.err.println("Usage: java " + IOPerformance.class.getName()
        + " runLength logFile otherFile\n"
        + "   runLength (integer) the number of logs to generate perthread\n"
        + "   logFile path to a logFile\n"
        + "   otherFile path to a second file\n");
    System.exit(1);
  }

  static void perfCase(boolean immediateFlush, long len) throws Exception {
    IOPerformance[] threads = new IOPerformance[NUM_THREADS];
    OtherIO otherIOThread = new OtherIO();
    otherIOThread.start();

    // First create the threads
    for (int i = 0; i < NUM_THREADS; i++) {
      threads[i] = new IOPerformance(immediateFlush, len);
    }

    // then start them
    for (int i = 0; i < NUM_THREADS; i++) {
      threads[i].start();
    }

    // wait for them to processPriorToRemoval, compute the average throughput
    double sum = 0;

    for (int i = 0; i < NUM_THREADS; i++) {
      threads[i].join();
      sum += threads[i].throughput;
    }

    // setting the interrupted field will cause counterThread to processPriorToRemoval
    otherIOThread.interrupted = true;
    otherIOThread.join();

    System.out.println("On total throughput of " + (sum)
        + " logs per microsecond.");
    System.out.println("------------------------------------------------");
  }

  public void run() {

    long before = System.nanoTime();

    for (int i = 0; i < len; i++) {
      logger.debug(MSG);
    }

    throughput = (len * 1.0) / ((System.nanoTime() - before) / 1000);
    System.out.println(getName() + ", immediateFlush: " + immediateFlush
        + ", throughput: " + throughput + " logs per microsecond.");
  }
}

class OtherIO extends Thread {
  public boolean interrupted = false;
  public int counter = 0;

  public void run() {
    long before = System.nanoTime();
    try {
      FileWriter fw = new FileWriter(IOPerformance.PARALLEL_FILE, true);

      while (!interrupted) {
        counter++;
        fw.write("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        fw.flush();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    double tput = (counter * 1.0) / (System.nanoTime() - before);
    System.out.println("Counter thread " + getName()
        + " incremented counter by " + tput + " per nanosecond.");
  }
}


text:
"""
XML utilities.
"""
from __future__ import absolute_import

import collections
import os

from libsaas import http, port

# check for explicit request to use a specific library
_library = os.getenv("LIBSAAS_XML_LIBRARY")

if _library == "lxml":
    from lxml import etree
elif _library == "cElementTree":
    from xml.etree import cElementTree as etree
elif _library == "ElementTree":
    from xml.etree import ElementTree as etree
else:
    # try various implementations until one works
    try:
        from lxml import etree
    except ImportError:
        try:
            from xml.etree import cElementTree as etree
        except ImportError:
            from xml.etree import ElementTree as etree

del _library

class XMLParserException(Exception):
    """
    XML document not well formed
    """
    def __str__(self):
        return self.__doc__

def value_for_element(elem):
    # We want to have tag attributes
    elem_dict = dict(
        ('@{0}'.format(attrib), value)
        for attrib, value in elem.attrib.items() if attrib != 'type'
    )

    elem_text = elem.text and elem.text.strip()
    elem_type = elem.attrib.get('type', None)

    if elem_type == 'integer':
        value = int(elem_text)
    elif elem_type == 'float':
        value = float(elem_text)
    elif elem_type == 'boolean':
        value = elem_text.lower() == 'true'
    elif elem_type == 'array':
        tags = set([child.tag for child in elem])

        if not tags:
            return []

        if len(tags) > 1:
            raise XMLParserException()

        value = {
            tags.pop(): [value_for_element(child) for child in elem]
        }
    else:
        value = elem_text

    if not value:
        d = collections.defaultdict(list)
        for child in elem:
            d[child.tag].append(value_for_element(child))

        for key, value in d.items():
            if len(value) == 1:
                elem_dict[key] = value[0]
            else:
                elem_dict[key] = value

        return elem_dict or None

    if elem_dict:
        elem_dict.update({elem.tag: value})
        return elem_dict
    else:
        return value

def parse_xml(body, code, headers):
    """
    Return a dictionary.

    Transformation is done assuming:
    1.  If a tag indicates its value type, we'll try to cast it.
    2.  Siblings with the same tag name, become a list.
    3.  Attributes become a dict key starting with '@'.

    <duck>
        <name>Donald</name>
        <birth_date type="datetime">1934-06-04T00:00:00</birth_date>
        <first_film/>
        <last_film></last_film>
        <species href="http://en.wikipedia.org/wiki/Pekin_duck"/>
        <created_by href="http://en.wikipedia.org/wiki/Disney">
            <name>Walt Disney</name>
            <cryopreserved type="boolean">true</cryopreserved>
        </created_by>
        <family>
            <children type="array"></children>
            <uncles type="array">
                <uncle><name>Scrooge McDuck</name></uncle>
                <uncle><name>Ludwig Von Drake</name></uncle>
            </uncles>
            <nephew><name>Huey</name></nephew>
            <nephew><name>Dewey</name></nephew>
            <nephew><name>Louie</name></nephew>
        </family>
    </duck>

    {'duck': {'birth_date': '1934-06-04T00:00:00',
              'created_by': {'@href': 'http://en.wikipedia.org/wiki/Disney',
                             'cryopreserved': True,
                             'name': 'Walt Disney'},
              'family': {'nephew': [{'name': 'Huey'},
                                    {'name': 'Dewey'},
                                    {'name': 'Louie'}],
                         'children': [],
                         'uncles': {'uncle': [{'name': 'Scrooge McDuck'},
                                              {'name': 'Ludwig Von Drake'}]}},
              'first_film': None,
              'last_film': None,
              'name': 'Donald',
              'species': {'@href': 'http://en.wikipedia.org/wiki/Pekin_duck'}}
    }
    """
    if not 200 <= code < 300:
        raise http.HTTPError(body, code, headers)

    root_elem = etree.fromstring(body)
    return {
        root_elem.tag: value_for_element(root_elem)
    }

def element_for_value(obj, parent):
    for key, value in obj.items():
        if isinstance(value, dict):
            node = etree.SubElement(parent, key)
            element_for_value(value, node)
        elif isinstance(value, list):
            if not value:
                node = etree.SubElement(parent, key)

            for item in value:
                node = etree.SubElement(parent, key)
                element_for_value(item, node)
        else:
            if key.startswith('@'):
                parent.set(key.lstrip('@'), value)
            else:
                node = etree.SubElement(parent, key)
                node.text = (port.to_u(value)
                             if value is not None else port.to_u(''))

def dict_to_xml(obj):
    """
    Return a xml representation of the given dictionary:
    1.  keys of the dictionary become sublements.
    2.  if a value is a list, then key is a set of sublements.
    3.  keys starting with '@' became an attribute.

    {'duck': {'birth_date': '1934-06-04T00:00:00',
              'created_by': {'@href': 'http://en.wikipedia.org/wiki/Disney',
                             'cryopreserved': True,
                             'name': 'Walt Disney'},
              'family': {'nephew': [{'name': 'Huey'},
                                    {'name': 'Dewey'},
                                    {'name': 'Louie'}],
                         'children': [],
                         'uncles': {'uncle': [{'name': 'Scrooge McDuck'},
                                              {'name': 'Ludwig Von Drake'}]}},
              'first_film': None,
              'last_film': None,
              'name': 'Donald',
              'species': {'@href': 'http://en.wikipedia.org/wiki/Pekin_duck'}}
    }

    <?xml version="1.0" encoding="UTF-8"?>
    <duck>
        <name>Donald</name>
        <family>
            <children />
            <nephew><name>Huey</name></nephew>
            <nephew><name>Dewey</name></nephew>
            <nephew><name>Louie</name></nephew>
            <uncles>
                <uncle><name>Scrooge McDuck</name></uncle>
                <uncle><name>Ludwig Von Drake</name></uncle>
            </uncles>
        </family>
        <last_film />
        <first_film />
        <created_by href="http://en.wikipedia.org/wiki/Disney">
            <cryopreserved>True</cryopreserved>
            <name>Walt Disney</name>
        </created_by>
        <birth_date>1934-06-04T00:00:00</birth_date>
        <species href="http://en.wikipedia.org/wiki/Pekin_duck" />
    </duck>
    """
    if not obj:
        return

    # top level dictionary must contain a single entry
    # corresponding to the root element
    key, value = obj.popitem()

    root = etree.Element(key)
    element_for_value(value, root)
    return (b'<?xml version="1.0" encoding="UTF-8"?>' +
                etree.tostring(root, encoding='utf-8'))


text:
<?php

namespace frontend\models;

use Yii;

use yii\helpers\ArrayHelper;
use yii\db\Expression;

/**
 * This is the model class for table "activity".
 *
 * @property integer $id
 * @property integer $rec_id
 * @property string $title
 * @property string $details
 * @property string $venue
 * @property string $from_dt
 * @property string $to_dt
 * @property integer $criterion_id
 * @property string $discussion
 * @property integer $status_id
 * @property string $comment
 * @property string $created_dt
 * @property string $updated_dt
 *
 * @property Recognition $rec
 * @property Status $status
 * @property Criteria $criterion
 * @property Document[] $documents
 * @property Transaction[] $transactions
 */
class Activity extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'activity';
    }

   /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['rec_id', 'title', 'venue', 'from_dt', 'to_dt'], 'required', 'on' => ['request create','datetime input']],
            [['rec_id', 'title', 'venue', 'from_dt', 'to_dt'], 'required', 'on' => 'request input'],
            [['rec_id', 'status_id', 'discussion'], 'required', 'on' => 'report input'],
            [['rec_id', 'status_id'], 'required', 'on' => 'comment status'], // comment
            [['rec_id', 'status_id', 'criterion_id'], 'required', 'on' => 'evaluate'], // comment
            [['rec_id', 'criterion_id', 'status_id'], 'integer'],
            [['details', 'discussion', 'comment'], 'string'],
            [['created_dt', 'updated_dt'], 'safe'],
            [['title', 'venue'], 'string', 'max' => 40],
            [['rec_id'], 'exist', 'skipOnError' => true, 'targetClass' => Recognition::className(), 'targetAttribute' => ['rec_id' => 'id']],
            [['status_id'], 'exist', 'skipOnError' => true, 'targetClass' => Status::className(), 'targetAttribute' => ['status_id' => 'id']],
            [['criterion_id'], 'exist', 'skipOnError' => true, 'targetClass' => Criteria::className(), 'targetAttribute' => ['criterion_id' => 'id']],
            [['from_dt'], 'validateFromDt', 'on' => ['request create','request input', 'datetime input']],
            [['to_dt'], 'validateToDt', 'on' => ['request create','request input', 'datetime input']],
            [['from_dt','to_dt'], 'fromNow', 'on' => ['request create','request input', 'datetime input']],

        ];
    }

    /**
     * List of Scenarios that can be used in the model
     * @return mixed
     */
    public function scenarios()
    {
        $scenarios = parent::scenarios();

        $scenario['request create'] = ['rec_id','title', 'venue', 'from_dt', 'to_dt'];
        $scenario['request input'] = ['rec_id','status_id','title', 'venue', 'from_dt', 'to_dt'];
        $scenario['datetime input'] = ['from_dt', 'to_dt'];
        $scenario['report input'] = ['rec_id','status_id','discussion'];
        $scenario['comment status'] = ['rec_id','status_id'];  // comment
        $scenario['evaluate'] = ['rec_id','status_id','criterion_id'];

        return $scenarios;
    }

    /**
     * changes the scenario depending on the status
     * @return mixed
     */
    public function checkScenario() {
        if($this->isNewRecord) {
            $this->scenario = 'request create';
        } else {
            switch($this->status->status) {
                case 'request: none':
                case 'request: draft':
                case 'request: academe returned':
                case 'request: administration returned':
                case 'administrative: static':
                    $this->scenario = 'request input';
                        break;
                case 'report: none':
                case 'report: draft':
                case 'report: academe returned':
                case 'report: administration returned':
                    $this->scenario = 'report input';
                        break;
                case 'request: submitted to academe':
                case 'request: academe read':
                case 'request: academe approved':
                case 'request: submitted to administration':
                case 'request: administration read':
                case 'request: administration approved':
                case 'report: submitted to academe':
                case 'report: academe read':
                case 'report: academe approved':
                case 'report: submitted to administration':
                case 'report: administration read':
                // case 'report: administration approved':
                    $this->scenario = 'comment status';
                    break;
                case 'report: administration approved':
                case 'evaluation: none':
                case 'evaluation: updated':
                    $this->scenario = 'evaluate';
                    break;
                default:
                        break;
            }
        }
    }

    /**
     * The first datetime should be behind on the second datetime.
     * @return mixed
     */
    public function validateFromDt()
    {
        if(strtotime($this->from_dt) >= strtotime($this->to_dt)) {
            $this->addError('from_dt', 'DateTime from should be earlier than DateTime to');
        }
    }

    /**
     * The second datetime should be later than the first datetime.
     * @return mixed
     */
    public function validateToDt()
    {
        if(strtotime($this->from_dt) >= strtotime($this->to_dt)) {
            $this->addError('to_dt', 'DateTime To should be later than DateTime From');
        }
    }

    /**
     * The first datetime should be behind on the second datetime.
     * @return mixed
     */
    public function fromNow() {
        if($this->isAttributeChanged('from_dt') && strtotime($this->from_dt) < strtotime(date('Y-m-d H:i:s'))) {
            $this->addError('from_dt', 'From should not be behind from the current datetime');
        }
        if($this->isAttributeChanged('to_dt') && strtotime($this->to_dt) < strtotime(date('Y-m-d H:i:s'))) {
            $this->addError('to_dt', 'To should not be behind from the current datetime');
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'rec_id' => 'Rec ID',
            'title' => 'Title',
            'details' => 'Details',
            'venue' => 'Venue',
            'from_dt' => 'From',
            'to_dt' => 'To',
            'criterion_id' => 'Criterion',
            'discussion' => 'Discussion',
            'status_id' => 'Status',
            'comment' => 'Comment',
            'created_dt' => 'Created',
            'updated_dt' => 'Updated',
        ];
    }

    /**
     * @inheritdoc
     */
    public function beforeValidate() {
        if($this->isNewRecord)
            $this->rec_id = Yii::$app->session->get('rec_id');

        return parent::beforeValidate();
    }

    /**
     * @inheritdoc
     */
    public function beforeSave($insert) {
        if($this->isNewRecord) {
            $this->rec_id = intval(Yii::$app->session->get('rec_id'));
        }

        if($this->isNewRecord) {
            if(Yii::$app->session->get('role') === 'administration' ) {
                $this->status_id = 23;  //  administrative: static
            } else {
                $this->status_id = 2; //request: draft
            }
            $this->created_dt = new Expression('NOW()');
        } else {
            $this->updated_dt = new Expression('NOW()');
        }

        // Change status to draft if the status of activity request or report is 'none'
        if(strpos($this->status->status, 'none') !== false) {
            $this->status_id += 1;
        }

        return parent::beforeSave($insert);
    }

    /**
     * gets all of the acronyms of the organization related to the activities
     * @return mixed
     */
    public static function getOrgAcronyms() {
        $result = ArrayHelper::map(self::find()->innerJoinWith(['rec','rec.org'])->all(), 'rec.org.id', 'rec.org.acronym');
        if(!empty($result)) {
            return $result;
        } else {
            return [""=>""];
        }
    }

    /**
     * gets all of the titles related to the activities
     * @return mixed
     */
    public static function getTitles() {
        $result = (Yii::$app->session->get('role') === 'administration') ?
            ArrayHelper::map(self::find()->innerJoinWith(['rec','rec.org'])->all(), 'id', 'title') :
            ArrayHelper::map(self::find()->innerJoinWith(['status','rec','rec.org'])
                ->andWhere(['!=','status.status','osa_activity'])->all(), 'id', 'title');
        if(!empty($result)) {
            return $result;
        } else {
            return [[]];
        }
    }

    /**
     * gets all of the status related to the activities
     * @return mixed
     */
    public static function getStatusStatus() {
         $result = (Yii::$app->session->get('role') === 'administration') ?
        ArrayHelper::map(self::find()->innerJoinWith(['status','rec','rec.org'])
            ->all(), 'status.id', 'status.status') :
        ArrayHelper::map(self::find()->innerJoinWith(['status','rec','rec.org'])
            ->andWhere(['not like','status.status','administrative'])->all(), 'status.id', 'status.status');
        if(!empty($result)) {
            return $result;
        } else {
            return [];
        }
    }

    /**
     * gets all of the activities and attached to the yii2fullcalendar model
     * @return mixed
     */
    public static function getEvents() {
        $events = self::find()->all();
        $tasks = [];
        foreach($events as $event) {
            $event1 = new \yii2fullcalendar\models\Event();
            $event1->id = $event->id;
            $event1->title = $event->title;
            $event1->start = date('Y-m-d\TH:i:s\Z', strtotime($event->from_dt));
            $event1->end = date('Y-m-d\TH:i:s\Z', strtotime($event->to_dt));
            $tasks[] = $event1;
        }

        return $tasks;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCriterion()
    {
       return $this->hasOne(Criteria::className(), ['id' => 'criterion_id']);
    }

   /**
     * @return \yii\db\ActiveQuery
     */
    public function getRec()
    {
        return $this->hasOne(Recognition::className(), ['id' => 'rec_id'])->schoolYear();
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getStatus()
    {
        return $this->hasOne(Status::className(), ['id' => 'status_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getDocuments()
    {
        return $this->hasMany(Document::className(), ['activity_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRequestDocuments()
    {
        return $this->hasMany(Document::className(), ['activity_id' => 'id'])->andWhere(['purpose'=>'request']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getReportDocuments()
    {
        return $this->hasMany(Document::className(), ['activity_id' => 'id'])->andWhere(['purpose'=>'report']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTransactions()
       {
        return $this->hasMany(Transaction::className(), ['activity_id' => 'id']);
    }

    /**
     * @inheritdoc
     * @return ActivityQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new ActivityQuery(get_called_class());
    }
}

class ActivityQuery extends \yii\db\ActiveQuery
{
    /**
     * returns all of activities joined with the following relations
     * @return mixed
     */
    public function joinRequest() {
        return $this->innerJoinWith(['rec','rec.org','status'])->joinWith(['documents']);
    }

    /**
     * returns all of activities joined with the following relations
     * @return mixed
     */
    public function joinAll() {
        return $this->joinRequest()->innerJoinWith(['criterion']);
    }
}


text: FAIL COMPILATION


text:
package store

import (
	"testing"

	"github.com/yosssi/boltstore/shared"
)

func TestConfig_setDefault(t *testing.T) {
	config := Config{}
	config.setDefault()
	if config.SessionOptions.Path != shared.DefaultPath {
		t.Errorf("config.SessionOptions.Path should be %s (actual: %s)", shared.DefaultPath, config.SessionOptions.Path)
	}
	if config.SessionOptions.MaxAge != shared.DefaultMaxAge {
		t.Errorf("config.SessionOptions.MaxAge should be %s (actual: %s)", shared.DefaultMaxAge, config.SessionOptions.MaxAge)
	}
	if string(config.DBOptions.BucketName) != shared.DefaultBucketName {
		t.Errorf("config.SessionOptions.BucketName should be %+v (actual: %+v)", shared.DefaultBucketName, config.DBOptions.BucketName)
	}
}


text:
package org.dozer.eclipse.plugin.editorpage.pages.composites;

import org.dozer.eclipse.plugin.editorpage.DozerModelManager;
import org.dozer.eclipse.plugin.editorpage.utils.DozerUiUtils;
import org.dozer.eclipse.plugin.editorpage.utils.DozerUtils;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.viewers.AbstractListViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;

public class MappingClassComposite extends Composite {

	private IObservableValue className;
	private IObservableValue beanFactory;
	private IObservableValue beanFactoryId;
	private IObservableValue mapNull;
	private IObservableValue mapEmpty;
	private ObservableSingleSelectionObject mapSetMethod;
	private ObservableSingleSelectionObject mapGetMethod;
	private ObservableSingleSelectionObject createMethod;

	private AbstractListViewer mapGetComboViewer;
	private AbstractListViewer mapSetComboViewer;
	private AbstractListViewer createComboViewer;

	private Section optionSection;

	public MappingClassComposite(Composite parent, FormToolkit toolkit, final DozerModelManager modelManager) {
		super(parent, SWT.NULL);

		//FIXME otherwise its transparent!?!?
		this.setBackground(new Color(Display.getCurrent(), 255,255,255));

		TableWrapLayout layout = new TableWrapLayout();
		layout.numColumns = 2;
		this.setLayout(layout);

		className = DozerUiUtils.createLabelClassBrowse(
				this,
				"ClassMappingSection.classname",
				null,
				true);

		optionSection = toolkit.createSection(this, ExpandableComposite.TWISTIE | ExpandableComposite.SHORT_TITLE_BAR);
		optionSection.setText("Class Options");

		Composite sectionComposite = toolkit.createComposite(optionSection);
		optionSection.setClient(sectionComposite);

		TableWrapData td = new TableWrapData(TableWrapData.FILL);
		td.colspan = 2;
		optionSection.setLayoutData(td);

		TableWrapLayout layout2 = new TableWrapLayout();
		layout2.numColumns = 2;
		sectionComposite.setLayout(layout2);

		beanFactory = DozerUiUtils.createLabelClassBrowse(
				sectionComposite,
				"ConfigSection.beanfactory",
				DozerUtils.getBeanFactoryInterfaceName(modelManager.getModel()),
				false);

		beanFactoryId = DozerUiUtils.createLabelText(sectionComposite, "ClassMappingSection.beanFactoryId");

		DozerUiUtils.createLabel(sectionComposite, "MappingSection.mapnull");
		Composite comboComposite = toolkit.createComposite(sectionComposite);
		TableWrapLayout comboLayout = new TableWrapLayout();
		comboLayout.numColumns = 3;
		comboLayout.bottomMargin = 0;
		comboLayout.horizontalSpacing = 5;
		comboLayout.leftMargin = 0;
		comboLayout.rightMargin = 0;
		comboLayout.topMargin = 0;
		comboComposite.setLayout(comboLayout);

		td = new TableWrapData();
		comboComposite.setLayoutData(td);

		mapNull = DozerUiUtils.createCombo(
				comboComposite,
				"MappingSection.mapnull", new String[] { "", "true", "false" }); //$NON-NLS-1$

		mapEmpty = DozerUiUtils.createLabelCombo(
				comboComposite,
				"MappingSection.mapempty", new String[] { "", "true", "false" }); //$NON-NLS-1$

		mapGetComboViewer = DozerUiUtils.createLabelMethodCombobox(
				sectionComposite,
				"MappingSection.mapGetMethod"); //$NON-NLS-1$
		mapGetMethod = new ObservableSingleSelectionObject(mapGetComboViewer);

		mapSetComboViewer = DozerUiUtils.createLabelMethodCombobox(
				sectionComposite,
				"MappingSection.mapSetMethod"); //$NON-NLS-1$
		mapSetMethod = new ObservableSingleSelectionObject(mapSetComboViewer);

		createComboViewer = DozerUiUtils.createLabelMethodCombobox(
				sectionComposite,
				"MappingSection.createMethod"); //$NON-NLS-1$
		createMethod =  new ObservableSingleSelectionObject(createComboViewer);
	}

	public IObservableValue getClassName() {
		return className;
	}

	public IObservableValue getBeanFactory() {
		return beanFactory;
	}

	public IObservableValue getBeanFactoryId() {
		return beanFactoryId;
	}

	public IObservableValue getMapNull() {
		return mapNull;
	}

	public IObservableValue getMapEmpty() {
		return mapEmpty;
	}

	public ObservableSingleSelectionObject getMapSetMethod() {
		return mapSetMethod;
	}

	public ObservableSingleSelectionObject getMapGetMethod() {
		return mapGetMethod;
	}

	public ObservableSingleSelectionObject getCreateMethod() {
		return createMethod;
	}

	public Section getOptionSection() {
		return optionSection;
	}

	public AbstractListViewer getMapGetComboViewer() {
		return mapGetComboViewer;
	}

	public AbstractListViewer getMapSetComboViewer() {
		return mapSetComboViewer;
	}

	public AbstractListViewer getCreateComboViewer() {
		return createComboViewer;
	}

}


text:
package com.intellij.codeInspection.bulkOperation;

import com.intellij.psi.CommonClassNames;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.stream.Stream;

public class JdkBulkMethodInfoProvider implements BulkMethodInfoProvider {
  private static final BulkMethodInfo[] INFOS = {
    new BulkMethodInfo(CommonClassNames.JAVA_UTIL_COLLECTION, "add", "addAll")
  };

  @NotNull
  @Override
  public Stream<BulkMethodInfo> consumers() {
    return Arrays.stream(INFOS);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Web;
using System.Web.Mvc;

namespace ASP.NETAppWithNorthwind.Controllers
{
    public class CustomersController : Controller
    {
        NORTHWNDEntities dbContext = new NORTHWNDEntities();

        public ActionResult All()
        {
            var customers = dbContext.Customers.ToList();

            return View(customers);
        }

        public ActionResult CustomerDetails(string id)
        {
            var customer = dbContext.Customers
                .FirstOrDefault(c => c.CustomerID == id);

            return View(customer);
        }
    }
}


text:
package com.twitter.finagle.kestrel

import scala.collection.JavaConversions._
import _root_.java.{util => ju}

import com.twitter.concurrent.{Offer, Broker}

object AllHandlesDiedException extends Exception

/**
 * Read from multiple clients in round-robin fashion, "grabby hands"
 * style.  The load balancing is simple, and falls out naturally from
 * the user of the {{Offer}} mechanism: When there are multiple
 * available messages, round-robin across them.  Otherwise, wait for
 * the first message to arrive.
 */
object MultiReader {
  def apply(clients: Seq[Client], queueName: String): ReadHandle =
    apply(clients map { _.readReliably(queueName) })

  /**
   * A java friendly interface: we use scala's implicit conversions to
   * feed in a {{java.util.Iterator<ReadHandle>}}
   */
  def apply(handles: ju.Iterator[ReadHandle]): ReadHandle =
    apply(handles.toSeq)

  def apply(handles: Seq[ReadHandle]): ReadHandle = {
    val error = new Broker[Throwable]
    val messages = new Broker[ReadMessage]
    val close = new Broker[Unit]

    var underlying = Set() ++ handles
    val errors = underlying map { h => h.error map { _ => h } } toSeq

    val closeOf = close.recv { _ =>
      underlying foreach { _.close() }
      error ! ReadClosedException
    }

    def loop() {
      // compute the active queues
      if (underlying.isEmpty) {
        error ! AllHandlesDiedException
        return
      }
      val queues = underlying map { _.messages } toSeq

      // we sequence here to ensure that close gets
      // priority over reads
      val of = closeOf orElse {
        Offer.choose(
          closeOf,
          Offer.choose(queues:_*) { m =>
            messages ! m
            loop()
          },
          Offer.choose(errors:_*) { h =>
            underlying -= h
            loop()
          }
        )
      }

      of()
    }

    loop()

    ReadHandle(messages.recv, error.recv, close.send(()))
  }
}


text:
<!DOCTYPE html>

		<meta charset="UTF-8"/>
		<meta name="generator" content="org.rostlab.relna"/>
		<title>72cec4cdad504556b16afdf08353038b:97458236</title>

Negative regulation by HLA-DO of MHC class II -restricted antigen processing.

Abstract

HLA-DM is a major histocompatibility complex (MHC) class II-like molecule that facilitates antigen processing by catalyzing the exchange of invariant chain-derived peptides (CLIP) from class II molecules for antigenic peptides. HLA-DO is a second class II-like molecule that physically associates with HLA-DM in B cells. HLA-DO was shown to block HLA-DM function. Purified HLA-DM-DO complexes could not promote peptide exchange in vitro. Expression of HLA-DO in a class II+ and DM+, DO- human T cell line caused the accumulation of class II-CLIP complexes, indicating that HLA-DO blocked DM function in vivo and suggesting that HLA-DO is an important modulator of class II-restricted antigen processing.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Erythea 1: 197 (1893)

#### Original name
Rosellinia pulcherrima Ellis & Everh.

### Remarks
null


text:
using Microsoft.Xaml.Interactivity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace UwpApp1
{
    //public abstract class Behavior<T> : DependencyObject, IBehavior where T : DependencyObject
    public abstract class Behavior<T> : DependencyObject , IBehavior where T : DependencyObject
    {
        public T AssociatedObject { get; private set; }

        DependencyObject IBehavior.AssociatedObject
        {
            get { return this.AssociatedObject; }
        }

        protected abstract void OnAttached();
        protected abstract void OnDetached();

        public void Attach(DependencyObject associatedObject)
        {
            if (associatedObject != null && !typeof(T).GetTypeInfo().IsAssignableFrom(associatedObject.GetType().GetTypeInfo()))
                throw new Exception(string.Format("associatedObject is not assignable to type:", typeof(T)));

            this.AssociatedObject = associatedObject as T;
            this.OnAttached();
        }

        public void Detach()
        {
            this.OnDetached();
            this.AssociatedObject = null;
        }
    }

}


text:
No `main` function was found in a binary crate.

To fix this error, add a `main` function:

```
fn main() {
    // Your program will start here.
    println!("Hello world!");
}
```

If you don't know the basics of Rust, you can look at the
[Rust Book][rust-book] to get started.

[rust-book]: https://doc.rust-lang.org/book/


text:
//
//  VROViewRecorder.h
//  ViroKit
//
//  Created by Raj Advani on 11/28/17.
//  Copyright © 2017 Viro Media. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining
//  a copy of this software and associated documentation files (the
//  "Software"), to deal in the Software without restriction, including
//  without limitation the rights to use, copy, modify, merge, publish,
//  distribute, sublicense, and/or sell copies of the Software, and to
//  permit persons to whom the Software is furnished to do so, subject to
//  the following conditions:
//
//  The above copyright notice and this permission notice shall be included
//  in all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#import <Foundation/Foundation.h>
#import <GLKit/GLKit.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import <memory>
#import "VRORenderToTextureDelegate.h"

class VRODriver;
class VRORenderer;
class VROTexture;
class VRORenderTarget;
@class VROViewRecorder;

typedef void (^VROViewRecordingErrorBlock)(NSInteger errorCode);
typedef void (^VROViewWriteMediaFinishBlock)(BOOL success, NSURL *filePath, NSURL *gifPath, NSInteger errorCode);

static NSInteger const kVROViewErrorNone = -1;
static NSInteger const kVROViewErrorUnknown = 0;
static NSInteger const kVROViewErrorNoPermissions = 1;
static NSInteger const kVROViewErrorInitialization = 2;
static NSInteger const kVROViewErrorWriteToFile = 3;
static NSInteger const kVROViewErrorAlreadyRunning = 4;
static NSInteger const kVROViewErrorAlreadyStopped = 5;
static NSInteger const kVROViewErrorWriteGifToFile = 6;
static NSInteger const kVROViewErrorAudioFailure = 7;

static NSString *const kVROViewTempMediaDirectory = @"viro_media";
static NSString *const kVROViewAudioSuffix = @".m4a";
static NSString *const kVROViewImageSuffix = @".png";
static NSString *const kVROViewTempVideoSuffix = @"-temp.mp4";
static NSString *const kVROViewVideoSuffix = @".mp4";
static NSString *const kVROViewGifSuffix = @".gif";

class VROViewRecorderRTTDelegate : public VRORenderToTextureDelegate {
public:
    VROViewRecorderRTTDelegate(VROViewRecorder *recorder,
                               std::shared_ptr<VROTexture> texture,
                               std::shared_ptr<VRORenderer> renderer,
                               std::shared_ptr<VRODriver> driver);
    virtual ~VROViewRecorderRTTDelegate() {}

    void didRenderFrame(std::shared_ptr<VRORenderTarget> target,
                        std::shared_ptr<VRODriver> driver);

private:
    __weak VROViewRecorder *_recorder;
    std::shared_ptr<VROTexture> _texture;
    std::weak_ptr<VRORenderer> _renderer;
    std::shared_ptr<VRORenderTarget> _renderToTextureTarget;
};

/*
 Video recording and screenshot implementation for a GLKView.
 */
@interface VROViewRecorder : NSObject

- (id)initWithView:(GLKView *)view
          renderer:(std::shared_ptr<VRORenderer>)renderer
            driver:(std::shared_ptr<VRODriver>)driver;
- (void)deleteGL;

- (void)startVideoRecording:(NSString *)fileName
           saveToCameraRoll:(BOOL)saveToCamera
                 errorBlock:(VROViewRecordingErrorBlock)errorBlock;

- (void)startVideoRecording:(NSString *)fileName
              withWatermark:(UIImage *)watermarkImage
                  withFrame:(CGRect)watermarkFrame
           saveToCameraRoll:(BOOL)saveToCamera
                 errorBlock:(VROViewRecordingErrorBlock)errorBlock;

- (void)startVideoRecording:(NSString *)fileName
                    gifFile:(NSString *)gifFile
              withWatermark:(UIImage *)watermarkImage
                  withFrame:(CGRect)watermarkFrame
           saveToCameraRoll:(BOOL)saveToCamera
                 errorBlock:(VROViewRecordingErrorBlock)errorBlock;

- (void)stopVideoRecordingWithHandler:(VROViewWriteMediaFinishBlock)completionHandler;
- (void)stopVideoRecordingWithHandler:(VROViewWriteMediaFinishBlock)completionHandler mergeAudioTrack:(NSURL *)audioPath;

- (void)takeScreenshot:(NSString *)fileName
      saveToCameraRoll:(BOOL)saveToCamera
 withCompletionHandler:(VROViewWriteMediaFinishBlock)completionHandler;
- (void)lockPixelBuffer;
- (void)setUseMicrophone:(BOOL)useMicrophone;

/*
 Manually overrides video recording parameters with a different width and
 height, instead of using the dimensions of the underlying GLView.
 */
- (void)setRecorderWidth:(int)width
                  height:(int)height;
@end


text:
<?php

namespace app\controllers;

use Yii;
use app\models\Category;
use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * CategoryController implements the CRUD actions for Category model.
 */
class CategoryController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'view', 'create', 'update', 'delete'],
                        'allow' => true,
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['category'],
                ],
            ],
        ];
    }

    /**
     * Список категорий.
     * @return string
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => Category::find(),
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Просмотр категории.
     * @param string $id идентификатор просматриваемой категории
     * @return string
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Создание категории.
     * @return string|Response
     */
    public function actionCreate()
    {
        $model = new Category();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Редактирование категории.
     * @param string $id идентификатор редактируемой категории
     * @return string|Response
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Удаление категории
     * @param string $id идентификатор удаляемой категории
     * @return Response
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Category model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Category the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Category::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
from PySide.QtCore import *
from PySide.QtGui import *
import os, re
from . pythonSyntax import design
import managers
style = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'style', 'completer.qss')
if not os.path.exists(style):
    style=None

class completeMenuClass(QListWidget):
    def __init__(self, parent=None, editor=None):
        super(completeMenuClass, self).__init__(parent)
        self.setAlternatingRowColors(1)
        self.lineHeight = 18
        self.e = editor
        self.setAttribute(Qt.WA_ShowWithoutActivating)
        if managers._s == 'w':
            self.setWindowFlags(Qt.FramelessWindowHint |  Qt.Window)
        else:
            self.setWindowFlags(Qt.FramelessWindowHint |  Qt.Window | Qt.WindowStaysOnTopHint)
        @self.itemDoubleClicked.connect
        def insertSelected(item):
            if item:
                comp = item.data(32)
                self.sendText(comp)
                self.hideMe()

    def updateStyle(self, colors=None):
        text = design.editorStyle()
        self.setStyleSheet(text)

    def updateCompleteList(self, lines=None, extra=None):
        self.clear()
        if lines or extra:
            self.showMe()
            if lines:
                for i in [x for x in lines if not x.name == 'mro']:
                    item = QListWidgetItem(i.name)
                    item.setData(32, i)
                    self.addItem(item)
            if extra:

                font = self.font()
                font.setItalic(1)
                font.setPointSize(font.pointSize()*0.8)
                for e in extra:
                    item = QListWidgetItem(e.name)
                    item.setData(32, e)
                    item.setFont(font)
                    self.addItem(item)

            font = QFont("monospace", self.lineHeight, False)
            fm = QFontMetrics (font)
            width = fm.width(' ') *  max([len(x.name) for x in lines or extra]) + 40

            self.resize(max(250,width), 250)
            self.setCurrentRow(0)
        else:
            self.hideMe()

    def applyCurrentComplete(self):
        i = self.selectedItems()
        if i:
            comp = i[0].data(32)
            self.sendText(comp)
        self.hideMe()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.close()
        # elif event.text():
        #     self.editor().setFocus()
        elif event.key() == Qt.Key_Return or event.key() == Qt.Key_Enter:
            self.editor().setFocus()
            self.applyCurrentComplete()
            return event
        elif event.key() == Qt.Key_Up:
            sel = self.selectedItems()
            if sel:
                i = self.row(sel[0])
                if i == 0:
                    QListWidget.keyPressEvent(self, event)
                    self.setCurrentRow(self.count()-1)
                    return
        elif event.key() == Qt.Key_Down:
            sel = self.selectedItems()
            if sel:
                i = self.row(sel[0])
                if i+1 == self.count():
                    QListWidget.keyPressEvent(self, event)
                    self.setCurrentRow(0)
                    return
        elif event.key() == Qt.Key_Backspace:
            self.editor().setFocus()
            self.editor().activateWindow()
        elif event.text():
            self.editor().keyPressEvent(event)
            return

        QListWidget.keyPressEvent(self, event)

    def sendText(self, comp):
        self.editor().insertText(comp)

    def editor(self):
        return self.e

    def activateCompleter(self, key=False):
        self.activateWindow()
        if not key==Qt.Key_Up:
            self.setCurrentRow(min(1, self.count()-1))
        else:
            self.setCurrentRow(self.count()-1)

    def showMe(self):

        self.show()

    def hideMe(self):
        self.hide()


text:
/**
 * Port From:   JDK 1.4b1 : java.text.Format.IntlTestDecimalFormatSymbols
 * Source File: java/text/format/IntlTestDecimalFormatSymbols.java
 **/

/*
    @test 1.4 98/03/06
    @summary test International Decimal Format Symbols
*/

package com.ibm.icu.dev.test.format;

import java.util.Locale;

import com.ibm.icu.text.DecimalFormatSymbols;
import com.ibm.icu.util.Currency;

public class IntlTestDecimalFormatSymbols extends com.ibm.icu.dev.test.TestFmwk
{
    public static void main(String[] args) throws Exception {
        new IntlTestDecimalFormatSymbols().run(args);
    }

    // Test the API of DecimalFormatSymbols; primarily a simple get/set set.
    public void TestSymbols()
    {
        DecimalFormatSymbols fr = new DecimalFormatSymbols(Locale.FRENCH);

        DecimalFormatSymbols en = new DecimalFormatSymbols(Locale.ENGLISH);

        if(en.equals(fr)) {
            errln("ERROR: English DecimalFormatSymbols equal to French");
        }

        // just do some VERY basic tests to make sure that get/set work

        char zero = en.getZeroDigit();
        fr.setZeroDigit(zero);
        if(fr.getZeroDigit() != en.getZeroDigit()) {
            errln("ERROR: get/set ZeroDigit failed");
        }

        char sigDigit = en.getSignificantDigit();
        fr.setSignificantDigit(sigDigit);
        if(fr.getSignificantDigit() != en.getSignificantDigit()) {
            errln("ERROR: get/set SignificantDigit failed");
        }

        Currency currency = Currency.getInstance("USD");
        fr.setCurrency(currency);
        if (!fr.getCurrency().equals(currency)){
            errln("ERROR: get/set Currency failed");
        }

        char group = en.getGroupingSeparator();
        fr.setGroupingSeparator(group);
        if(fr.getGroupingSeparator() != en.getGroupingSeparator()) {
            errln("ERROR: get/set GroupingSeparator failed");
        }

        char decimal = en.getDecimalSeparator();
        fr.setDecimalSeparator(decimal);
        if(fr.getDecimalSeparator() != en.getDecimalSeparator()) {
            errln("ERROR: get/set DecimalSeparator failed");
        }

        char monetaryGroup = en.getMonetaryGroupingSeparator();
        fr.setMonetaryGroupingSeparator(monetaryGroup);
        if(fr.getMonetaryGroupingSeparator() != en.getMonetaryGroupingSeparator()) {
            errln("ERROR: get/set MonetaryGroupingSeparator failed");
        }

        char monetaryDecimal = en.getMonetaryDecimalSeparator();
        fr.setMonetaryDecimalSeparator(monetaryDecimal);
        if(fr.getMonetaryDecimalSeparator() != en.getMonetaryDecimalSeparator()) {
            errln("ERROR: get/set MonetaryDecimalSeparator failed");
        }

        char perMill = en.getPerMill();
        fr.setPerMill(perMill);
        if(fr.getPerMill() != en.getPerMill()) {
            errln("ERROR: get/set PerMill failed");
        }

        char percent = en.getPercent();
        fr.setPercent(percent);
        if(fr.getPercent() != en.getPercent()) {
            errln("ERROR: get/set Percent failed");
        }

        char digit = en.getDigit();
        fr.setDigit(digit);
        if(fr.getPercent() != en.getPercent()) {
            errln("ERROR: get/set Percent failed");
        }

        char patternSeparator = en.getPatternSeparator();
        fr.setPatternSeparator(patternSeparator);
        if(fr.getPatternSeparator() != en.getPatternSeparator()) {
            errln("ERROR: get/set PatternSeparator failed");
        }

        String infinity = en.getInfinity();
        fr.setInfinity(infinity);
        String infinity2 = fr.getInfinity();
        if(! infinity.equals(infinity2)) {
            errln("ERROR: get/set Infinity failed");
        }

        String nan = en.getNaN();
        fr.setNaN(nan);
        String nan2 = fr.getNaN();
        if(! nan.equals(nan2)) {
            errln("ERROR: get/set NaN failed");
        }

        char minusSign = en.getMinusSign();
        fr.setMinusSign(minusSign);
        if(fr.getMinusSign() != en.getMinusSign()) {
            errln("ERROR: get/set MinusSign failed");
        }

        char plusSign = en.getPlusSign();
        fr.setPlusSign(plusSign);
        if(fr.getPlusSign() != en.getPlusSign()) {
            errln("ERROR: get/set PlusSign failed");
        }

        char padEscape = en.getPadEscape();
        fr.setPadEscape(padEscape);
        if(fr.getPadEscape() != en.getPadEscape()) {
            errln("ERROR: get/set PadEscape failed");
        }

        String exponential = en.getExponentSeparator();
        fr.setExponentSeparator(exponential);
        if(fr.getExponentSeparator() != en.getExponentSeparator()) {
            errln("ERROR: get/set Exponential failed");
        }

        // Test CurrencySpacing.
        // In CLDR 1.7, only root.txt has CurrencySpacing data. This data might
        // be different between en and fr in the future.
        for (int i = DecimalFormatSymbols.CURRENCY_SPC_CURRENCY_MATCH; i <= DecimalFormatSymbols.CURRENCY_SPC_INSERT; i++) {
            if (en.getPatternForCurrencySpacing(i, true) !=
                fr.getPatternForCurrencySpacing(i, true)) {
                errln("ERROR: get currency spacing item:"+ i+" before the currency");
                if (en.getPatternForCurrencySpacing(i, false) !=
                    fr.getPatternForCurrencySpacing(i, false)) {
                    errln("ERROR: get currency spacing item:" + i + " after currency");
                }
            }
        }

        String dash = "-";
        en.setPatternForCurrencySpacing(DecimalFormatSymbols.CURRENCY_SPC_INSERT, true, dash);
        if (dash != en.getPatternForCurrencySpacing(DecimalFormatSymbols.CURRENCY_SPC_INSERT, true)) {
            errln("ERROR: set currency spacing pattern for before currency.");
        }

        //DecimalFormatSymbols foo = new DecimalFormatSymbols(); //The variable is never used

        en = (DecimalFormatSymbols) fr.clone();

        if(! en.equals(fr)) {
            errln("ERROR: Clone failed");
        }
    }

    public void testCoverage() {
        DecimalFormatSymbols df = new DecimalFormatSymbols();
        DecimalFormatSymbols df2 = (DecimalFormatSymbols)df.clone();
        if (!df.equals(df2) || df.hashCode() != df2.hashCode()) {
            errln("decimal format symbols clone, equals, or hashCode failed");
        }
    }
}


text:
class ChangeFloatToDoubleInDeviceLocations < ActiveRecord::Migration
  def self.up
    remove_column :device_locations, :latitude
    add_column :device_locations, :latitude, :double
    remove_column :device_locations, :longitude
    add_column :device_locations, :longitude, :double
  end

  def self.down
  end
end