text:
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <chrono>
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#ifdef __linux__
#include <GL/glx.h>
#endif

#include "cl_video.hpp"

cl_video::cl_video(bool gpu,
				   unsigned int device) :
device_used_(device),
err_(0),
mdx_(0),
mdy_(0)
{
	//setup devices_ and context_
	std::vector<cl::Platform> platforms;
	err_ = cl::Platform::get(&platforms);
	err_ = platforms[0].getDevices((gpu) ?
								   CL_DEVICE_TYPE_GPU :
								   CL_DEVICE_TYPE_CPU,
								   &devices_);
	//	int t = devices_.front().getInfo<CL_DEVICE_TYPE>();
	int i = 0;
	for (auto device : devices_) {
		std::cout
		<< "device name [" << i << "] : "
		<< device.getInfo<CL_DEVICE_NAME>()
		<< std::endl;
		i++;
	}
	// take the last device (work around Intel GPU)
	device_used_ = device;
	std::cout << "device used     : " << device_used_ << std::endl;
	try {
		throw cl::Error(0, "cheat pass");
#if defined (__APPLE__) || defined(MACOSX)
		CGLContextObj kCGLContext = CGLGetCurrentContext();
		CGLShareGroupObj kCGLShareGroup = CGLGetShareGroup(kCGLContext);
		cl_context_properties props[] =
		{
			CL_CONTEXT_PROPERTY_USE_CGL_SHAREGROUP_APPLE,
			(cl_context_properties)kCGLShareGroup,
			0
		};
		context_ = cl::Context(CL_DEVICE_TYPE_GPU, props);
#else
#if defined WIN32 // Win32
		cl_context_properties props[] =
		{
			CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(),
			CL_WGL_HDC_KHR, (cl_context_properties)wglGetCurrentDC(),
			CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(),
			0
		};
		context_ = cl::Context(CL_DEVICE_TYPE_GPU, props);
#else
		//		throw cl::Error(0, "cheat pass");
		cl_context_properties props[] =
		{
			CL_GL_CONTEXT_KHR, (cl_context_properties)glXGetCurrentContext(),
			CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(),
			CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[0])(),
			0
		};
		context_ = cl::Context(CL_DEVICE_TYPE_GPU, props);
#endif
#endif
	} catch (cl::Error er) {
		std::cerr
		<< "Warning         : could not attach GL and CL together!"
		<< std::endl;
		cl_context_properties properties[] = {
			CL_CONTEXT_PLATFORM,
			(cl_context_properties)(platforms[0])(),
			0
		};
		context_ = cl::Context((gpu) ? CL_DEVICE_TYPE_GPU : CL_DEVICE_TYPE_CPU,
							   properties);
		devices_ = context_.getInfo<CL_CONTEXT_DEVICES>();
	}
	queue_ = cl::CommandQueue(context_, devices_[device_used_], 0, &err_);
}

cl_video::~cl_video() {}

void cl_video::init(const std::string& cl_file) {
	std::ifstream ifs(cl_file);
	if (!ifs.is_open())
		throw std::runtime_error("could not open file : " + cl_file);
	std::string kernel__source((std::istreambuf_iterator<char>(ifs)),
							   std::istreambuf_iterator<char>());
	cl::Program::Sources source(1,
								std::make_pair(kernel__source.c_str(),
											   kernel__source.size()));
	program_ = cl::Program(context_, source);
	try {
		err_ = program_.build(devices_);
	} catch (cl::Error er) {
		std::cerr
		<< "build status    : "
		<< program_.getBuildInfo<CL_PROGRAM_BUILD_STATUS>(devices_[0])
		<< std::endl;
		std::cerr
		<< "build options   : "
		<< program_.getBuildInfo<CL_PROGRAM_BUILD_OPTIONS>(devices_[0])
		<< std::endl;
		std::cerr
		<< "build log       : "  << std::endl
		<< program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices_[0])
		<< std::endl;
		throw er;
	}
}

void cl_video::setup(const std::pair<unsigned int, unsigned int>& s,
					 unsigned int nb_col)
{
	mdx_ = s.first;
	mdy_ = s.second;
	nb_col_ = nb_col;
}

void cl_video::prepare(const std::vector<char>& input) {
	total_size_ = mdx_ * mdy_ * nb_col_;
	origin_[0] = 0;
	origin_[1] = 0;
	origin_[2] = 0;
	region_[0] = mdx_;
	region_[1] = mdy_;
	region_[2] = 1;
	if (input.size() != (total_size_))
		throw std::runtime_error("input buffer size != image size!");
	kernel_ = cl::Kernel(program_, "video_image", &err_);
	// initialize our CPU memory arrays, send them to the device and set
	// the kernel_ arguements
	cl::ImageFormat format;
	if (nb_col_ == 1)
		format = cl::ImageFormat(CL_INTENSITY, CL_UNORM_INT8);
	else
		format = cl::ImageFormat(CL_BGRA, CL_UNORM_INT8);
	cl_image_input_ = cl::Image2D(context_,
								  CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
								  format,
								  mdx_,
								  mdy_,
								  0,
								  (void*)&input[0],
								  &err_);
	cl_image_output_ = cl::Image2D(context_,
								   CL_MEM_WRITE_ONLY,
								   format,
								   mdx_,
								   mdy_,
								   0,
								   NULL,
								   &err_);
	queue_.finish();
	//set the arguements of our kernel_
	err_ = kernel_.setArg(0, cl_image_input_);
	err_ = kernel_.setArg(1, cl_image_output_);
	//Wait for the command queue_ to finish these commands before proceeding
	queue_.finish();
}

std::chrono::duration<double> cl_video::run(std::vector<char>& output) {
	if (output.size() != total_size_)
		output.resize(total_size_);
	auto before = std::chrono::system_clock::now();
	// make the computation
	err_ = queue_.enqueueNDRangeKernel(kernel_,
									   cl::NullRange,
									   cl::NDRange(mdx_, mdy_),
									   cl::NullRange,
									   NULL,
									   &event_);
	queue_.finish();
	auto after = std::chrono::system_clock::now();
	err_ = queue_.enqueueReadImage(cl_image_output_,
								   CL_TRUE,
								   origin_,
								   region_,
								   0,
								   0,
								   (void*)&output[0]);
	queue_.finish();
	return (after - before);
}


text:
<!DOCTYPE html>

	<title>Holiday » Wifi</title>

			Apps

Wifi Configuration

Choose Network

Join network?

Are you sure you want to join

If successful, Holiday will no longer be visible on this network.

				<form id="passform">

Password Required

					Password:
					<input type="password" name="pw" id="pw" placeholder="Password">
				</form>
				Cancel
				Join

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using System.Text;
using Jil;
using Xunit;

namespace JilTests
{
    public class DeepObjectGraphTests
    {
        [Fact]
        public void DeepObjectGraphShouldNotBeEmpty()
        {
            // given
            var model = new UserCredentialsUpdateResponse()
            {
                User =
                    new UserDto()
                    {
                        DateOfBirth = new DateTime(1980, 01, 01),
                        CreatedAtUtc = new DateTime(2014, 01, 01, 08, 00, 00),
                        UserId = 1,
                        Username = "SomeUsername"
                    }
            };

            //When
            var stringBuilder = new StringBuilder();
            using (var stringOutput = new StringWriter(stringBuilder))
            {
                JSON.Serialize(model, stringOutput, Options.IncludeInherited);
            }
            var serializedJsonAsString = stringBuilder.ToString();

            // round tripping
            var deserializedRoundtrippedObject = JSON.Deserialize(serializedJsonAsString, typeof(UserCredentialsUpdateResponse), Options.IncludeInherited);
            var deserializedRoundtrippedInstance = deserializedRoundtrippedObject as UserCredentialsUpdateResponse;

            // Then
            Assert.NotEqual("{}", serializedJsonAsString);
            Assert.NotNull(deserializedRoundtrippedInstance);
            Assert.IsType<UserCredentialsUpdateResponse>(deserializedRoundtrippedInstance);

            Assert.NotNull(deserializedRoundtrippedInstance.User); // << this fails

            Assert.Equal(deserializedRoundtrippedInstance.User.CreatedAtUtc.ToUniversalTime(), model.User.CreatedAtUtc.ToUniversalTime());
            Assert.Equal(deserializedRoundtrippedInstance.User.DateOfBirth.ToUniversalTime(), model.User.DateOfBirth.ToUniversalTime());
            Assert.Equal(deserializedRoundtrippedInstance.User.UserId, model.User.UserId);
            Assert.Equal(deserializedRoundtrippedInstance.User.Username, model.User.Username);
        }
    }

    public class UserCredentialsUpdateResponse : UserResponse
    {
        public UserCredentialsUpdateResponse()
        {
        }
    }

    public class UserResponse : Response
    {
        public UserResponse()
        {

        }

        public UserDto User { get; set; }
    }

    public class UserDto : CreatedAtDto
    {
        public UserDto()
        {
        }

        public DateTime DateOfBirth { get; set; }

        public long UserId { get; set; }

        public string Username { get; set; }
    }

    #region Base Classes
    public abstract class CreatedAtDto
    {
        public virtual DateTime CreatedAtUtc { get; set; }
    }

    public abstract class Response
    {

    }
    #endregion Base Classes
}


text:
"""
https://open.kattis.com/problems/pet
"""

import sys

max_points = 0
winner = 0
for x in range(1, 6):
    line = sys.stdin
    grades = list(map(int, input().split()))

    points = sum(grades)
    if points > max_points:
        max_points = points
        winner = x

print("{} {}".format(winner, max_points))


text:
import React from 'react'
import { observer, inject } from 'mobx-react'
import { Collapse } from 'react-bootstrap'

import { GlyphButton } from '../others/form'

import EditorRowInput from './editor-row-input'
import EditorRowPicture from './editor-row-picture'

@inject('appStore', 'textbookEditorStore')
@observer
export default class EditorRowNew extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      open: this.props.open
    };
  }

  toggleOpen = e => {
    this.setState({
      open: !this.state.open
    })
  }

  addWord = e => {
    let data = {
      value: this.valueInput.value,
      meaning: this.meaningInput.value,
      word_class: this.wordClassInput.value,
      difficulty: this.difficultyInput.value,
      definition: this.definitionInput.value,
      definition_m: this.definitionmInput.value,
      usage: this.usageInput.value,
      usage_m: this.usagemInput.value,
    }

    this.valueInput.value = ''
    this.meaningInput.value = ''
    this.wordClassInput.value = 1
    this.difficultyInput.value = 2
    this.definitionInput.value = ''
    this.definitionmInput.value = ''
    this.usageInput.value = ''
    this.definitionmInput.value = ''

    this.props.textbookEditorStore.addWord(data)
  }

  inputBlur = e => {
    let value = this.valueInput.value
    let meaning = this.meaningInput.value
    this.difficultyInput.value = value.wordDifficulty(meaning)
  }

  render() {
    const { difficulties, wordClasses } = this.props.appStore

    return (

        <EditorRowInput className="title" name="value" type="input" placeholder="Slovo v cizím jazyce" onBlur={this.inputBlur} inputRef={ref => this.valueInput = ref}/>
        <EditorRowInput className="title" name="meaning" type="input" placeholder="Slovo v mateřském jazyce" onBlur={this.inputBlur} inputRef={ref => this.meaningInput = ref} />
        <EditorRowInput className="wordClasses" name="word_class" options={wordClasses} type="select" inputRef={ref => this.wordClassInput = ref} />
        <EditorRowInput className="difficulty" name="difficulty" options={difficulties} type="select" inputRef={ref => this.difficultyInput = ref} />

          <GlyphButton glyph="chevron-down" onClick={this.toggleOpen} />
          <GlyphButton glyph="plus" onClick={this.addWord} />

        <Collapse in={this.state.open}>

            <EditorRowInput className="text" name="definition" placeholder="Definice v cizím jazyce" type="input" inputRef={ref => this.definitionInput = ref} />
            <EditorRowInput className="text" name="usage" placeholder="Použití ve větě v cizím jazyce" type="input" inputRef={ref => this.usageInput = ref} />

        </Collapse>

    );
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<install type="module" version="1.0.0">
	<name>Custom HTML</name>
	<author>Joomla! Project</author>
	<creationDate>July 2004</creationDate>
	<copyright>Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.</copyright>
	<license>http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL</license>
	<authorEmail>admin@joomla.org</authorEmail>
	<authorUrl>www.joomla.org</authorUrl>
	<version>1.5.0</version>
	<description>DESCMODCUSTOM</description>
	<params>
		<param name="moduleclass_sfx" type="text" default="" label="Module Class Suffix" description="PARAMMODULECLASSSUFFIX" />
	</params>
</install>


text:
/**
 *
 */
package com.knowladgeduty.dto;

import javax.servlet.http.HttpServletRequest;

/**
 * The Class DataTableColumnSpecs.
 *
 * @author pavan.solapure
 */
public class DataTableColumnSpecs {

	/** The index. */
	private int index;

	/** The data. */
	private String data;

	/** The name. */
	private String name;

	/** The searchable. */
	private boolean searchable;

	/** The orderable. */
	private boolean orderable;

	/** The search. */
	private String search;

	/** The regex. */
	private boolean regex;

	/** The sort dir. */
	private String sortDir;

	/**
	 * Instantiates a new data table column specs.
	 *
	 * @param request the request
	 * @param i the i
	 */
	public DataTableColumnSpecs(HttpServletRequest request, int i) {
		this.setIndex(i);
		prepareColumnSpecs(request, i);
	}

	/**
	 * Gets the data.
	 *
	 * @return the data
	 */
	public String getData() {
		return data;
	}

	/**
	 * Sets the data.
	 *
	 * @param data the data to set
	 */
	public void setData(String data) {
		this.data = data;
	}

	/**
	 * Gets the name.
	 *
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * Sets the name.
	 *
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * Checks if is searchable.
	 *
	 * @return the searchable
	 */
	public boolean isSearchable() {
		return searchable;
	}

	/**
	 * Sets the searchable.
	 *
	 * @param searchable the searchable to set
	 */
	public void setSearchable(boolean searchable) {
		this.searchable = searchable;
	}

	/**
	 * Checks if is orderable.
	 *
	 * @return the orderable
	 */
	public boolean isOrderable() {
		return orderable;
	}

	/**
	 * Sets the orderable.
	 *
	 * @param orderable the orderable to set
	 */
	public void setOrderable(boolean orderable) {
		this.orderable = orderable;
	}

	/**
	 * Gets the search.
	 *
	 * @return the search
	 */
	public String getSearch() {
		return search;
	}

	/**
	 * Sets the search.
	 *
	 * @param search the search to set
	 */
	public void setSearch(String search) {
		this.search = search;
	}

	/**
	 * Checks if is regex.
	 *
	 * @return the regex
	 */
	public boolean isRegex() {
		return regex;
	}

	/**
	 * Sets the regex.
	 *
	 * @param regex the regex to set
	 */
	public void setRegex(boolean regex) {
		this.regex = regex;
	}

	/**
	 * Gets the sort dir.
	 *
	 * @return the sortDir
	 */
	public String getSortDir() {
		return sortDir;
	}

	/**
	 * Sets the sort dir.
	 *
	 * @param sortDir the sortDir to set
	 */
	public void setSortDir(String sortDir) {
		this.sortDir = (null != sortDir) ? sortDir.toUpperCase() : sortDir;
	}

	/**
	 * Gets the index.
	 *
	 * @return the index
	 */
	public int getIndex() {
		return index;
	}

	/**
	 * Sets the index.
	 *
	 * @param index the index to set
	 */
	public void setIndex(int index) {
		this.index = index;
	}

	/**
	 * Prepare column specs.
	 *
	 * @param request the request
	 * @param i the i
	 */
	private void prepareColumnSpecs(HttpServletRequest request, int i) {

		this.setData(request.getParameter("columns["+ i +"][data]"));
		this.setName(request.getParameter("columns["+ i +"][name]"));
		this.setOrderable(Boolean.valueOf(request.getParameter("columns["+ i +"][orderable]")));
		this.setRegex(Boolean.valueOf(request.getParameter("columns["+ i +"][search][regex]")));
		this.setSearch(request.getParameter("columns["+ i +"][search][value]"));
		this.setSearchable(Boolean.valueOf(request.getParameter("columns["+ i +"][searchable]")));

		int sortableCol = Integer.parseInt(request.getParameter("order[0][column]"));
		String sortDir = request.getParameter("order[0][dir]");

		if(i == sortableCol) {
			this.setSortDir(sortDir);
		}
	}

}


text:
package org.hillview.table.rows;

import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import org.hillview.table.api.ContentsKind;
import org.hillview.table.api.IStringColumn;
import org.hillview.utils.DateParsing;

import javax.annotation.Nullable;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;

/**
 * Helper class to guess the schema of data given a set of strings.
 */
public class GuessSchema {
    public static class SchemaInfo {
        public ContentsKind kind;
        public boolean      allowMissing;

        SchemaInfo(ContentsKind kind, boolean allowMissing) {
            this.kind = kind;
            this.allowMissing = allowMissing;
        }

        public String toString() {
            return this.kind.toString() + ", " +
                    (this.allowMissing ? "allow missing" : "no missing");
        }
    }

    enum CanParse {
        Yes,
        No,
        AsNull
    }

    /**
     * A lattice of contents kind.  Things can move only up in the lattice.
     */
    private static final HashMap<ContentsKind, ContentsKind[]> successor =
            new HashMap<ContentsKind, ContentsKind[]>();

    static {
        successor.put(ContentsKind.None, new ContentsKind[]{
                ContentsKind.Integer, ContentsKind.Double,
                ContentsKind.Duration, ContentsKind.Date,
                ContentsKind.Json, ContentsKind.String
        });
        successor.put(ContentsKind.Integer,
                new ContentsKind[] { ContentsKind.Double, ContentsKind.Json,
                        ContentsKind.String
        });
        successor.put(ContentsKind.Double,
                new ContentsKind[] { ContentsKind.Json, ContentsKind.String });
        successor.put(ContentsKind.Date, new ContentsKind[]
                { ContentsKind.String });
        successor.put(ContentsKind.Duration, new ContentsKind[]
                {  ContentsKind.String });
        successor.put(ContentsKind.Json, new ContentsKind[] { ContentsKind.String });
    }

    @Nullable
    private
    DateParsing dateParser;

    public GuessSchema() {
        this.dateParser = null;
    }

    private void guess(@Nullable String value, SchemaInfo info) {
        if (info.kind == ContentsKind.String)
            return;

        CanParse cp = this.canParse(value, info.kind);
        if (cp == CanParse.Yes)
            return;
        if (cp == CanParse.AsNull) {
            info.allowMissing = true;
            return;
        }
        ContentsKind[] succ = successor.get(info.kind);
        for (ContentsKind c: succ) {
            cp = this.canParse(value, c);
            if (cp == CanParse.AsNull) {
                info.kind = c;
                info.allowMissing = true;
                return;
            } else if (cp == CanParse.Yes) {
                info.kind = c;
                return;
            }
        }
        throw new RuntimeException("Could not guess kind of `" + value + "' currently " + info);
    }

    public SchemaInfo guess(Iterable<String> values) {
        SchemaInfo current = new SchemaInfo(ContentsKind.None, false);
        for (String s: values) {
            this.guess(s, current);
            if (current.kind == ContentsKind.String)
                return current;
        }
        return current;
    }

    public SchemaInfo guess(IStringColumn column) {
        SchemaInfo current = new SchemaInfo(ContentsKind.None, false);
        for (int i=0; i < column.sizeInRows(); i++) {
            this.guess(column.getString(i), current);
            if (current.kind == ContentsKind.String)
                return current;
        }
        return current;
    }

    private static boolean isJsonValid(final String json) throws IOException {
        return isJsonValid(new StringReader(json));
    }

    private static boolean isJsonValid(final Reader reader)
            throws IOException {
        return isJsonValid(new JsonReader(reader));
    }

    /**
     * Throws if the value is not valid JSON
     * The gson parser is not strict enough: it parses
     * unquoted strings as JSON.String, so we have to do this manually.
     * Returns true if this is a complex json value, false otherwise.
     */
    private static boolean isJsonValid(final JsonReader jsonReader) throws IOException {
        JsonToken token;
        boolean isComplex = false;
        loop:
        while ((token = jsonReader.peek()) != JsonToken.END_DOCUMENT && token != null) {
            switch (token) {
                case BEGIN_ARRAY:
                    isComplex = true;
                    jsonReader.beginArray();
                    break;
                case END_ARRAY:
                    isComplex = true;
                    jsonReader.endArray();
                    break;
                case BEGIN_OBJECT:
                    isComplex = true;
                    jsonReader.beginObject();
                    break;
                case END_OBJECT:
                    isComplex = true;
                    jsonReader.endObject();
                    break;
                case NAME:
                    jsonReader.nextName();
                    break;
                case STRING:
                case NUMBER:
                case BOOLEAN:
                case NULL:
                    jsonReader.skipValue();
                    break;
                case END_DOCUMENT:
                    break loop;
                default:
                    throw new AssertionError(token);
            }
        }
        return isComplex;
    }

    private CanParse canParse(@Nullable String value, final ContentsKind with) {
        if (value == null)
            return CanParse.AsNull;
        switch (with) {
            case None:
                return CanParse.No;
            case String:
                return CanParse.Yes;
            case Date:
                try {
                    if (this.dateParser == null)
                        this.dateParser = new DateParsing(value);
                    this.dateParser.parse(value);
                    return CanParse.Yes;
                } catch (Exception ex) {
                    return CanParse.No;
                }
            case Integer:
                try {
                    // Allow empty strings as numbers
                    if (value.trim().isEmpty())
                        return CanParse.AsNull;
                    Integer.parseInt(value);
                    return CanParse.Yes;
                } catch (Exception ex) {
                    return CanParse.No;
                }
            case Json:
                return CanParse.No;
                // TODO: reinstate this
                /*
                try {
                    isJsonValid(value);
                    return CanParse.Yes;
                } catch (Exception ex) {
                    return CanParse.No;
                }
                */
            case Double:
                try {
                    // Allow empty strings as numbers
                    if (value.trim().isEmpty())
                        return CanParse.AsNull;
                    Double.parseDouble(value);
                    return CanParse.Yes;
                } catch (Exception ex) {
                    return CanParse.No;
                }
            case Duration:
                // TODO: how do durations look as strings?
                return CanParse.No;
        }
        throw new RuntimeException("Unexpected kind " + with);
    }
}


text:
using System;

namespace TubeStar
{
    public class Memetic : VideoAttribute
    {
        public override string Name
        {
            get { return EnglishStrings.MemeticAttribute.Translate(); }
        }

        public override string Description
        {
            get { return EnglishStrings.MemeticAttributeDescription.Translate(); }
        }

        public override int Cost
        {
            get { return 1; }
        }
    }
}


text:
<?php

namespace ConfigToken\Tests\TreeSerializer;

use ConfigToken\Tests\TreeSerializer\Types\ValidCustomTreeSerializer;
use ConfigToken\TreeSerializer\TreeSerializerFactory;

class TreeSerializerFactoryTest extends \PHPUnit_Framework_TestCase
{
    public function testRegister()
    {
        $serializer = new ValidCustomTreeSerializer();
        TreeSerializerFactory::register($serializer);
        $this->assertTrue(TreeSerializerFactory::isRegistered($serializer));
        $this->assertTrue(TreeSerializerFactory::isRegisteredByFileExtension($serializer->getFileExtension()));
        $this->assertTrue(TreeSerializerFactory::isRegisteredByContentType($serializer->getContentType()));
        $this->assertEquals($serializer, TreeSerializerFactory::getByFileExtension($serializer->getFileExtension()));
        $this->assertEquals($serializer, TreeSerializerFactory::getByContentType($serializer->getContentType()));
    }

    /**
     * @expectedException \ConfigToken\Exception\AlreadyRegisteredException
     */
    public function testAlreadyRegistered()
    {
        $serializer = new ValidCustomTreeSerializer();
        TreeSerializerFactory::register($serializer);
        TreeSerializerFactory::register($serializer);
    }

    /**
     * @expectedException \ConfigToken\TreeSerializer\Exception\UnknownContentTypeException
     */
    public function testUnknownContentType()
    {
        TreeSerializerFactory::getByContentType('rubbish');
    }

    /**
     * @expectedException \ConfigToken\TreeSerializer\Exception\UnknownFileExtensionException
     */
    public function testUnknownFileExtension()
    {
        TreeSerializerFactory::getByFileExtension('rubbish');
    }
}


text:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;
using Csla.Properties;

namespace Csla
{

  /// <summary>
  /// Provides a sorted view into an existing IList(Of T).
  /// </summary>
  /// <typeparam name="T">
  /// Type of child object contained by
  /// the original list or collection.
  /// </typeparam>
  public class SortedBindingList<T> :
    IList<T>, IBindingList, IEnumerable<T>, ICancelAddNew
  {

    #region ListItem class

    private class ListItem : IComparable<ListItem>
    {

      private object _key;
      private int _baseIndex;

      public object Key
      {
        get { return _key; }
      }

      public int BaseIndex
      {
        get { return _baseIndex; }
        set { _baseIndex = value; }
      }

      public ListItem(object key, int baseIndex)
      {
        _key = key;
        _baseIndex = baseIndex;
      }

      public int CompareTo(ListItem other)
      {
        object target = other.Key;

        if (Key is IComparable)
          return ((IComparable)Key).CompareTo(target);

        else
        {
          if (Key == null)
          {
            if (target == null)
              return 0;
            else
              return 1;
          }
          else if (Key.Equals(target))
            return 0;

          else if (target == null)
            return 1;

          return Key.ToString().CompareTo(target.ToString());
        }
      }

      public override string ToString()
      {
        return Key.ToString();
      }

    }

    #endregion

    #region Sorted enumerator

    private class SortedEnumerator : IEnumerator<T>
    {
      private IList<T> _list;
      private List<ListItem> _sortIndex;
      private ListSortDirection _sortOrder;
      private int _index;

      public SortedEnumerator(
        IList<T> list,
        List<ListItem> sortIndex,
        ListSortDirection direction)
      {
        _list = list;
        _sortIndex = sortIndex;
        _sortOrder = direction;
        Reset();
      }

      public T Current
      {
        get { return _list[_sortIndex[_index].BaseIndex]; }
      }

      Object System.Collections.IEnumerator.Current
      {
        get { return _list[_sortIndex[_index].BaseIndex]; }
      }

      public bool MoveNext()
      {
        if (_sortOrder == ListSortDirection.Ascending)
        {
          if (_index < _sortIndex.Count - 1)
          {
            _index++;
            return true;
          }
          else
            return false;
        }
        else
        {
          if (_index > 0)
          {
            _index--;
            return true;
          }
          else
            return false;
        }
      }

      public void Reset()
      {
        if (_sortOrder == ListSortDirection.Ascending)
          _index = -1;
        else
          _index = _sortIndex.Count;
      }

      #region IDisposable Support

      private bool _disposedValue = false; // To detect redundant calls.

      // IDisposable
      protected virtual void Dispose(bool disposing)
      {
        if (!_disposedValue)
        {
          if (disposing)
          {
            // free unmanaged resources when explicitly called
          }
          // free shared unmanaged resources
        }
        _disposedValue = true;
      }

      // this code added to correctly implement the disposable pattern.
      public void Dispose()
      {
        // Do not change this code.  Put cleanup code in Dispose(bool disposing) above.
        Dispose(true);
        GC.SuppressFinalize(this);
      }

      /// <summary>
      /// Allows an <see cref="T:System.Object"/> to attempt to free resources and perform other cleanup operations before the <see cref="T:System.Object"/> is reclaimed by garbage collection.
      /// </summary>
      ~SortedEnumerator()
      {
        Dispose(false);
      }

      #endregion

    }

    #endregion

    #region Sort/Unsort

    private void DoSort()
    {
      int index = 0;
      _sortIndex.Clear();

      if (_sortBy == null)
      {
        foreach (T obj in _list)
        {
          _sortIndex.Add(new ListItem(obj, index));
          index++;
        }
      }
      else
      {
        foreach (T obj in _list)
        {
          _sortIndex.Add(new ListItem(_sortBy.GetValue(obj), index));
          index++;
        }
      }

      _sortIndex.Sort();
      _sorted = true;

      OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, 0));

    }

    private void UndoSort()
    {
      _sortIndex.Clear();
      _sortBy = null;
      _sortOrder = ListSortDirection.Ascending;
      _sorted = false;

      OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, 0));

    }

    #endregion

    #region IEnumerable<T>

    /// <summary>
    /// Returns an enumerator for the list, honoring
    /// any sort that is active at the time.
    /// </summary>
    public IEnumerator<T> GetEnumerator()
    {
      if (_sorted)
        return new SortedEnumerator(_list, _sortIndex, _sortOrder);
      else
        return _list.GetEnumerator();
    }

    #endregion

    #region IBindingList, IList<T>

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    /// <param name="property">Property on which
    /// to build the index.</param>
    public void AddIndex(PropertyDescriptor property)
    {
      if (_supportsBinding)
        _bindingList.AddIndex(property);
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    public object AddNew()
    {
      object result;
      if (_supportsBinding)
      {
        _initiatedLocally = true;
        result = _bindingList.AddNew();
        _initiatedLocally = false;
        OnListChanged(
          new ListChangedEventArgs(
          ListChangedType.ItemAdded, _bindingList.Count - 1));
      }
      else
        result = null;

      return result;
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    public bool AllowEdit
    {
      get
      {
        if (_supportsBinding)
          return _bindingList.AllowEdit;
        else
          return false;
      }
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    public bool AllowNew
    {
      get
      {
        if (_supportsBinding)
          return _bindingList.AllowNew;
        else
          return false;
      }
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    public bool AllowRemove
    {
      get
      {
        if (_supportsBinding)
          return _bindingList.AllowRemove;
        else
          return false;
      }
    }

    /// <summary>
    /// Applies a sort to the view.
    /// </summary>
    /// <param name="propertyName">The text name of the property on which to sort.</param>
    /// <param name="direction">The direction to sort the data.</param>
    public void ApplySort(string propertyName, ListSortDirection direction)
    {
      _sortBy = GetPropertyDescriptor(propertyName);

      ApplySort(_sortBy, direction);
    }

    /// <summary>
    /// Applies a sort to the view.
    /// </summary>
    /// <param name="property">A PropertyDescriptor for the property on which to sort.</param>
    /// <param name="direction">The direction to sort the data.</param>
    public void ApplySort(
      PropertyDescriptor property, ListSortDirection direction)
    {
      _sortBy = property;
      _sortOrder = direction;
      DoSort();
    }

    /// <summary>
    /// Finds an item in the view
    /// </summary>
    /// <param name="propertyName">Name of the property to search</param>
    /// <param name="key">Value to find</param>
    public int Find(string propertyName, object key)
    {
      PropertyDescriptor findProperty = GetPropertyDescriptor(propertyName);

      return Find(findProperty, key);

    }

    private static PropertyDescriptor GetPropertyDescriptor(string propertyName)
    {
      PropertyDescriptor property = null;

      if (!String.IsNullOrEmpty(propertyName))
      {
        Type itemType = typeof(T);
        foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(itemType))
        {
          if (prop.Name == propertyName)
          {
            property = prop;
            break;
          }
        }

        // throw exception if propertyDescriptor could not be found
        if (property == null)
          throw new ArgumentException(string.Format(Resources.SortedBindingListPropertyNameNotFound, propertyName), propertyName);
      }

      return property;
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    /// <param name="key">Key value for which to search.</param>
    /// <param name="property">Property to search for the key
    /// value.</param>
    public int Find(PropertyDescriptor property, object key)
    {
      if (_supportsBinding)
      {
        var originalIndex = _bindingList.Find(property, key);
        return originalIndex > -1 ? SortedIndex(originalIndex) : -1;
      }
      else
        return -1;
    }

    /// <summary>
    /// Gets a value indicating whether the view is currently sorted.
    /// </summary>
    public bool IsSorted
    {
      get { return _sorted; }
    }

    /// <summary>
    /// Raised to indicate that the list's data has changed.
    /// </summary>
    /// <remarks>
    /// This event is raised if the underling IList object's data changes
    /// (assuming the underling IList also implements the IBindingList
    /// interface). It is also raised if the sort property or direction
    /// is changed to indicate that the view's data has changed. See
    /// Chapter 5 for details.
    /// </remarks>
    public event ListChangedEventHandler ListChanged;

    /// <summary>
    /// Raises the <see cref="ListChanged"/> event.
    /// </summary>
    /// <param name="e">Event arguments.</param>
    protected void OnListChanged(ListChangedEventArgs e)
    {
      if (ListChanged != null)
        ListChanged(this, e);
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    /// <param name="property">Property for which the
    /// index should be removed.</param>
    public void RemoveIndex(PropertyDescriptor property)
    {
      if (_supportsBinding)
        _bindingList.RemoveIndex(property);
    }

    /// <summary>
    /// Removes any sort currently applied to the view.
    /// </summary>
    public void RemoveSort()
    {
      UndoSort();
    }

    /// <summary>
    /// Returns the direction of the current sort.
    /// </summary>
    public ListSortDirection SortDirection
    {
      get { return _sortOrder; }
    }

    /// <summary>
    /// Returns the PropertyDescriptor of the current sort.
    /// </summary>
    public PropertyDescriptor SortProperty
    {
      get { return _sortBy; }
    }

    /// <summary>
    /// Returns true since this object does raise the
    /// ListChanged event.
    /// </summary>
    public bool SupportsChangeNotification
    {
      get { return true; }
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    public bool SupportsSearching
    {
      get
      {
        if (_supportsBinding)
          return _bindingList.SupportsSearching;
        else
          return false;
      }
    }

    /// <summary>
    /// Returns true. Sorting is supported.
    /// </summary>
    public bool SupportsSorting
    {
      get { return true; }
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    /// <param name="array">Array to receive the data.</param>
    /// <param name="arrayIndex">Starting array index.</param>
    public void CopyTo(T[] array, int arrayIndex)
    {
      int pos = arrayIndex;
      foreach (T child in this)
      {
        array[pos] = child;
        pos++;
      }
    }

    void System.Collections.ICollection.CopyTo(System.Array array, int index)
    {
      T[] tmp = new T[array.Length];
      CopyTo(tmp, index);
      Array.Copy(tmp, 0, array, index, array.Length);
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    public int Count
    {
      get { return _list.Count; }
    }

    bool System.Collections.ICollection.IsSynchronized
    {
      get { return false; }
    }

    object System.Collections.ICollection.SyncRoot
    {
      get { return _list; }
    }

    IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    /// <param name="item">Item to add to the list.</param>
    public void Add(T item)
    {
      _list.Add(item);
    }

    int System.Collections.IList.Add(object value)
    {
      Add((T)value);
      return SortedIndex(_list.Count - 1);
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    public void Clear()
    {
      _list.Clear();
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    /// <param name="item">Item for which to search.</param>
    public bool Contains(T item)
    {
      return _list.Contains(item);
    }

    bool System.Collections.IList.Contains(object value)
    {
      return Contains((T)value);
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    /// <param name="item">Item for which to search.</param>
    public int IndexOf(T item)
    {
      return SortedIndex(_list.IndexOf(item));
    }

    int System.Collections.IList.IndexOf(object value)
    {
      return IndexOf((T)value);
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    /// <param name="index">Index at
    /// which to insert the item.</param>
    /// <param name="item">Item to insert.</param>
    public void Insert(int index, T item)
    {
      _list.Insert(index, item);
    }

    void System.Collections.IList.Insert(int index, object value)
    {
      Insert(index, (T)value);
    }

    bool System.Collections.IList.IsFixedSize
    {
      get { return false; }
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    public bool IsReadOnly
    {
      get { return _list.IsReadOnly; }
    }

    object System.Collections.IList.this[int index]
    {
      get
      {
        return this[index];
      }
      set
      {
        this[index] = (T)value;
      }
    }

    /// <summary>
    /// Implemented by IList source object.
    /// </summary>
    /// <param name="item">Item to be removed.</param>
    public bool Remove(T item)
    {
      return _list.Remove(item);
    }

    void System.Collections.IList.Remove(object value)
    {
      Remove((T)value);
    }

    /// <summary>
    /// Removes the child object at the specified index
    /// in the list, resorting the display as needed.
    /// </summary>
    /// <param name="index">The index of the object to remove.</param>
    /// <remarks>
    /// See Chapter 5 for details on how and why the list is
    /// altered during the remove process.
    /// </remarks>
    public void RemoveAt(int index)
    {
      if (_sorted)
      {
        _initiatedLocally = true;
        int baseIndex = OriginalIndex(index);

        // remove the item from the source list
        _list.RemoveAt(baseIndex);

        _initiatedLocally = false;
      }
      else
        _list.RemoveAt(index);
    }

    /// <summary>
    /// Gets the child item at the specified index in the list,
    /// honoring the sort order of the items.
    /// </summary>
    /// <param name="index">The index of the item in the sorted list.</param>
    public T this[int index]
    {
      get
      {
        if (_sorted)
          return _list[OriginalIndex(index)];
        else
          return _list[index];
      }
      set
      {
        if (_sorted)
          _list[OriginalIndex(index)] = value;
        else
          _list[index] = value;
      }
    }

    #endregion

    #region SourceList

    /// <summary>
    /// Gets the source list over which this
    /// SortedBindingList is a view.
    /// </summary>
    [EditorBrowsable(EditorBrowsableState.Advanced)]
    public IList<T> SourceList
    {
      get
      {
        return _list;
      }
    }

    #endregion

    private IList<T> _list;
    private bool _supportsBinding;
    private IBindingList _bindingList;
    private bool _sorted;
    private bool _initiatedLocally;
    private PropertyDescriptor _sortBy;
    private ListSortDirection _sortOrder =
      ListSortDirection.Ascending;
    private List<ListItem> _sortIndex =
      new List<ListItem>();

    /// <summary>
    /// Creates a new view based on the provided IList object.
    /// </summary>
    /// <param name="list">The IList (collection) containing the data.</param>
    public SortedBindingList(IList<T> list)
    {
      _list = list;

      if (_list is IBindingList)
      {
        _supportsBinding = true;
        _bindingList = (IBindingList)_list;
        _bindingList.ListChanged +=
          new ListChangedEventHandler(SourceChanged);
      }
    }

    private void SourceChanged(
      object sender, ListChangedEventArgs e)
    {
      if (_sorted)
      {
        switch (e.ListChangedType)
        {
          case ListChangedType.ItemAdded:
            T newItem = _list[e.NewIndex];
            if (e.NewIndex == _list.Count - 1)
            {
              object newKey;
              if (_sortBy != null)
                newKey = _sortBy.GetValue(newItem);
              else
                newKey = newItem;

              if (_sortOrder == ListSortDirection.Ascending)
                _sortIndex.Add(
                  new ListItem(newKey, e.NewIndex));
              else
                _sortIndex.Insert(0,
                  new ListItem(newKey, e.NewIndex));
              if (!_initiatedLocally)
                OnListChanged(
                  new ListChangedEventArgs(
                  ListChangedType.ItemAdded,
                  SortedIndex(e.NewIndex)));
            }
            else
              DoSort();
            break;

          case ListChangedType.ItemChanged:
            // an item changed - just relay the event with
            // a translated index value
            OnListChanged(
              new ListChangedEventArgs(
              ListChangedType.ItemChanged, SortedIndex(e.NewIndex), e.PropertyDescriptor));
            break;

          case ListChangedType.ItemDeleted:
            var internalIndex = InternalIndex(e.NewIndex);
            var sortedIndex = internalIndex;
            if ((_sorted) && (_sortOrder == ListSortDirection.Descending))
              sortedIndex = _sortIndex.Count - 1 - internalIndex;

            // remove from internal list
            _sortIndex.RemoveAt(internalIndex);

            // now fix up all index pointers in the sort index
            foreach (ListItem item in _sortIndex)
              if (item.BaseIndex > e.NewIndex)
                item.BaseIndex -= 1;

            OnListChanged(
               new ListChangedEventArgs(
              ListChangedType.ItemDeleted, sortedIndex, e.PropertyDescriptor));
            break;

          default:
            // for anything other than add, delete or change
            // just re-sort the list
            if (!_initiatedLocally)
              DoSort();
            break;
        }
      }
      else
      {
        if (!_initiatedLocally)
          OnListChanged(e);
      }
    }

    private int OriginalIndex(int sortedIndex)
    {
      if (sortedIndex == -1) return -1;

      if (_sorted)
      {
        if (_sortOrder == ListSortDirection.Ascending)
          return _sortIndex[sortedIndex].BaseIndex;
        else
          return _sortIndex[_sortIndex.Count - 1 - sortedIndex].BaseIndex;
      }
      else
        return sortedIndex;
    }

    private int SortedIndex(int originalIndex)
    {
      if (originalIndex == -1) return -1;

      int result = 0;
      if (_sorted)
      {
        for (int index = 0; index < _sortIndex.Count; index++)
        {
          if (_sortIndex[index].BaseIndex == originalIndex)
          {
            result = index;
            break;
          }
        }
        if (_sortOrder == ListSortDirection.Descending)
          result = _sortIndex.Count - 1 - result;
      }
      else
        result = originalIndex;
      return result;
    }

    private int InternalIndex(int originalIndex)
    {
      int result = 0;
      if (_sorted)
      {
        for (int index = 0; index < _sortIndex.Count; index++)
        {
          if (_sortIndex[index].BaseIndex == originalIndex)
          {
            result = index;
            break;
          }
        }
      }
      else
        result = originalIndex;
      return result;
    }

    #region ICancelAddNew Members

    void ICancelAddNew.CancelNew(int itemIndex)
    {
      if (itemIndex <= -1) return;

      ICancelAddNew can = _list as ICancelAddNew;
      if (can != null)
        can.CancelNew(OriginalIndex(itemIndex));
      else
        _list.RemoveAt(OriginalIndex(itemIndex));
    }

    void ICancelAddNew.EndNew(int itemIndex)
    {
      ICancelAddNew can = _list as ICancelAddNew;
      if (can != null)
        can.EndNew(OriginalIndex(itemIndex));
    }

    #endregion

    #region ToArray

    /// <summary>
    /// Get an array containing all items in the list.
    /// </summary>
    public T[] ToArray()
    {
      List<T> result = new List<T>();
      foreach (T item in this)
        result.Add(item);
      return result.ToArray();
    }

    #endregion

  }
}
#endif


text:
import collections

from oslo_log import log as logging
from oslo_utils import reflection

from neutron._i18n import _LE
from neutron.callbacks import events
from neutron.callbacks import exceptions

LOG = logging.getLogger(__name__)

class CallbacksManager(object):
    """A callback system that allows objects to cooperate in a loose manner."""

    def __init__(self):
        self.clear()

    def subscribe(self, callback, resource, event):
        """Subscribe callback for a resource event.

        The same callback may register for more than one event.

        :param callback: the callback. It must raise or return a boolean.
        :param resource: the resource. It must be a valid resource.
        :param event: the event. It must be a valid event.
        """
        LOG.debug("Subscribe: %(callback)s %(resource)s %(event)s",
                  {'callback': callback, 'resource': resource, 'event': event})

        callback_id = _get_id(callback)
        try:
            self._callbacks[resource][event][callback_id] = callback
        except KeyError:
            # Initialize the registry for unknown resources and/or events
            # prior to enlisting the callback.
            self._callbacks[resource][event] = {}
            self._callbacks[resource][event][callback_id] = callback
        # We keep a copy of callbacks to speed the unsubscribe operation.
        if callback_id not in self._index:
            self._index[callback_id] = collections.defaultdict(set)
        self._index[callback_id][resource].add(event)

    def unsubscribe(self, callback, resource, event):
        """Unsubscribe callback from the registry.

        :param callback: the callback.
        :param resource: the resource.
        :param event: the event.
        """
        LOG.debug("Unsubscribe: %(callback)s %(resource)s %(event)s",
                  {'callback': callback, 'resource': resource, 'event': event})

        callback_id = self._find(callback)
        if not callback_id:
            LOG.debug("Callback %s not found", callback_id)
            return
        if resource and event:
            del self._callbacks[resource][event][callback_id]
            self._index[callback_id][resource].discard(event)
            if not self._index[callback_id][resource]:
                del self._index[callback_id][resource]
                if not self._index[callback_id]:
                    del self._index[callback_id]
        else:
            value = '%s,%s' % (resource, event)
            raise exceptions.Invalid(element='resource,event', value=value)

    def unsubscribe_by_resource(self, callback, resource):
        """Unsubscribe callback for any event associated to the resource.

        :param callback: the callback.
        :param resource: the resource.
        """
        callback_id = self._find(callback)
        if callback_id:
            if resource in self._index[callback_id]:
                for event in self._index[callback_id][resource]:
                    del self._callbacks[resource][event][callback_id]
                del self._index[callback_id][resource]
                if not self._index[callback_id]:
                    del self._index[callback_id]

    def unsubscribe_all(self, callback):
        """Unsubscribe callback for all events and all resources.

        :param callback: the callback.
        """
        callback_id = self._find(callback)
        if callback_id:
            for resource, resource_events in self._index[callback_id].items():
                for event in resource_events:
                    del self._callbacks[resource][event][callback_id]
            del self._index[callback_id]

    def notify(self, resource, event, trigger, **kwargs):
        """Notify all subscribed callback(s).

        Dispatch the resource's event to the subscribed callbacks.

        :param resource: the resource.
        :param event: the event.
        :param trigger: the trigger. A reference to the sender of the event.
        """
        errors = self._notify_loop(resource, event, trigger, **kwargs)
        if errors and event.startswith(events.BEFORE):
            abort_event = event.replace(
                events.BEFORE, events.ABORT)
            self._notify_loop(resource, abort_event, trigger)
            raise exceptions.CallbackFailure(errors=errors)

    def clear(self):
        """Brings the manager to a clean slate."""
        self._callbacks = collections.defaultdict(dict)
        self._index = collections.defaultdict(dict)

    def _notify_loop(self, resource, event, trigger, **kwargs):
        """The notification loop."""
        LOG.debug("Notify callbacks for %(resource)s, %(event)s",
                  {'resource': resource, 'event': event})

        errors = []
        callbacks = self._callbacks[resource].get(event, {}).items()
        # TODO(armax): consider using a GreenPile
        for callback_id, callback in callbacks:
            try:
                LOG.debug("Calling callback %s", callback_id)
                callback(resource, event, trigger, **kwargs)
            except Exception as e:
                LOG.exception(_LE("Error during notification for "
                                  "%(callback)s %(resource)s, %(event)s"),
                              {'callback': callback_id,
                               'resource': resource,
                               'event': event})
                errors.append(exceptions.NotificationError(callback_id, e))
        return errors

    def _find(self, callback):
        """Return the callback_id if found, None otherwise."""
        callback_id = _get_id(callback)
        return callback_id if callback_id in self._index else None

def _get_id(callback):
    """Return a unique identifier for the callback."""
    # TODO(armax): consider using something other than names
    # https://www.python.org/dev/peps/pep-3155/, but this
    # might be okay for now.
    return reflection.get_callable_name(callback)


text:
using Cake.Core.Diagnostics;

namespace Cake.Diagnostics
{
    /// <summary>
    /// Represents a verbosity aware log.
    /// </summary>
    public interface IVerbosityAwareLog : ICakeLog
    {
        /// <summary>
        /// Gets or sets the verbosity.
        /// </summary>
        /// <value>The verbosity.</value>
        Verbosity Verbosity { get; set; }
    }
}


text:
"""Module for the NotEqualsSubstitution substitution."""

from typing import Any
from typing import Iterable
from typing import Optional
from typing import Text
from typing import Union

from .equals_substitution import EqualsSubstitution
from ..frontend import expose_substitution
from ..launch_context import LaunchContext

@expose_substitution('not-equals')
class NotEqualsSubstitution(EqualsSubstitution):
    """
    Substitution that checks if two inputs are not equal.

    Returns 'true' or 'false' strings depending on the result.
    """

    def __init__(
        self,
        left: Optional[Union[Any, Iterable[Any]]],
        right: Optional[Union[Any, Iterable[Any]]]
    ) -> None:
        """Create a NotEqualsSubstitution substitution."""
        super().__init__(left, right)

    def describe(self) -> Text:
        """Return a description of this substitution as a string."""
        return f'NotEqualsSubstitution({self.left} {self.right})'

    def perform(self, context: LaunchContext) -> Text:
        """Perform the substitution."""
        return str(not (super().perform(context) == 'true')).lower()


text:
<results>
<result item="1">
[<block>{key 1 one}</block>]
</result>
<result item="2">
[<block>{key 1 two}</block>]
</result>
<result item="3">
[<block>{key 1 three}</block>]
</result>
<result item="4">
[<block>{key 2 four}</block>]
</result>
<result item="5">
[<block>{key 3 five}</block>]
</result>
<result item="6">
[<block>{key 3 six}</block>]
</result>
<result item="7">
[<block>{key 3 seven}</block>]
</result>
<result item="8">
[<block>{key 3 eight}</block>]
</result>
<result item="9">
[<block>{key 4 nine}</block>]
</result>
<result item="10">
[<block>{key 3 ten}</block>]
</result>
</results>


text:
package server;

import help.ClientCommand;
import help.ServerInfo;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class ChatServer implements Runnable {

	private final ServerInfo serverInfo;
	private Thread currentThread;
	private Map<String, Socket> clients;
	private Thread clientHandlerThread[];
	private Logger log;
	private int verbose;

	public ChatServer(ServerInfo serverInfo, int verbose) {
		this.serverInfo = serverInfo;
		this.clients = new HashMap<String, Socket>();
		this.clientHandlerThread = new Thread[(int) serverInfo.getMaxClients()];
		this.verbose = verbose;
	}

	int getFreeThreadId() {
		for (int i = 0; i < this.clientHandlerThread.length; i++) {
			if (this.clientHandlerThread[i] != null && this.clientHandlerThread[i].isAlive())
				continue;
			else {
				this.log.info("get Free Thread Id: " + i);
				return i;
			}
		}
		this.log.info("get Free Thread Id: -1");
		return -1;
	}

	@Override
	public void run() {
		initializeLogger();
		this.log.info("Start chat server");
		this.currentThread = Thread.currentThread();
		if (this.currentThread.isInterrupted()) {
			this.log.info("current Thread is Interrupted");
			this.log.severe("finish -1");
			return;
		}
		ServerSocket serverSocket = createServerSocket();
		if (serverSocket == null){
			this.log.severe("finish -2");
			return;
		}

		while (true) {
			if (isCurrentThreadInterrupted(serverSocket))
			{
				this.log.info("finish -3");
				return;
			}
			if (this.clients.size() >= this.serverInfo.getMaxClients())
			{
				this.log.info("server is busy");
				continue;
			}
			Socket clientSocket = null;
			try {
				this.log.info("server Socket WAIT client Socket");
				clientSocket = serverSocket.accept();
				this.log.info("server Socket ACCEPT client Socket: " + clientSocket.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				clientSocket = null;
				this.log.severe("server Socket ACCEPT client Socket: fail");
			}
			if (clientSocket == null)
			{
				this.log.info("clientSocket == null --> continue");
				continue;
			}

			int threadId = getFreeThreadId();
			if (threadId < 0) continue;
			ClientHandler clientHandler = new ClientHandler(clientSocket, this, threadId, this.verbose);
			this.log.info("CREATE client Handler: " + clientHandler.toString());
			this.clientHandlerThread[threadId] = new Thread(clientHandler);
			this.log.info("CREATE Thread[" + threadId + "] for client Handler");
			clientHandlerThread[threadId].start();
			this.log.info("START Thread[" + threadId + "] for client Handler");
		}
	}

	/**
	 *
	 */
	private void initializeLogger() {
		this.log = Logger.getLogger(this.getClass().getName());
		try {
			FileHandler fh = new FileHandler(this.getClass().getName().replace("class ", "") + ".log");
			fh.setFormatter(new SimpleFormatter());
			this.log.addHandler(fh);
		} catch (SecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		this.log.setUseParentHandlers(this.verbose != 0);
		this.log.setLevel(Level.ALL);
	}

	/**
	 * @param serverSocket
	 */
	private boolean isCurrentThreadInterrupted(ServerSocket serverSocket) {
		if (this.currentThread.isInterrupted()) {
			this.log.info("current Thread is Interrupted");
			try {
				serverSocket.close();
				this.log.info("close server Socket: " + serverSocket.toString());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				this.log.severe("close server Socket: fail");
			}
			for (int i = 0; i < this.clientHandlerThread.length; i++)
				if (this.clientHandlerThread[i] != null && this.clientHandlerThread[i].isAlive())
				{
					this.log.info("interrupt clientHandlerThread[" + i + "]");
					this.clientHandlerThread[i].interrupt();
				}
			for (int i = 0; i < this.clientHandlerThread.length; i++)
				if (this.clientHandlerThread[i] != null && this.clientHandlerThread[i].isAlive())
					try {
						this.log.info("join clientHandlerThread[" + i + "]");
						this.clientHandlerThread[i].join();
					} catch (InterruptedException e) {
						this.log.severe("InterruptedException join clientHandlerThread[" + i + "]");
						continue; // never be here
					}

			return true;
		}
		return false;
	}

	/**
	 * @return
	 */
	private ServerSocket createServerSocket() {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(this.serverInfo.getPort());
			this.log.info("create Server Socket: " + serverSocket.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			serverSocket = null;
			this.log.severe("create Server Socket: fail IOException");
		}
		return serverSocket;
	}

	public synchronized boolean manageClients(ClientCommand command, ManageClientArgument client) {
		this.log.info("manageClients: " + command.getName());
		switch (command) {
		case USER:
			if (this.clients.containsKey(client.clientName))
			{
				this.log.info("return false");
				return false;
			}
			this.clients.put(client.clientName, client.clientSocket);
			break;
		case BYE:
			if (!this.clients.containsKey(client.clientName))
			{
				this.log.info("return false");
				return false;
			}
			client.clientSocket = this.clients.remove(client.clientName);
			break;
		case SEND_TO:
		case SEND_FILE_TO:
			if (!this.clients.containsKey(client.clientName))
			{
				this.log.info("return false");
				return false;
			}
			client.clientSocket = this.clients.get(client.clientName);
		case SEND_ALL:
			if (!this.clients.containsKey(client.clientName))
			{
				this.log.info("return false");
				return false;
			}
			client.clientsSocket = this.clients.values();
			break;
		case LIST:
			if (!this.clients.containsKey(client.clientName))
			{
				this.log.info("return false");
				return false;
			}
			client.clientName = this.clients.keySet().toString();
			break;
		default:
			break;
		}
		this.log.info("return true");
		return true;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<Type Name="CCWavesTiles3D" FullName="Cocos2D.CCWavesTiles3D">
  <TypeSignature Language="C#" Value="public class CCWavesTiles3D : Cocos2D.CCTiledGrid3DAction" />
  <TypeSignature Language="ILAsm" Value=".class public auto ansi beforefieldinit CCWavesTiles3D extends Cocos2D.CCTiledGrid3DAction" />
  <AssemblyInfo>
    <AssemblyName>cocos2d-xna</AssemblyName>
    <AssemblyVersion>2.0.3.0</AssemblyVersion>
  </AssemblyInfo>
  <Base>
    <BaseTypeName>Cocos2D.CCTiledGrid3DAction</BaseTypeName>
  </Base>
  <Interfaces />
  <Docs>

      <para> action. </para>

    <remarks>To be added.</remarks>
  </Docs>
  <Members>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CCWavesTiles3D ();" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor() cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.3.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters />
      <Docs>
        creates the action with a number of waves, the waves amplitude, the grid size and the duration
        <remarks />
      </Docs>
    </Member>
    <Member MemberName=".ctor">
      <MemberSignature Language="C#" Value="public CCWavesTiles3D (float duration, Cocos2D.CCGridSize gridSize, int waves, float amplitude);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig specialname rtspecialname instance void .ctor(float32 duration, valuetype Cocos2D.CCGridSize gridSize, int32 waves, float32 amplitude) cil managed" />
      <MemberType>Constructor</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.3.0</AssemblyVersion>
      </AssemblyInfo>
      <Parameters>
        <Parameter Name="duration" Type="System.Single" />
        <Parameter Name="gridSize" Type="Cocos2D.CCGridSize" />
        <Parameter Name="waves" Type="System.Int32" />
        <Parameter Name="amplitude" Type="System.Single" />
      </Parameters>
      <Docs>
        <param name="duration">To be added.</param>
        <param name="gridSize">To be added.</param>
        <param name="waves">To be added.</param>
        <param name="amplitude">To be added.</param>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Amplitude">
      <MemberSignature Language="C#" Value="public float Amplitude { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance float32 Amplitude" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.3.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Single</ReturnType>
      </ReturnValue>
      <Docs>
        waves amplitude
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="AmplitudeRate">
      <MemberSignature Language="C#" Value="public override float AmplitudeRate { get; set; }" />
      <MemberSignature Language="ILAsm" Value=".property instance float32 AmplitudeRate" />
      <MemberType>Property</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.3.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Single</ReturnType>
      </ReturnValue>
      <Docs>
        waves amplitude rate
        <value>To be added.</value>
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Copy">
      <MemberSignature Language="C#" Value="public override object Copy (Cocos2D.ICCCopyable pZone);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig virtual instance object Copy(class Cocos2D.ICCCopyable pZone) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.3.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Object</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="pZone" Type="Cocos2D.ICCCopyable" />
      </Parameters>
      <Docs>
        <param name="pZone">To be added.</param>
        returns a new clone of the action
        <returns>To be added.</returns>
        <remarks />
      </Docs>
    </Member>
    <Member MemberName="InitWithDuration">
      <MemberSignature Language="C#" Value="protected virtual bool InitWithDuration (float duration, Cocos2D.CCGridSize gridSize, int waves, float amplitude);" />
      <MemberSignature Language="ILAsm" Value=".method familyhidebysig newslot virtual instance bool InitWithDuration(float32 duration, valuetype Cocos2D.CCGridSize gridSize, int32 waves, float32 amplitude) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.3.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Boolean</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="duration" Type="System.Single" />
        <Parameter Name="gridSize" Type="Cocos2D.CCGridSize" />
        <Parameter Name="waves" Type="System.Int32" />
        <Parameter Name="amplitude" Type="System.Single" />
      </Parameters>
      <Docs>
        <param name="duration">To be added.</param>
        <param name="gridSize">To be added.</param>
        <param name="waves">To be added.</param>
        <param name="amplitude">To be added.</param>
        initializes the action with a number of waves, the waves amplitude, the grid size and the duration
        <returns>To be added.</returns>
        <remarks />
      </Docs>
    </Member>
    <Member MemberName="m_fAmplitude">
      <MemberSignature Language="C#" Value="protected float m_fAmplitude;" />
      <MemberSignature Language="ILAsm" Value=".field family float32 m_fAmplitude" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.3.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Single</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="m_fAmplitudeRate">
      <MemberSignature Language="C#" Value="protected float m_fAmplitudeRate;" />
      <MemberSignature Language="ILAsm" Value=".field family float32 m_fAmplitudeRate" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.3.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Single</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="m_nWaves">
      <MemberSignature Language="C#" Value="protected int m_nWaves;" />
      <MemberSignature Language="ILAsm" Value=".field family int32 m_nWaves" />
      <MemberType>Field</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.3.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Int32</ReturnType>
      </ReturnValue>
      <Docs>
        To be added.
        <remarks>To be added.</remarks>
      </Docs>
    </Member>
    <Member MemberName="Update">
      <MemberSignature Language="C#" Value="public override void Update (float time);" />
      <MemberSignature Language="ILAsm" Value=".method public hidebysig virtual instance void Update(float32 time) cil managed" />
      <MemberType>Method</MemberType>
      <AssemblyInfo>
        <AssemblyVersion>2.0.3.0</AssemblyVersion>
      </AssemblyInfo>
      <ReturnValue>
        <ReturnType>System.Void</ReturnType>
      </ReturnValue>
      <Parameters>
        <Parameter Name="time" Type="System.Single" />
      </Parameters>
      <Docs>
        <param name="time">To be added.</param>
        called once per frame. time a value between 0 and 1
        <remarks>
          <para>called once per frame. time a value between 0 and 1</para>
          <para>For example:<list type="bullet" /></para>
          <list type="bullet" />
          <item>
            <description>0 means that the action just started</description>
          </item>
          <description>0 means that the action just started</description>
          <item>
            <description>0.5 means that the action is in the middle</description>
          </item>
          <description>0.5 means that the action is in the middle</description>
          <item>
            <description>1 means that the action is over </description>
          </item>
          <description>1 means that the action is over </description>
        </remarks>
      </Docs>
    </Member>
  </Members>
</Type>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Home</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Home

Async Connection Core

An async, call-and-message oriented protocol

This package implements the core functionality used by asynconnection

Docs

All public methods are described in the generated docs

Home

Classes

Call

Connection

Context

Message

Peer

Events

close

connect

error

frame

close

connect

error

Global

checkHash

    Documentation generated by JSDoc 3.5.5 on Mon Nov 27 2017 16:15:03 GMT-0200 (Horário brasileiro de verão)


text:
package org.ripple.power.ui.projector.action.sprite.effect;

import org.ripple.power.ui.graphics.LGraphics;

public interface IKernel {

	public void draw(LGraphics g);

	public void move();

}


text:
package org.teavm.runtime;

import org.teavm.interop.Structure;

class FreeChunkHolder extends Structure {
    FreeChunk value;
}


text:
<?php

// File generated from our OpenAPI spec

namespace Stripe\Service\Issuing;

/**
 * Service factory class for API resources in the Issuing namespace.
 *
 * @property AuthorizationService $authorizations
 * @property CardholderService $cardholders
 * @property CardService $cards
 * @property DisputeService $disputes
 * @property TransactionService $transactions
 */
class IssuingServiceFactory extends \Stripe\Service\AbstractServiceFactory
{
    /**
     * @var array<string, string>
     */
    private static $classMap = [
        'authorizations' => AuthorizationService::class,
        'cardholders' => CardholderService::class,
        'cards' => CardService::class,
        'disputes' => DisputeService::class,
        'transactions' => TransactionService::class,
    ];

    protected function getServiceClass($name)
    {
        return \array_key_exists($name, self::$classMap) ? self::$classMap[$name] : null;
    }
}


text:
using SamlOida.Model;
using System.Xml;

namespace SamlOida.MessageHandler.Parser
{
    public class LogoutResponseParser : SamlMessageParserBase<SamlLogoutResponseMessage>
    {
        protected override string RootElementName => "LogoutResponse";

        protected override SamlLogoutResponseMessage ParseInternal(XmlNode logoutResponseNode, SamlLogoutResponseMessage result, SamlOptions options)
        {
            var statusCodeNode = logoutResponseNode.SelectSingleNode($"{SamlAuthenticationDefaults.SamlProtocolNsPrefix}:Status/{SamlAuthenticationDefaults.SamlProtocolNsPrefix}:StatusCode/@Value", SamlXmlExtensions.NamespaceManager);
            if (statusCodeNode == null)
                throw new ParsingException("Node 'StatusCode' missing.");

            result.Success = statusCodeNode.Value == "urn:oasis:names:tc:SAML:2.0:status:Success";

            result.InResponseTo = logoutResponseNode.Attributes["InResponseTo"]?.Value;

            return result;
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Trans. Br. mycol. Soc. 81(3): 641 (1983)

#### Original name
Glomus multisubstensum Mukerji, Bhattacharjee & J.P. Tewari

### Remarks
null


text:
package org.locationtech.geomesa.api;

import org.apache.hadoop.classification.InterfaceStability;

@InterfaceStability.Unstable
public enum IndexType {
    SPATIAL,
    SPATIOTEMPORAL,
    RECORD
}


text:
package in.mused.api.util;

import java.lang.reflect.Type;

import org.bson.types.ObjectId;

import flexjson.ObjectBinder;
import flexjson.ObjectFactory;
import flexjson.transformer.AbstractTransformer;
import flexjson.transformer.DateTransformer;

public class ObjectIdTransformer extends AbstractTransformer implements ObjectFactory{

    public void transform(Object object) {
        getContext().writeQuoted(object.toString());
    }

	public Object instantiate(ObjectBinder context, Object value, Type targetType, Class targetClass) {
		return new ObjectId(value.toString());
	}

}


text:
    <jqxGrid
        [width]="850" [source]="dataAdapter" [columns]="columns" [columnsresize]="true">
    </jqxGrid>


text:
<?php

namespace MwBundle\Repository;

use AppBundle\Repository\DoelstellingRepositoryInterface;
use AppBundle\Repository\DoelstellingRepositoryTrait;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Metadata\ClassMetadata;
use MwBundle\Entity\Info;
use MwBundle\Entity\Verslag;

class KlantInfoRepository extends EntityRepository implements DoelstellingRepositoryInterface
{
    use DoelstellingRepositoryTrait;

    public $economischDaklozenLocaties;

    public function setEconomischDaklozenLocaties($locaties)
    {
        $this->economischDaklozenLocaties = $locaties;
    }

    public function getCategory(): string
    {
        return DoelstellingRepositoryInterface::CAT_HULPVERLENING;
    }

    public function initDoelstellingcijfers(): void
    {
        $economischDaklozenLocatiesStr = implode(", ",$this->economischDaklozenLocaties);
        $this->addDoelstellingcijfer(
            "Aantal clienten dat een verslag heeft dat is vastgelegd in de periode, die een RIS beschikking heeft die nog loopt in de periode, vanaf de locaties '$economischDaklozenLocatiesStr'.",
            "4160",
            "Ambulante ondersteuning",
            function($doelstelling,$startdatum,$einddatum){
                $r = $this->getAantalRisClientenLocaties($startdatum,$einddatum,$this->economischDaklozenLocaties);
                return $r;
            }
        );

    }

    private function getAantalRisClientenLocaties($startdatum,$einddatum,$locaties)
    {

        $builder = $this->createQueryBuilder("info");

        $builder->select("COUNT(DISTINCT klant.id) AS aantalKlanten")
            ->innerJoin("info.klant","klant")
            ->innerJoin("klant.verslagen","verslag")
            ->innerJoin("verslag.locatie","locatie")
            ->andWhere("info.risDatumTot IS NOT NULL")
            ->andWhere("DATE(info.risDatumTot) > :startdatum")
            ->andWhere("verslag.type = :mw_verslagType")
            ->andWhere("DATE(verslag.datum) BETWEEN :startdatum AND :einddatum")
            ->andWhere("locatie.naam IN (:locatieNamen)")
            ->setParameter("mw_verslagType",Verslag::TYPE_MW)
            ->setParameter("startdatum",$startdatum)
            ->setParameter("einddatum",$einddatum)
            ->setParameter("locatieNamen",$locaties)
        ;

        $query = $builder->getQuery();
        $sql = $query->getSQL();
        $parameters = $query->getParameters();
        $result = $query->getSingleScalarResult();
        return $result;
    }
}


text:
namespace evpp {

InvokeTimer::InvokeTimer(EventLoop* evloop, Duration timeout, const Functor& f, bool periodic)
    : loop_(evloop), timeout_(timeout), functor_(f), periodic_(periodic) {
    DLOG_TRACE << "loop=" << loop_;
}

InvokeTimer::InvokeTimer(EventLoop* evloop, Duration timeout, Functor&& f, bool periodic)
    : loop_(evloop), timeout_(timeout), functor_(std::move(f)), periodic_(periodic) {
    DLOG_TRACE << "loop=" << loop_;
}

InvokeTimerPtr InvokeTimer::Create(EventLoop* evloop, Duration timeout, const Functor& f, bool periodic) {
    InvokeTimerPtr it(new InvokeTimer(evloop, timeout, f, periodic));
    it->self_ = it;
    return it;
}

InvokeTimerPtr InvokeTimer::Create(EventLoop* evloop, Duration timeout, Functor&& f, bool periodic) {
    InvokeTimerPtr it(new InvokeTimer(evloop, timeout, std::move(f), periodic));
    it->self_ = it;
    return it;
}

InvokeTimer::~InvokeTimer() {
    DLOG_TRACE << "loop=" << loop_;
}

void InvokeTimer::Start() {
    DLOG_TRACE << "loop=" << loop_ << " refcount=" << self_.use_count();
    auto f = [this]() {
        timer_.reset(new TimerEventWatcher(loop_, [time_weak = std::weak_ptr<InvokeTimer>(shared_from_this())]() {
            auto time_ptr = time_weak.lock();
            if (time_ptr) {
                time_ptr->OnTimerTriggered();
            }
        }, timeout_));

        timer_->SetCancelCallback([time_weak = std::weak_ptr<InvokeTimer>(shared_from_this())]() {
            auto time_ptr = time_weak.lock();
            if (time_ptr) {
                time_ptr->OnCanceled();
            }
        });
        timer_->Init();
        timer_->AsyncWait();
        DLOG_TRACE << "timer=" << timer_.get() << " loop=" << loop_ << " refcount=" << self_.use_count() << " periodic=" << periodic_ << " timeout(ms)=" << timeout_.Milliseconds();
    };
    loop_->RunInLoop(std::move(f));
}

void InvokeTimer::Cancel() {
    DLOG_TRACE;
    auto f = [time_weak = std::weak_ptr<InvokeTimer>(shared_from_this())]() {
        auto time_ptr = time_weak.lock();
        if (time_ptr && time_ptr->timer_) {
            time_ptr->timer_->Cancel();
        }
    };
    loop_->RunInLoop(std::move(f));
}

void InvokeTimer::OnTimerTriggered() {
    DLOG_TRACE << "loop=" << loop_ << " use_count=" << self_.use_count();
    functor_();

    if (periodic_) {
        timer_->AsyncWait();
    } else {
        timer_.reset();
        self_.reset();
    }
}

void InvokeTimer::OnCanceled() {
    DLOG_TRACE << "loop=" << loop_ << " use_count=" << self_.use_count();
    periodic_ = false;
    if (cancel_callback_) {
        cancel_callback_();
    }
    timer_.reset();
    self_.reset();
}

}


text:
import Ember from 'ember';
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';

const {
  Route
} = Ember;

export default Route.extend(ApplicationRouteMixin, {
  model() {
      return this.store.query('league-team', {leagueId: this.paramsFor('league').id});
  },
  setupController(controller, model) {
    controller.set('model', model);
  },
  actions: {
    removeTeam(team) {
      const flashMessages = Ember.get(this, 'flashMessages');

      return team.destroyRecord().then(() => {
        flashMessages.success(`${team.get('name')} has been removed from the league`);
      }).catch(() => {
        team.rollback();

        flashMessages.danger('Unable to remove team from the league');
      });
    }
  }
});


text:
namespace rx
{

class BufferGL : public BufferImpl
{
  public:
    BufferGL();
    ~BufferGL() override;

    gl::Error setData(const void* data, size_t size, GLenum usage) override;
    gl::Error setSubData(const void* data, size_t size, size_t offset) override;
    gl::Error copySubData(BufferImpl* source, GLintptr sourceOffset, GLintptr destOffset, GLsizeiptr size) override;
    gl::Error map(size_t offset, size_t length, GLbitfield access, GLvoid **mapPtr) override;
    gl::Error unmap() override;
    void markTransformFeedbackUsage() override;

    // This method may not have a corresponding GL-backed function. It is necessary
    // for validation, for certain indexed draw calls.
    gl::Error getData(const uint8_t **outData) override;

  private:
    DISALLOW_COPY_AND_ASSIGN(BufferGL);
};

}

#endif // LIBANGLE_RENDERER_GL_BUFFERGL_H_


text:
import psutil
import plugins

class Plugin(plugins.BasePlugin):
    __name__ = 'cpu_freq'

    def run(self, *unused):
        results = {}
        data = psutil.cpu_freq(percpu=True)
        cpu_number = -1
        for cpu in data:
            core = {}
            cpu_number = cpu_number+1
            results[cpu_number] = {}
            for key in cpu._fields:
                core[key] = getattr(cpu, key)
            results[cpu_number] = core['current']
        return results

if __name__ == '__main__':
    Plugin().execute()


text:
module Single
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def instance
      @instance ||= new
    end

    def method_missing(method_id, *args, &block)
      instance.send method_id, *args, &block
    end
  end
end


text:
namespace ceres {
namespace internal {

LinearSolver::~LinearSolver() {
}

LinearSolver* LinearSolver::Create(const LinearSolver::Options& options) {
  switch (options.type) {
    case CGNR:
      return new CgnrSolver(options);

    case SPARSE_NORMAL_CHOLESKY:
#ifndef CERES_NO_SUITESPARSE
      return new SparseNormalCholeskySolver(options);
#else
      LOG(WARNING) << "SPARSE_NORMAL_CHOLESKY is not available. Please "
                   << "build Ceres with SuiteSparse. Returning NULL.";
      return NULL;
#endif  // CERES_NO_SUITESPARSE

    case SPARSE_SCHUR:
#ifndef CERES_NO_SUITESPARSE
      return new SparseSchurComplementSolver(options);
#else
      LOG(WARNING) << "SPARSE_SCHUR is not available. Please "
                   << "build Ceres with SuiteSparse. Returning NULL.";
      return NULL;
#endif  // CERES_NO_SUITESPARSE

    case DENSE_SCHUR:
      return new DenseSchurComplementSolver(options);

    case ITERATIVE_SCHUR:
      return new IterativeSchurComplementSolver(options);

    case DENSE_QR:
      return new DenseQRSolver(options);

    default:
      LOG(FATAL) << "Unknown linear solver type :"
                 << options.type;
  }
}

}  // namespace internal
}  // namespace ceres


text:
namespace GrayStorm
{
    partial class grayStorm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(grayStorm));
            this.information_panel = new System.Windows.Forms.Panel();
            this.addrOfMethod_TB = new System.Windows.Forms.TextBox();
            this.addrOfMethod_L = new System.Windows.Forms.Label();
            this.selectedConstructor_TB = new System.Windows.Forms.TextBox();
            this.selectedMethod_TB = new System.Windows.Forms.TextBox();
            this.constructor_LB = new System.Windows.Forms.Label();
            this.methodSelected_LB = new System.Windows.Forms.Label();
            this.splitContainer2 = new System.Windows.Forms.SplitContainer();
            this.splitContainer1 = new System.Windows.Forms.SplitContainer();
            this.hierarchyViewer1 = new GrayStorm.hierarchyViewer();
            this.mainControl_TAB = new System.Windows.Forms.TabControl();
            this.tabPage1 = new System.Windows.Forms.TabPage();
            this.memoryHijacker1 = new GrayStorm.memoryHijacker();
            this.tabPage2 = new System.Windows.Forms.TabPage();
            this.shellcodeTAB = new GrayStorm.shellcode();
            this.tabPage3 = new System.Windows.Forms.TabPage();
            this.cSharpMethodWriter1 = new GrayStorm.cSharpMethodWriter();
            this.tabPage4 = new System.Windows.Forms.TabPage();
            this.methodEditor1 = new GrayStorm.GUI.MethodEditor();
            this.addrOfConstructor_TB = new System.Windows.Forms.TextBox();
            this.addrCon_L = new System.Windows.Forms.Label();
            this.information_panel.SuspendLayout();
            this.splitContainer2.Panel1.SuspendLayout();
            this.splitContainer2.Panel2.SuspendLayout();
            this.splitContainer2.SuspendLayout();
            this.splitContainer1.Panel1.SuspendLayout();
            this.splitContainer1.Panel2.SuspendLayout();
            this.splitContainer1.SuspendLayout();
            this.mainControl_TAB.SuspendLayout();
            this.tabPage1.SuspendLayout();
            this.tabPage2.SuspendLayout();
            this.tabPage3.SuspendLayout();
            this.tabPage4.SuspendLayout();
            this.SuspendLayout();
            //
            // information_panel
            //
            this.information_panel.Controls.Add(this.addrOfConstructor_TB);
            this.information_panel.Controls.Add(this.addrCon_L);
            this.information_panel.Controls.Add(this.addrOfMethod_TB);
            this.information_panel.Controls.Add(this.addrOfMethod_L);
            this.information_panel.Controls.Add(this.selectedConstructor_TB);
            this.information_panel.Controls.Add(this.selectedMethod_TB);
            this.information_panel.Controls.Add(this.constructor_LB);
            this.information_panel.Controls.Add(this.methodSelected_LB);
            this.information_panel.Dock = System.Windows.Forms.DockStyle.Fill;
            this.information_panel.Location = new System.Drawing.Point(0, 0);
            this.information_panel.Name = "information_panel";
            this.information_panel.Size = new System.Drawing.Size(845, 45);
            this.information_panel.TabIndex = 1;
            //
            // addrOfMethod_TB
            //
            this.addrOfMethod_TB.Location = new System.Drawing.Point(92, 22);
            this.addrOfMethod_TB.Name = "addrOfMethod_TB";
            this.addrOfMethod_TB.Size = new System.Drawing.Size(251, 20);
            this.addrOfMethod_TB.TabIndex = 6;
            this.addrOfMethod_TB.Text = "Address of Method";
            //
            // addrOfMethod_L
            //
            this.addrOfMethod_L.AutoSize = true;
            this.addrOfMethod_L.Location = new System.Drawing.Point(3, 24);
            this.addrOfMethod_L.Name = "addrOfMethod_L";
            this.addrOfMethod_L.Size = new System.Drawing.Size(83, 13);
            this.addrOfMethod_L.TabIndex = 5;
            this.addrOfMethod_L.Text = "Addr of Method:";
            //
            // selectedConstructor_TB
            //
            this.selectedConstructor_TB.Location = new System.Drawing.Point(467, 1);
            this.selectedConstructor_TB.Name = "selectedConstructor_TB";
            this.selectedConstructor_TB.Size = new System.Drawing.Size(253, 20);
            this.selectedConstructor_TB.TabIndex = 4;
            //
            // selectedMethod_TB
            //
            this.selectedMethod_TB.Location = new System.Drawing.Point(90, 0);
            this.selectedMethod_TB.Name = "selectedMethod_TB";
            this.selectedMethod_TB.Size = new System.Drawing.Size(253, 20);
            this.selectedMethod_TB.TabIndex = 3;
            //
            // constructor_LB
            //
            this.constructor_LB.AutoSize = true;
            this.constructor_LB.Location = new System.Drawing.Point(349, 0);
            this.constructor_LB.Name = "constructor_LB";
            this.constructor_LB.Size = new System.Drawing.Size(112, 13);
            this.constructor_LB.TabIndex = 2;
            this.constructor_LB.Text = "Constructor Selected: ";
            //
            // methodSelected_LB
            //
            this.methodSelected_LB.AutoSize = true;
            this.methodSelected_LB.Location = new System.Drawing.Point(3, 4);
            this.methodSelected_LB.Name = "methodSelected_LB";
            this.methodSelected_LB.Size = new System.Drawing.Size(94, 13);
            this.methodSelected_LB.TabIndex = 0;
            this.methodSelected_LB.Text = "Method Selected: ";
            //
            // splitContainer2
            //
            this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainer2.Location = new System.Drawing.Point(0, 0);
            this.splitContainer2.Name = "splitContainer2";
            this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
            //
            // splitContainer2.Panel1
            //
            this.splitContainer2.Panel1.Controls.Add(this.information_panel);
            //
            // splitContainer2.Panel2
            //
            this.splitContainer2.Panel2.Controls.Add(this.splitContainer1);
            this.splitContainer2.Size = new System.Drawing.Size(845, 503);
            this.splitContainer2.SplitterDistance = 45;
            this.splitContainer2.TabIndex = 1;
            //
            // splitContainer1
            //
            this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.splitContainer1.Location = new System.Drawing.Point(0, 0);
            this.splitContainer1.Name = "splitContainer1";
            //
            // splitContainer1.Panel1
            //
            this.splitContainer1.Panel1.Controls.Add(this.hierarchyViewer1);
            //
            // splitContainer1.Panel2
            //
            this.splitContainer1.Panel2.Controls.Add(this.mainControl_TAB);
            this.splitContainer1.Size = new System.Drawing.Size(845, 454);
            this.splitContainer1.SplitterDistance = 279;
            this.splitContainer1.TabIndex = 0;
            //
            // hierarchyViewer1
            //
            this.hierarchyViewer1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.hierarchyViewer1.Location = new System.Drawing.Point(0, 0);
            this.hierarchyViewer1.Name = "hierarchyViewer1";
            this.hierarchyViewer1.Size = new System.Drawing.Size(279, 454);
            this.hierarchyViewer1.TabIndex = 0;
            //
            // mainControl_TAB
            //
            this.mainControl_TAB.Controls.Add(this.tabPage1);
            this.mainControl_TAB.Controls.Add(this.tabPage2);
            this.mainControl_TAB.Controls.Add(this.tabPage3);
            this.mainControl_TAB.Controls.Add(this.tabPage4);
            this.mainControl_TAB.Dock = System.Windows.Forms.DockStyle.Fill;
            this.mainControl_TAB.Location = new System.Drawing.Point(0, 0);
            this.mainControl_TAB.Name = "mainControl_TAB";
            this.mainControl_TAB.SelectedIndex = 0;
            this.mainControl_TAB.Size = new System.Drawing.Size(562, 454);
            this.mainControl_TAB.TabIndex = 0;
            //
            // tabPage1
            //
            this.tabPage1.Controls.Add(this.memoryHijacker1);
            this.tabPage1.Location = new System.Drawing.Point(4, 22);
            this.tabPage1.Name = "tabPage1";
            this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
            this.tabPage1.Size = new System.Drawing.Size(554, 428);
            this.tabPage1.TabIndex = 0;
            this.tabPage1.Text = "Memory Hijacker";
            this.tabPage1.UseVisualStyleBackColor = true;
            //
            // memoryHijacker1
            //
            this.memoryHijacker1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.memoryHijacker1.Location = new System.Drawing.Point(3, 3);
            this.memoryHijacker1.Name = "memoryHijacker1";
            this.memoryHijacker1.Size = new System.Drawing.Size(548, 422);
            this.memoryHijacker1.TabIndex = 0;
            //
            // tabPage2
            //
            this.tabPage2.Controls.Add(this.shellcodeTAB);
            this.tabPage2.Location = new System.Drawing.Point(4, 22);
            this.tabPage2.Name = "tabPage2";
            this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
            this.tabPage2.Size = new System.Drawing.Size(554, 428);
            this.tabPage2.TabIndex = 1;
            this.tabPage2.Text = "Shellcode";
            this.tabPage2.UseVisualStyleBackColor = true;
            //
            // shellcodeTAB
            //
            this.shellcodeTAB.Dock = System.Windows.Forms.DockStyle.Fill;
            this.shellcodeTAB.Location = new System.Drawing.Point(3, 3);
            this.shellcodeTAB.Name = "shellcodeTAB";
            this.shellcodeTAB.Size = new System.Drawing.Size(548, 422);
            this.shellcodeTAB.TabIndex = 0;
            //
            // tabPage3
            //
            this.tabPage3.Controls.Add(this.cSharpMethodWriter1);
            this.tabPage3.Location = new System.Drawing.Point(4, 22);
            this.tabPage3.Name = "tabPage3";
            this.tabPage3.Size = new System.Drawing.Size(554, 428);
            this.tabPage3.TabIndex = 2;
            this.tabPage3.Text = "Dynamic C#";
            this.tabPage3.UseVisualStyleBackColor = true;
            //
            // cSharpMethodWriter1
            //
            this.cSharpMethodWriter1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.cSharpMethodWriter1.Location = new System.Drawing.Point(0, 0);
            this.cSharpMethodWriter1.Name = "cSharpMethodWriter1";
            this.cSharpMethodWriter1.Size = new System.Drawing.Size(554, 428);
            this.cSharpMethodWriter1.TabIndex = 0;
            //
            // tabPage4
            //
            this.tabPage4.Controls.Add(this.methodEditor1);
            this.tabPage4.Location = new System.Drawing.Point(4, 22);
            this.tabPage4.Name = "tabPage4";
            this.tabPage4.Size = new System.Drawing.Size(554, 428);
            this.tabPage4.TabIndex = 3;
            this.tabPage4.Text = "Method Editor";
            this.tabPage4.UseVisualStyleBackColor = true;
            //
            // methodEditor1
            //
            this.methodEditor1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.methodEditor1.Location = new System.Drawing.Point(0, 0);
            this.methodEditor1.Name = "methodEditor1";
            this.methodEditor1.Size = new System.Drawing.Size(554, 428);
            this.methodEditor1.TabIndex = 0;
            //
            // addrOfConstructor_TB
            //
            this.addrOfConstructor_TB.Location = new System.Drawing.Point(467, 23);
            this.addrOfConstructor_TB.Name = "addrOfConstructor_TB";
            this.addrOfConstructor_TB.Size = new System.Drawing.Size(251, 20);
            this.addrOfConstructor_TB.TabIndex = 8;
            this.addrOfConstructor_TB.Text = "Addr of Constructor";
            //
            // addrCon_L
            //
            this.addrCon_L.AutoSize = true;
            this.addrCon_L.Location = new System.Drawing.Point(363, 24);
            this.addrCon_L.Name = "addrCon_L";
            this.addrCon_L.Size = new System.Drawing.Size(101, 13);
            this.addrCon_L.TabIndex = 7;
            this.addrCon_L.Text = "Addr of Constructor:";
            //
            // grayStorm
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(845, 503);
            this.Controls.Add(this.splitContainer2);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "grayStorm";
            this.Text = "Gray Storm";
            this.information_panel.ResumeLayout(false);
            this.information_panel.PerformLayout();
            this.splitContainer2.Panel1.ResumeLayout(false);
            this.splitContainer2.Panel2.ResumeLayout(false);
            this.splitContainer2.ResumeLayout(false);
            this.splitContainer1.Panel1.ResumeLayout(false);
            this.splitContainer1.Panel2.ResumeLayout(false);
            this.splitContainer1.ResumeLayout(false);
            this.mainControl_TAB.ResumeLayout(false);
            this.tabPage1.ResumeLayout(false);
            this.tabPage2.ResumeLayout(false);
            this.tabPage3.ResumeLayout(false);
            this.tabPage4.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.SplitContainer splitContainer1;
        private hierarchyViewer hierarchyViewer1;
        private System.Windows.Forms.TabControl mainControl_TAB;
        private System.Windows.Forms.TabPage tabPage1;
        private System.Windows.Forms.TabPage tabPage2;
        private GrayStorm.shellcode shellcodeTAB;
        private System.Windows.Forms.Panel information_panel;
        private System.Windows.Forms.SplitContainer splitContainer2;
        private System.Windows.Forms.Label methodSelected_LB;
        private System.Windows.Forms.Label constructor_LB;
        private memoryHijacker memoryHijacker1;
        private System.Windows.Forms.TextBox selectedConstructor_TB;
        private System.Windows.Forms.TextBox selectedMethod_TB;
        private System.Windows.Forms.TabPage tabPage3;
        private cSharpMethodWriter cSharpMethodWriter1;
        private System.Windows.Forms.TabPage tabPage4;
        private GUI.MethodEditor methodEditor1;
        private System.Windows.Forms.Label addrOfMethod_L;
        private System.Windows.Forms.TextBox addrOfMethod_TB;
        private System.Windows.Forms.TextBox addrOfConstructor_TB;
        private System.Windows.Forms.Label addrCon_L;
    }
}