text:
//! # Schemes
//! A scheme is a primitive for handling filesystem syscalls in Redox.
//! Schemes accept paths from the kernel for `open`, and file descriptors that they generate
//! are then passed for operations like `close`, `read`, `write`, etc.
//!
//! The kernel validates paths and file descriptors before they are passed to schemes,
//! also stripping the scheme identifier of paths if necessary.

use alloc::{
    boxed::Box,
    collections::BTreeMap,
    string::ToString,
    sync::Arc,
    vec::Vec,
};
use core::sync::atomic::AtomicUsize;
use spin::{Once, RwLock, RwLockReadGuard, RwLockWriteGuard};

use crate::context::{memory::AddrSpace, file::FileDescriptor};
use crate::syscall::error::*;
use crate::syscall::scheme::Scheme;

#[cfg(all(feature = "acpi", any(target_arch = "x86", target_arch = "x86_64")))]
use self::acpi::AcpiScheme;

use self::debug::DebugScheme;
use self::event::EventScheme;
use self::irq::IrqScheme;
use self::itimer::ITimerScheme;
use self::memory::MemoryScheme;
use self::pipe::PipeScheme;
use self::proc::ProcScheme;
use self::root::RootScheme;
use self::serio::SerioScheme;
use self::sys::SysScheme;
use self::time::TimeScheme;

/// When compiled with the "acpi" feature - `acpi:` - allows drivers to read a limited set of ACPI tables.
#[cfg(all(feature = "acpi", any(target_arch = "x86", target_arch = "x86_64")))]
pub mod acpi;

/// `debug:` - provides access to serial console
pub mod debug;

/// `event:` - allows reading of `Event`s which are registered using `fevent`
pub mod event;

/// `irq:` - allows userspace handling of IRQs
pub mod irq;

/// `itimer:` - support for getitimer and setitimer
pub mod itimer;

/// When `disk/live:` - embedded filesystem for live disk
pub mod live;

/// `memory:` - a scheme for accessing physical memory
pub mod memory;

/// `pipe:` - used internally by the kernel to implement `pipe`
pub mod pipe;

/// `proc:` - allows tracing processes and reading/writing their memory
pub mod proc;

/// `:` - allows the creation of userspace schemes, tightly dependent on `user`
pub mod root;

/// `serio:` - provides access to ps/2 devices
pub mod serio;

/// `sys:` - system information, such as the context list and scheme list
pub mod sys;

/// `time:` - allows reading time, setting timeouts and getting events when they are met
pub mod time;

/// A wrapper around userspace schemes, tightly dependent on `root`
pub mod user;

/// Limit on number of schemes
pub const SCHEME_MAX_SCHEMES: usize = 65_536;

// Unique identifier for a scheme namespace.
int_like!(SchemeNamespace, AtomicSchemeNamespace, usize, AtomicUsize);

// Unique identifier for a scheme.
int_like!(SchemeId, AtomicSchemeId, usize, AtomicUsize);

// Unique identifier for a file descriptor.
int_like!(FileHandle, AtomicFileHandle, usize, AtomicUsize);

pub struct SchemeIter<'a> {
    inner: Option<::alloc::collections::btree_map::Iter<'a, Box<str>, SchemeId>>
}

impl<'a> Iterator for SchemeIter<'a> {
    type Item = (&'a Box<str>, &'a SchemeId);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.as_mut().and_then(|iter| iter.next())
    }
}

/// Scheme list type
pub struct SchemeList {
    map: BTreeMap<SchemeId, Arc<dyn KernelScheme + Send + Sync>>,
    names: BTreeMap<SchemeNamespace, BTreeMap<Box<str>, SchemeId>>,
    next_ns: usize,
    next_id: usize
}

impl SchemeList {
    /// Create a new scheme list.
    pub fn new() -> Self {
        let mut list = SchemeList {
            map: BTreeMap::new(),
            names: BTreeMap::new(),
            // Scheme namespaces always start at 1. 0 is a reserved namespace, the null namespace
            next_ns: 1,
            next_id: 1
        };
        list.new_null();
        list.new_root();
        list
    }

    /// Initialize the null namespace
    fn new_null(&mut self) {
        let ns = SchemeNamespace(0);
        self.names.insert(ns, BTreeMap::new());

        //TODO: Only memory: is in the null namespace right now. It should be removed when
        //anonymous mmap's are implemented
        self.insert(ns, "memory", |_| Arc::new(MemoryScheme::new())).unwrap();
        self.insert(ns, "thisproc", |_| Arc::new(ProcScheme::restricted())).unwrap();
    }

    /// Initialize a new namespace
    fn new_ns(&mut self) -> SchemeNamespace {
        let ns = SchemeNamespace(self.next_ns);
        self.next_ns += 1;
        self.names.insert(ns, BTreeMap::new());

        self.insert(ns, "", |scheme_id| Arc::new(RootScheme::new(ns, scheme_id))).unwrap();
        self.insert(ns, "event", |_| Arc::new(EventScheme)).unwrap();
        self.insert(ns, "itimer", |_| Arc::new(ITimerScheme::new())).unwrap();
        self.insert(ns, "memory", |_| Arc::new(MemoryScheme::new())).unwrap();
        self.insert(ns, "sys", |_| Arc::new(SysScheme::new())).unwrap();
        self.insert(ns, "time", |scheme_id| Arc::new(TimeScheme::new(scheme_id))).unwrap();

        ns
    }

    /// Initialize the root namespace
    fn new_root(&mut self) {
        // Do common namespace initialization
        let ns = self.new_ns();

        // These schemes should only be available on the root
        #[cfg(all(feature = "acpi", any(target_arch = "x86", target_arch = "x86_64")))] {
            self.insert(ns, "kernel/acpi", |scheme_id| Arc::new(AcpiScheme::new(scheme_id))).unwrap();
        }
        self.insert(ns, "debug", |scheme_id| Arc::new(DebugScheme::new(scheme_id))).unwrap();
        self.insert(ns, "irq", |scheme_id| Arc::new(IrqScheme::new(scheme_id))).unwrap();
        self.insert(ns, "proc", |scheme_id| Arc::new(ProcScheme::new(scheme_id))).unwrap();
        self.insert(ns, "thisproc", |_| Arc::new(ProcScheme::restricted())).unwrap();
        self.insert(ns, "serio", |scheme_id| Arc::new(SerioScheme::new(scheme_id))).unwrap();

        if let Some(scheme) = self::live::DiskScheme::new().map(Arc::new) {
            self.insert(ns, "disk/live", move |_| scheme.clone()).unwrap();
        }

        // Pipe is special and needs to be in the root namespace
        self.insert(ns, "pipe", |scheme_id| Arc::new(PipeScheme::new(scheme_id))).unwrap();
    }

    pub fn make_ns(&mut self, from: SchemeNamespace, names: &[&str]) -> Result<SchemeNamespace> {
        // Create an empty namespace
        let to = self.new_ns();

        // Copy requested scheme IDs
        for name in names.iter() {
            let id = if let Some((id, _scheme)) = self.get_name(from, name) {
                id
            } else {
                return Err(Error::new(ENODEV));
            };

            if let Some(ref mut names) = self.names.get_mut(&to) {
                assert!(names.insert(name.to_string().into_boxed_str(), id).is_none());
            } else {
                panic!("scheme namespace not found");
            }
        }

        Ok(to)
    }

    pub fn iter(&self) -> ::alloc::collections::btree_map::Iter<SchemeId, Arc<dyn KernelScheme + Send + Sync>> {
        self.map.iter()
    }

    pub fn iter_name(&self, ns: SchemeNamespace) -> SchemeIter {
        SchemeIter {
            inner: self.names.get(&ns).map(|names| names.iter())
        }
    }

    /// Get the nth scheme.
    pub fn get(&self, id: SchemeId) -> Option<&Arc<dyn KernelScheme + Send + Sync>> {
        self.map.get(&id)
    }

    pub fn get_name(&self, ns: SchemeNamespace, name: &str) -> Option<(SchemeId, &Arc<dyn KernelScheme + Send + Sync>)> {
        if let Some(names) = self.names.get(&ns) {
            if let Some(&id) = names.get(name) {
                return self.get(id).map(|scheme| (id, scheme));
            }
        }
        None
    }

    /// Create a new scheme.
    pub fn insert<F>(&mut self, ns: SchemeNamespace, name: &str, scheme_fn: F) -> Result<SchemeId>
        where F: Fn(SchemeId) -> Arc<dyn KernelScheme + Send + Sync>
    {
        if let Some(names) = self.names.get(&ns) {
            if names.contains_key(name) {
                return Err(Error::new(EEXIST));
            }
        }

        if self.next_id >= SCHEME_MAX_SCHEMES {
            self.next_id = 1;
        }

        while self.map.contains_key(&SchemeId(self.next_id)) {
            self.next_id += 1;
        }

        /* Allow scheme list to grow if required
        if self.next_id >= SCHEME_MAX_SCHEMES {
            return Err(Error::new(EAGAIN));
        }
        */

        let id = SchemeId(self.next_id);
        self.next_id += 1;

        let scheme = scheme_fn(id);

        assert!(self.map.insert(id, scheme).is_none());
        if let Some(ref mut names) = self.names.get_mut(&ns) {
            assert!(names.insert(name.to_string().into_boxed_str(), id).is_none());
        } else {
            // Nonexistent namespace, posssibly null namespace
            return Err(Error::new(ENODEV));
        }
        Ok(id)
    }

    /// Remove a scheme
    pub fn remove(&mut self, id: SchemeId) {
        assert!(self.map.remove(&id).is_some());
        for (_ns, names) in self.names.iter_mut() {
            let mut remove = Vec::with_capacity(1);
            for (name, name_id) in names.iter() {
                if name_id == &id {
                    remove.push(name.clone());
                }
            }
            for name in remove {
                assert!(names.remove(&name).is_some());
            }
        }
    }
}

/// Schemes list
static SCHEMES: Once<RwLock<SchemeList>> = Once::new();

/// Initialize schemes, called if needed
fn init_schemes() -> RwLock<SchemeList> {
    RwLock::new(SchemeList::new())
}

/// Get the global schemes list, const
pub fn schemes() -> RwLockReadGuard<'static, SchemeList> {
    SCHEMES.call_once(init_schemes).read()
}

/// Get the global schemes list, mutable
pub fn schemes_mut() -> RwLockWriteGuard<'static, SchemeList> {
    SCHEMES.call_once(init_schemes).write()
}

#[allow(unused_variables)]
pub trait KernelScheme: Scheme + Send + Sync + 'static {
    fn as_filetable(&self, number: usize) -> Result<Arc<RwLock<Vec<Option<FileDescriptor>>>>> {
        Err(Error::new(EBADF))
    }
    fn as_addrspace(&self, number: usize) -> Result<Arc<RwLock<AddrSpace>>> {
        Err(Error::new(EBADF))
    }
    fn as_sigactions(&self, number: usize) -> Result<Arc<RwLock<Vec<(crate::syscall::data::SigAction, usize)>>>> {
        Err(Error::new(EBADF))
    }

    fn kfmap(&self, number: usize, addr_space: &Arc<RwLock<AddrSpace>>, map: &crate::syscall::data::Map, consume: bool) -> Result<usize> {
        Err(Error::new(EOPNOTSUPP))
    }
}


text:
package server;

import org.apache.log4j.Logger;
import server.thread.ConnectionAccepter;

import javax.net.ServerSocketFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.Collection;

/**
 * Created by pborges on 1/22/2015.
 */
public class HttpServer<CONNECTION extends Connection> {
	private Logger log = Logger.getLogger(HttpServer.class);
	private ConnectionAccepter<CONNECTION> webSocketAccepter;
	private ServerSocket serverSocket;
	private ConnectionManager<CONNECTION> connectionManager;
	private Boolean started = false;

	public HttpServer(ConnectionManager<CONNECTION> connectionManager, int port, int backlog, String address) throws IOException {
		log.debug("HttpServer(" + port + ", " + backlog + ", " + address + ")");
		ServerSocketFactory serverSocketFactory = ServerSocketFactory.getDefault();
		serverSocket = serverSocketFactory.createServerSocket(port, backlog, InetAddress.getByName(address));
		this.connectionManager = connectionManager;
		webSocketAccepter = new ConnectionAccepter<>(serverSocket, connectionManager.getConnectionFactory(), connectionManager);
	}

	public void start() {
		if (started)
			return;
		started = true;
		webSocketAccepter.start();
	}

	public ConnectionManager<CONNECTION> getConnectionManager() {
		return connectionManager;
	}

	public void broadcastMessage(String message) throws IOException {
		broadcastMessage(message, connectionManager.getOpenConnections());
	}

	public void broadcastMessage(String message, Collection<CONNECTION> connections) throws IOException {
		for (Connection connection : connections) {
			if (!connection.isClosed()) {
				connection.sendText(message);
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Dropbox;

// The Dropbox SDK autoloader.  You probably shouldn't be using this.  Instead,
// use a global autoloader, like the Composer autoloader.
//
// But if you really don't want to use a global autoloader, do this:
//
//     require_once "<path-to-here>/Dropbox/autoload.php"

/**
 * @internal
 */
function autoload($name)
{
    // If the name doesn't start with "Dropbox\", then its not once of our classes.
    if (\substr_compare($name, "Dropbox\\", 0, 8) !== 0) return;

    // Take the "Dropbox\" prefix off.
    $stem = \substr($name, 8);

    // Convert "\" and "_" to path separators.
    $pathified_stem = \str_replace(array("\\", "_"), '/', $stem);

    $path = __DIR__ . "/" . $pathified_stem . ".php";
    if (\is_file($path)) {
		//echo $path.'<br />';
        require_once $path;
    }
}

\spl_autoload_register('Dropbox\autoload');


text:
package consul

import (
	"time"

	"github.com/hashicorp/consul/api"
	"github.com/stretchr/testify/mock"
)

// resekClientFactory resets the global singleton factory function
// to its original value.  This function is handy as a defer for tests.
func resetClientFactory() {
	clientFactory = defaultClientFactory
}

// prepareMockClientFactory creates a new mockClientFactory and sets up this package
// to use it.
func prepareMockClientFactory() *mockClientFactory {
	m := new(mockClientFactory)
	clientFactory = m.NewClient
	return m
}

type mockClientFactory struct {
	mock.Mock
}

func (m *mockClientFactory) NewClient(c *api.Client) (Client, ttlUpdater) {
	arguments := m.Called(c)
	return arguments.Get(0).(Client),
		arguments.Get(1).(ttlUpdater)
}

func resetTickerFactory() {
	tickerFactory = defaultTickerFactory
}

func prepareMockTickerFactory() *mockTickerFactory {
	m := new(mockTickerFactory)
	tickerFactory = m.NewTicker
	return m
}

type mockTickerFactory struct {
	mock.Mock
}

func (m *mockTickerFactory) NewTicker(d time.Duration) (<-chan time.Time, func()) {
	arguments := m.Called(d)
	return arguments.Get(0).(<-chan time.Time), arguments.Get(1).(func())
}

type mockClient struct {
	mock.Mock
}

var _ Client = (*mockClient)(nil)

func (m *mockClient) Register(r *api.AgentServiceRegistration) error {
	return m.Called(r).Error(0)
}

func (m *mockClient) Deregister(r *api.AgentServiceRegistration) error {
	return m.Called(r).Error(0)
}

func (m *mockClient) Service(service, tag string, passingOnly bool, queryOpts *api.QueryOptions) ([]*api.ServiceEntry, *api.QueryMeta, error) {
	var (
		arguments = m.Called(service, tag, passingOnly, queryOpts)
		first, _  = arguments.Get(0).([]*api.ServiceEntry)
		second, _ = arguments.Get(1).(*api.QueryMeta)
	)

	return first, second, arguments.Error(2)
}

func (m *mockClient) Datacenters() ([]string, error) {
	arguments := m.Called()
	first, _ := arguments.Get(0).([]string)
	return first, arguments.Error(1)
}

type mockTTLUpdater struct {
	mock.Mock
}

func (m *mockTTLUpdater) UpdateTTL(checkID, output, status string) error {
	return m.Called(checkID, output, status).Error(0)
}


text:
var Rune = require('../RuneVM');

exports.execute = function (rune, state) {
    var modifyHealth = {
        "runeType":"ModifyHealth",
        "source":rune.source,
        "target":rune.target,
        //we flip this around because we deal a positive amount of damage, which is a negative change in health
        "amount":(rune.amount * -1)
    }
    Rune.executeRune(modifyHealth, state);
}

exports.CreateRune = function (sourceGuid, targetGuid, amount) {

    var rune = {
        "runeType":"DamageRune",
        "source":sourceGuid,
        "target":targetGuid,
        "amount":amount
    }
    return rune;
}

exports.canSee = function (rune, controller, state) {
    return true;
}


text:
<?php

namespace Dwf\PronosticsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Event
 *
 * @ORM\Table("events")
 * @ORM\Entity(repositoryClass="Dwf\PronosticsBundle\Entity\EventRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Event
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     * @var boolean
     *
     * @ORM\Column(name="nationalTeams", type="boolean")
     */
    private $nationalTeams;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="startDate", type="datetime")
     */
    private $startDate;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="finishDate", type="datetime")
     */
    private $finishDate;

    /**
     * @var boolean
     *
     * @ORM\Column(name="active", type="boolean")
     */
    private $active;

    /**
     * @var boolean
     *
     * @ORM\Column(name="simpleBet", type="boolean")
     */
    private $simpleBet;

    /**
     * @var boolean
     *
     * @ORM\Column(name="scoreDiff", type="boolean")
     */
    private $scoreDiff;

    /**
     * @var boolean
     *
     * @ORM\Column(name="championship", type="boolean")
     */
    private $championship;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForLoss", type="integer", nullable=true)
     */
    private $nbPointsForLoss;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForDraw", type="integer", nullable=true)
     */
    private $nbPointsForDraw;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForWin", type="integer", nullable=true)
     */
    private $nbPointsForWin;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForRightBet", type="integer", nullable=true)
     */
    private $nbPointsForRightBet;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForRightBetWithScore", type="integer", nullable=true)
     */
    private $nbPointsForRightBetWithScore;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForRightBetWithScoreAfterOvertime", type="integer", nullable=true)
     */
    private $nbPointsForRightBetWithScoreAfterOvertime;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForWrongBet", type="integer", nullable=true)
     */
    private $nbPointsForWrongBet;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForAlmostRightBet", type="integer", nullable=true)
     */
    private $nbPointsForAlmostRightBet;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForRightSimpleBet", type="integer", nullable=true)
     */
    private $nbPointsForRightSimpleBet;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForWrongSimpleBet", type="integer", nullable=true)
     */
    private $nbPointsForWrongSimpleBet;

    /**
     * @var integer
     *
     * @ORM\Column(name="nbPointsForRightSliceScore", type="integer", nullable=true)
     */
    private $nbPointsForRightSliceScore;

    /**
     * @var boolean
     *
     * @ORM\Column(name="bestScorer", type="boolean", nullable=true)
     */
    private $bestScorer;

    /**
     * @var file
     *
     * @ORM\Column(name="file", type="string", length=255, nullable=true)
     * @Assert\File(maxSize="6000000")
     */
    private $file;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    public $path;

    /**
     * @ORM\ManyToMany(targetEntity="GameType", mappedBy="events")
     */
    private $gameTypes;

    /**
     * @var integer
     *
     * @ORM\ManyToOne(targetEntity="Sport")
     * @ORM\JoinColumn(name="sport", referencedColumnName="id")
     */
    private $sport;

    public function getAbsolutePath()
    {
        return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
    }

    public function getWebPath()
    {
        return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
    }

    protected function getUploadRootDir()
    {
        // le chemin absolu du répertoire où les documents uploadés doivent être sauvegardés
        return __DIR__.'/../../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // on se débarrasse de « __DIR__ » afin de ne pas avoir de problème lorsqu'on affiche
        // le document/image dans la vue.
        return 'uploads/documents';
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return Event
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set startDate
     *
     * @param \DateTime $startDate
     * @return Event
     */
    public function setStartDate($startDate)
    {
        $this->startDate = $startDate;

        return $this;
    }

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

    /**
     * Set finishDate
     *
     * @param \DateTime $finishDate
     * @return Event
     */
    public function setFinishDate($finishDate)
    {
        $this->finishDate = $finishDate;

        return $this;
    }

    /**
     * Get finishDate
     *
     * @return \DateTime
     */
    public function getFinishDate()
    {
        return $this->finishDate;
    }

    /**
     * Set active
     *
     * @param boolean $active
     * @return Event
     */
    public function setActive($active)
    {
        $this->active = $active;

        return $this;
    }

    /**
     * Get active
     *
     * @return boolean
     */
    public function getActive()
    {
        return $this->active;
    }

    public function __toString()
    {
    	return $this->getName();
    }
    /**
     * @return the $img
     */
    public function getFile() {
    	return $this->file;
    }

    /**
     * @param \Dwf\PronosticsBundle\Entity\file $img
     */
    public function setFile($file) {
    	$this->file = $file;
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
    	if (null !== $this->file) {
    		// faites ce que vous voulez pour générer un nom unique
    		$this->path = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
    	}
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {
    	if (null === $this->file) {
    		return;
    	}

    	// s'il y a une erreur lors du déplacement du fichier, une exception
    	// va automatiquement être lancée par la méthode move(). Cela va empêcher
    	// proprement l'entité d'être persistée dans la base de données si
    	// erreur il y a
    	$this->file->move($this->getUploadRootDir(), $this->path);

    	unset($this->file);
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
    	if ($file = $this->getAbsolutePath()) {
    		unlink($file);
    	}
    }

    public function hasBegan()
    {
        return ($this->getStartDate()->format('U') < time());
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->gameTypes = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Set nbPointsForLoss
     *
     * @param integer $nbPointsForLoss
     * @return Event
     */
    public function setNbPointsForLoss($nbPointsForLoss)
    {
        $this->nbPointsForLoss = $nbPointsForLoss;

        return $this;
    }

    /**
     * Get nbPointsForLoss
     *
     * @return integer
     */
    public function getNbPointsForLoss()
    {
        return $this->nbPointsForLoss;
    }

    /**
     * Set nbPointsForDraw
     *
     * @param integer $nbPointsForDraw
     * @return Event
     */
    public function setNbPointsForDraw($nbPointsForDraw)
    {
        $this->nbPointsForDraw = $nbPointsForDraw;

        return $this;
    }

    /**
     * Get nbPointsForDraw
     *
     * @return integer
     */
    public function getNbPointsForDraw()
    {
        return $this->nbPointsForDraw;
    }

    /**
     * Set nbPointsForWin
     *
     * @param integer $nbPointsForWin
     * @return Event
     */
    public function setNbPointsForWin($nbPointsForWin)
    {
        $this->nbPointsForWin = $nbPointsForWin;

        return $this;
    }

    /**
     * Get nbPointsForWin
     *
     * @return integer
     */
    public function getNbPointsForWin()
    {
        return $this->nbPointsForWin;
    }

    /**
     * Set path
     *
     * @param string $path
     * @return Event
     */
    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * Get path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Add gameTypes
     *
     * @param \Dwf\PronosticsBundle\Entity\GameType $gameTypes
     * @return Event
     */
    public function addGameType(\Dwf\PronosticsBundle\Entity\GameType $gameTypes)
    {
        $this->gameTypes[] = $gameTypes;

        return $this;
    }

    /**
     * Remove gameTypes
     *
     * @param \Dwf\PronosticsBundle\Entity\GameType $gameTypes
     */
    public function removeGameType(\Dwf\PronosticsBundle\Entity\GameType $gameTypes)
    {
        $this->gameTypes->removeElement($gameTypes);
    }

    /**
     * Get gameTypes
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getGameTypes()
    {
        return $this->gameTypes;
    }

    /**
     * Set sport
     *
     * @param \Dwf\PronosticsBundle\Entity\Sport $sport
     * @return Event
     */
    public function setSport(\Dwf\PronosticsBundle\Entity\Sport $sport = null)
    {
        $this->sport = $sport;

        return $this;
    }

    /**
     * Get sport
     *
     * @return \Dwf\PronosticsBundle\Entity\Sport
     */
    public function getSport()
    {
        return $this->sport;
    }

    /**
     * Set nationalTeams
     *
     * @param boolean $nationalTeams
     * @return Event
     */
    public function setNationalTeams($nationalTeams)
    {
        $this->nationalTeams = $nationalTeams;

        return $this;
    }

    /**
     * Get nationalTeams
     *
     * @return boolean
     */
    public function getNationalTeams()
    {
        return $this->nationalTeams;
    }

    /**
     * Set simpleBet
     *
     * @param boolean $simpleBet
     * @return Event
     */
    public function setSimpleBet($simpleBet)
    {
        $this->simpleBet = $simpleBet;

        return $this;
    }

    /**
     * Get simpleBet
     *
     * @return boolean
     */
    public function getSimpleBet()
    {
        return $this->simpleBet;
    }

    /**
     * Set championship
     *
     * @param boolean $championship
     * @return Event
     */
    public function setChampionship($championship)
    {
        $this->championship = $championship;

        return $this;
    }

    /**
     * Get championship
     *
     * @return boolean
     */
    public function getChampionship()
    {
        return $this->championship;
    }

    /**
     * Set bestScorer
     *
     * @param boolean $bestScorer
     *
     * @return Event
     */
    public function setBestScorer($bestScorer)
    {
        $this->bestScorer = $bestScorer;

        return $this;
    }

    /**
     * Get bestScorer
     *
     * @return boolean
     */
    public function getBestScorer()
    {
        return $this->bestScorer;
    }

    /**
     * Set scoreDiff
     *
     * @param boolean $scoreDiff
     *
     * @return Event
     */
    public function setScoreDiff($scoreDiff)
    {
        $this->scoreDiff = $scoreDiff;

        return $this;
    }

    /**
     * Get scoreDiff
     *
     * @return boolean
     */
    public function getScoreDiff()
    {
        return $this->scoreDiff;
    }

    /**
     * Set nbPointsForRightBet
     *
     * @param integer $nbPointsForRightBet
     *
     * @return Event
     */
    public function setNbPointsForRightBet($nbPointsForRightBet)
    {
        $this->nbPointsForRightBet = $nbPointsForRightBet;

        return $this;
    }

    /**
     * Get nbPointsForRightBet
     *
     * @return integer
     */
    public function getNbPointsForRightBet()
    {
        return $this->nbPointsForRightBet;
    }

    /**
     * Set nbPointsForWrongBet
     *
     * @param integer $nbPointsForWrongBet
     *
     * @return Event
     */
    public function setNbPointsForWrongBet($nbPointsForWrongBet)
    {
        $this->nbPointsForWrongBet = $nbPointsForWrongBet;

        return $this;
    }

    /**
     * Get nbPointsForWrongBet
     *
     * @return integer
     */
    public function getNbPointsForWrongBet()
    {
        return $this->nbPointsForWrongBet;
    }

    /**
     * Set nbPointsForAlmostRightBet
     *
     * @param integer $nbPointsForAlmostRightBet
     *
     * @return Event
     */
    public function setNbPointsForAlmostRightBet($nbPointsForAlmostRightBet)
    {
        $this->nbPointsForAlmostRightBet = $nbPointsForAlmostRightBet;

        return $this;
    }

    /**
     * Get nbPointsForAlmostRightBet
     *
     * @return integer
     */
    public function getNbPointsForAlmostRightBet()
    {
        return $this->nbPointsForAlmostRightBet;
    }

    /**
     * Set nbPointsForRightSimpleBet
     *
     * @param integer $nbPointsForRightSimpleBet
     *
     * @return Event
     */
    public function setNbPointsForRightSimpleBet($nbPointsForRightSimpleBet)
    {
        $this->nbPointsForRightSimpleBet = $nbPointsForRightSimpleBet;

        return $this;
    }

    /**
     * Get nbPointsForRightSimpleBet
     *
     * @return integer
     */
    public function getNbPointsForRightSimpleBet()
    {
        return $this->nbPointsForRightSimpleBet;
    }

    /**
     * Set nbPointsForWrongSimpleBet
     *
     * @param integer $nbPointsForWrongSimpleBet
     *
     * @return Event
     */
    public function setNbPointsForWrongSimpleBet($nbPointsForWrongSimpleBet)
    {
        $this->nbPointsForWrongSimpleBet = $nbPointsForWrongSimpleBet;

        return $this;
    }

    /**
     * Get nbPointsForWrongSimpleBet
     *
     * @return integer
     */
    public function getNbPointsForWrongSimpleBet()
    {
        return $this->nbPointsForWrongSimpleBet;
    }

    /**
     * Set nbPointsForRightBetWithScore
     *
     * @param integer $nbPointsForRightBetWithScore
     *
     * @return Event
     */
    public function setNbPointsForRightBetWithScore($nbPointsForRightBetWithScore)
    {
        $this->nbPointsForRightBetWithScore = $nbPointsForRightBetWithScore;

        return $this;
    }

    /**
     * Get nbPointsForRightBetWithScore
     *
     * @return integer
     */
    public function getNbPointsForRightBetWithScore()
    {
        return $this->nbPointsForRightBetWithScore;
    }

    /**
     * Set nbPointsForRightBetWithScoreAfterOvertime
     *
     * @param integer $nbPointsForRightBetWithScoreAfterOvertime
     *
     * @return Event
     */
    public function setNbPointsForRightBetWithScoreAfterOvertime($nbPointsForRightBetWithScoreAfterOvertime)
    {
        $this->nbPointsForRightBetWithScoreAfterOvertime = $nbPointsForRightBetWithScoreAfterOvertime;

        return $this;
    }

    /**
     * Get nbPointsForRightBetWithScoreAfterOvertime
     *
     * @return integer
     */
    public function getNbPointsForRightBetWithScoreAfterOvertime()
    {
        return $this->nbPointsForRightBetWithScoreAfterOvertime;
    }

    /**
     * Set nbPointsForRightSliceScore
     *
     * @param integer $nbPointsForRightSliceScore
     *
     * @return Event
     */
    public function setNbPointsForRightSliceScore($nbPointsForRightSliceScore)
    {
        $this->nbPointsForRightSliceScore = $nbPointsForRightSliceScore;

        return $this;
    }

    /**
     * Get nbPointsForRightSliceScore
     *
     * @return integer
     */
    public function getNbPointsForRightSliceScore()
    {
        return $this->nbPointsForRightSliceScore;
    }
}


text:
.view-switcher {
    padding: 0.5em;
    font-weight: normal;
}

/* styles for validation helpers */
.field-validation-error {
    color: #e80c4d;
    font-weight: bold;
}

.field-validation-valid {
    display: none;
}

input[type="text"].input-validation-error,
input[type="password"].input-validation-error {
    border: solid 1px #e80c4d;
}

.validation-summary-errors {
    color: #e80c4d;
    font-weight: bold;
    font-size: 1.1em;
}

.validation-summary-valid {
    display: none;
}
.clear { clear: both; }


text:
package azkaban.trigger;

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

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import azkaban.alert.Alerter;
import azkaban.executor.ExecutorLoader;
import azkaban.executor.ExecutorManager;
import azkaban.executor.ExecutorManagerException;
import azkaban.executor.MockExecutorLoader;
import azkaban.trigger.builtin.CreateTriggerAction;
import azkaban.utils.Props;

public class TriggerManagerDeadlockTest {

  TriggerLoader loader;
  TriggerManager triggerManager;
  ExecutorLoader execLoader;

  @Before
  public void setup() throws ExecutorManagerException, TriggerManagerException {
    loader = new MockTriggerLoader();
    Props props = new Props();
    props.put("trigger.scan.interval", 1000);
    props.put("executor.port", 12321);
    execLoader = new MockExecutorLoader();
    Map<String, Alerter> alerters = new HashMap<String, Alerter>();
    ExecutorManager executorManager =
        new ExecutorManager(props, execLoader, alerters);
    triggerManager = new TriggerManager(props, loader, executorManager);
  }

  @After
  public void tearDown() {

  }

  @Test
  public void deadlockTest() throws TriggerLoaderException,
      TriggerManagerException {
    // this should well saturate it
    for (int i = 0; i < 1000; i++) {
      Trigger t = createSelfRegenTrigger();
      loader.addTrigger(t);
    }
    // keep going and add more
    for (int i = 0; i < 10000; i++) {
      Trigger d = createDummyTrigger();
      triggerManager.insertTrigger(d);
      triggerManager.removeTrigger(d);
    }

    System.out.println("No dead lock.");
  }

  public class AlwaysOnChecker implements ConditionChecker {

    public static final String type = "AlwaysOnChecker";

    private final String id;
    private final Boolean alwaysOn;

    public AlwaysOnChecker(String id, Boolean alwaysOn) {
      this.id = id;
      this.alwaysOn = alwaysOn;
    }

    @Override
    public Object eval() {
      // TODO Auto-generated method stub
      return alwaysOn;
    }

    @Override
    public Object getNum() {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public void reset() {
      // TODO Auto-generated method stub

    }

    @Override
    public String getId() {
      return id;
    }

    @Override
    public String getType() {
      // TODO Auto-generated method stub
      return type;
    }

    @Override
    public ConditionChecker fromJson(Object obj) throws Exception {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public Object toJson() {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public void stopChecker() {
      // TODO Auto-generated method stub

    }

    @Override
    public void setContext(Map<String, Object> context) {
      // TODO Auto-generated method stub

    }

    @Override
    public long getNextCheckTime() {
      // TODO Auto-generated method stub
      return 0;
    }

  }

  private Trigger createSelfRegenTrigger() {
    ConditionChecker alwaysOnChecker =
        new AlwaysOnChecker("alwaysOn", Boolean.TRUE);
    String triggerExpr = alwaysOnChecker.getId() + ".eval()";
    Map<String, ConditionChecker> triggerCheckers =
        new HashMap<String, ConditionChecker>();
    triggerCheckers.put(alwaysOnChecker.getId(), alwaysOnChecker);
    Condition triggerCond = new Condition(triggerCheckers, triggerExpr);

    TriggerAction triggerAct =
        new CreateTriggerAction("dummyTrigger", createDummyTrigger());
    List<TriggerAction> actions = new ArrayList<TriggerAction>();
    actions.add(triggerAct);

    ConditionChecker alwaysOffChecker =
        new AlwaysOnChecker("alwaysOff", Boolean.FALSE);
    String expireExpr = alwaysOffChecker.getId() + ".eval()";
    Map<String, ConditionChecker> expireCheckers =
        new HashMap<String, ConditionChecker>();
    expireCheckers.put(alwaysOffChecker.getId(), alwaysOffChecker);
    Condition expireCond = new Condition(expireCheckers, expireExpr);

    Trigger t =
        new Trigger("azkaban", "azkabanTest", triggerCond, expireCond, actions);
    return t;
  }

  private Trigger createDummyTrigger() {
    ConditionChecker alwaysOnChecker =
        new AlwaysOnChecker("alwaysOn", Boolean.TRUE);
    String triggerExpr = alwaysOnChecker.getId() + ".eval()";
    Map<String, ConditionChecker> triggerCheckers =
        new HashMap<String, ConditionChecker>();
    triggerCheckers.put(alwaysOnChecker.getId(), alwaysOnChecker);
    Condition triggerCond = new Condition(triggerCheckers, triggerExpr);

    TriggerAction triggerAct = new DummyTriggerAction("howdy!");
    List<TriggerAction> actions = new ArrayList<TriggerAction>();
    actions.add(triggerAct);

    ConditionChecker alwaysOffChecker =
        new AlwaysOnChecker("alwaysOff", Boolean.FALSE);
    String expireExpr = alwaysOffChecker.getId() + ".eval()";
    Map<String, ConditionChecker> expireCheckers =
        new HashMap<String, ConditionChecker>();
    expireCheckers.put(alwaysOffChecker.getId(), alwaysOffChecker);
    Condition expireCond = new Condition(expireCheckers, expireExpr);

    Trigger t =
        new Trigger("azkaban", "azkabanTest", triggerCond, expireCond, actions);
    return t;
  }

}


text:
import { storiesOf } from "@storybook/react";
import * as React from "react";

import ActionDialog from "../../../components/ActionDialog";
import Decorator from "../../Decorator";

storiesOf("Generics / ActionDialog", module)
  .addDecorator(Decorator)
  .add("default", () => (
    <ActionDialog
      title="Example title"
      open={true}
      onClose={undefined}
      onConfirm={undefined}
      confirmButtonState="default"
    >
      Example content
    </ActionDialog>
  ));


text:
using System;
/*
Declare  two integer variables and assign them with 5 and 10 and after that exchange their values.
*/

    class ChangingVariables
    {
        static void Main(string[] args)
        {

            int firstVar = 5;
            int secondVar = 10;
            int thirdVar = firstVar;

            firstVar = secondVar;
            secondVar = thirdVar;

            Console.WriteLine("firstVar = {0}, secondVar = {1}",firstVar,secondVar);

        }
    }


text:
/*global define*/
define([
        '../Core/BoundingRectangle',
        '../Core/Color',
        '../Core/defined',
        '../Core/destroyObject',
        '../Core/DeveloperError',
        '../Renderer/RenderState',
        '../Renderer/ShaderSource',
        '../Shaders/ViewportQuadFS',
        './BlendingState',
        './Material',
        './Pass'
    ], function(
        BoundingRectangle,
        Color,
        defined,
        destroyObject,
        DeveloperError,
        RenderState,
        ShaderSource,
        ViewportQuadFS,
        BlendingState,
        Material,
        Pass) {
    "use strict";

    /**
     * A viewport aligned quad.
     *
     * @alias ViewportQuad
     * @constructor
     *
     * @param {BoundingRectangle} [rectangle] The {@link BoundingRectangle} defining the quad's position within the viewport.
     * @param {Material} [material] The {@link Material} defining the surface appearance of the viewport quad.
     *
     * @example
     * var viewportQuad = new Cesium.ViewportQuad(new Cesium.BoundingRectangle(0, 0, 80, 40));
     * viewportQuad.material.uniforms.color = new Cesium.Color(1.0, 0.0, 0.0, 1.0);
     */
    var ViewportQuad = function(rectangle, material) {
        /**
         * Determines if the viewport quad primitive will be shown.
         *
         * @type {Boolean}
         * @default true
         */
        this.show = true;

        if (!defined(rectangle)) {
            rectangle = new BoundingRectangle();
        }

        /**
         * The BoundingRectangle defining the quad's position within the viewport.
         *
         * @type {BoundingRectangle}
         *
         * @example
         * viewportQuad.rectangle = new Cesium.BoundingRectangle(0, 0, 80, 40);
         */
        this.rectangle = BoundingRectangle.clone(rectangle);

        if (!defined(material)) {
            material = Material.fromType(Material.ColorType, {
                color : new Color(1.0, 1.0, 1.0, 1.0)
            });
        }

        /**
         * The surface appearance of the viewport quad.  This can be one of several built-in {@link Material} objects or a custom material, scripted with
         * {@link https://github.com/AnalyticalGraphicsInc/cesium/wiki/Fabric|Fabric}.
         *

         * The default material is Material.ColorType.
         *

         *
         * @type Material
         *
         * @example
         * // 1. Change the color of the default material to yellow
         * viewportQuad.material.uniforms.color = new Cesium.Color(1.0, 1.0, 0.0, 1.0);
         *
         * // 2. Change material to horizontal stripes
         * viewportQuad.material = Cesium.Material.fromType(Cesium.Material.StripeType);
         *
         * @see {@link https://github.com/AnalyticalGraphicsInc/cesium/wiki/Fabric|Fabric}
         */
        this.material = material;
        this._material = undefined;

        this._overlayCommand = undefined;
        this._rs = undefined;
    };

    /**
     * Called when {@link Viewer} or {@link CesiumWidget} render the scene to
     * get the draw commands needed to render this primitive.
     *

     * Do not call this function directly.  This is documented just to
     * list the exceptions that may be propagated when the scene is rendered:
     *

     *
     * @exception {DeveloperError} this.material must be defined.
     * @exception {DeveloperError} this.rectangle must be defined.
     */
    ViewportQuad.prototype.update = function(context, frameState, commandList) {
        if (!this.show) {
            return;
        }

        //>>includeStart('debug', pragmas.debug);
        if (!defined(this.material)) {
            throw new DeveloperError('this.material must be defined.');
        }
        if (!defined(this.rectangle)) {
            throw new DeveloperError('this.rectangle must be defined.');
        }
        //>>includeEnd('debug');

        var rs = this._rs;
        if ((!defined(rs)) || !BoundingRectangle.equals(rs.viewport, this.rectangle)) {
            this._rs = RenderState.fromCache({
                blending : BlendingState.ALPHA_BLEND,
                viewport : this.rectangle
            });
        }

        var pass = frameState.passes;
        if (pass.render) {
            if (this._material !== this.material || !defined(this._overlayCommand)) {
                // Recompile shader when material changes
                this._material = this.material;

                if (defined(this._overlayCommand)) {
                    this._overlayCommand.shaderProgram.destroy();
                }

                var fs = new ShaderSource({
                    sources : [this._material.shaderSource, ViewportQuadFS]
                });
                this._overlayCommand = context.createViewportQuadCommand(fs, {
                    renderState : this._rs,
                    uniformMap : this._material._uniforms,
                    owner : this
                });
                this._overlayCommand.pass = Pass.OVERLAY;
            }

            this._material.update(context);

            this._overlayCommand.uniformMap = this._material._uniforms;
            commandList.push(this._overlayCommand);
        }
    };

    /**
     * Returns true if this object was destroyed; otherwise, false.
     *

     * If this object was destroyed, it should not be used; calling any function other than
     * isDestroyed will result in a {@link DeveloperError} exception.
     *
     * @returns {Boolean} True if this object was destroyed; otherwise, false.
     *
     * @see ViewportQuad#destroy
     */
    ViewportQuad.prototype.isDestroyed = function() {
        return false;
    };

    /**
     * Destroys the WebGL resources held by this object.  Destroying an object allows for deterministic
     * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
     *

     * Once an object is destroyed, it should not be used; calling any function other than
     * isDestroyed will result in a {@link DeveloperError} exception.  Therefore,
     * assign the return value (undefined) to the object as done in the example.
     *
     * @returns {undefined}
     *
     * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
     *
     * @see ViewportQuad#isDestroyed
     *
     * @example
     * quad = quad && quad.destroy();
     */
    ViewportQuad.prototype.destroy = function() {
        if (defined(this._overlayCommand)) {
            this._overlayCommand.shaderProgram = this._overlayCommand.shaderProgram && this._overlayCommand.shaderProgram.destroy();
        }
        return destroyObject(this);
    };

    return ViewportQuad;
});


text:
{{title}}

		{{#if isBlog}}
		More
		{{/if}}
		{{#unless isBlog}}
		Play
		{{/unless}}

			{{this.looks}}

			{{this.likes}}

			{{this.bookmarksCount}}

			{{this.commentsCount}}

 {{#each tags}}
		{{this}} {{/each}}

Published by {{author}} on {{date}}

		{{description}}

 Comments:

	<textarea id="comment-add-area" rows="3" cols="21" style="color:midnightblue"></textarea>
	New

		{{#each comments}}

{{this.content}}

Posted by {{this.author}} on {{this.date}}

		{{/each}}


text:
/**
 * Created by Shuffle on 20.03.2015.
 */
'use strict';

angular.module('cmsApp')
    .factory('authenticationInterceptor', function(authenticationTokenService){
        return{
            request: function(config){
                var token = authenticationTokenService.getToken();
                if(token){
                    config.headers.Authorization = token;
                }
                return config;
            },
            response: function(response){
                return response;
            }
        }

});


text:
namespace MusicStore.Web
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;
    using System.Net.Http.Headers;
    using System.Web.Http.Tracing;

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }
    }
}


text:
namespace spio {
SPIO_BEGIN_NAMESPACE

template <typename Readable>
result read_all(Readable& d, span<byte> s, bool& eof)
{
    auto total_read = 0;
    for (auto i = 0; i < SPIO_READ_ALL_MAX_ATTEMPTS; ++i) {
        auto ret = d.read(s, eof);
        total_read += ret.value();
        if (eof) {
            break;
        }
        if (SPIO_UNLIKELY(ret.has_error() &&
                          ret.error().code() != std::errc::interrupted)) {
            return make_result(total_read, ret.error());
        }
        if (SPIO_UNLIKELY(ret.value() != s.size())) {
            s = s.subspan(ret.value());
        }
        break;
    }
    return total_read;
}

template <typename VectorReadable>
expected<span<typename VectorReadable::buffer_type>, failure> vread_all(
    span<typename VectorReadable::buffer_type> bufs,
    streampos pos = 0)
{
    SPIO_UNUSED(bufs);
    SPIO_UNUSED(pos);
    SPIO_UNIMPLEMENTED;
}

namespace detail {
    template <typename Source>
    class basic_buffered_source_base {
    public:
        using source_type = Source;

        basic_buffered_source_base(source_type* s) : m_source(s) {}

        SPIO_CONSTEXPR14 source_type& get() noexcept
        {
            return *m_source;
        }
        SPIO_CONSTEXPR const source_type& get() const noexcept
        {
            return *m_source;
        }
        SPIO_CONSTEXPR14 source_type& operator*() noexcept
        {
            return get();
        }
        SPIO_CONSTEXPR const source_type& operator*() const noexcept
        {
            return get();
        }
        SPIO_CONSTEXPR14 source_type* operator->() noexcept
        {
            return m_source;
        }
        SPIO_CONSTEXPR const source_type* operator->() const noexcept
        {
            return m_source;
        }

    private:
        source_type* m_source;
    };

    template <typename T>
    SPIO_CONSTEXPR14 T round_up_multiple_of_two(T n, T multiple) noexcept
    {
        Expects(multiple > 0);
        Expects((multiple & (multiple - 1)) == 0);
        return (n + multiple - 1) & -multiple;
    }
}  // namespace detail

template <typename Readable>
class basic_buffered_readable
    : public detail::basic_buffered_source_base<Readable> {
    using base = detail::basic_buffered_source_base<Readable>;

public:
    using readable_type = typename base::source_type;
    using buffer_type = ring;
    using size_type = std::ptrdiff_t;

    static SPIO_CONSTEXPR_DECL const size_type buffer_size = BUFSIZ * 2;

    basic_buffered_readable(readable_type& r,
                            size_type s = size_type(buffer_size),
                            size_type rs = -1)
        : base(std::addressof(r)),
          m_buffer(detail::round_up_power_of_two(s)),
          m_read_size(rs)
    {
        if (m_read_size == -1) {
            m_read_size = m_buffer.size() / 2;
        }
        m_read_size = detail::round_up_power_of_two(m_read_size);
        Expects(rs <= m_buffer.size());
    }

    SPIO_CONSTEXPR size_type free_space() const noexcept
    {
        return m_buffer.free_space();
    }
    SPIO_CONSTEXPR size_type in_use() const noexcept
    {
        return m_buffer.in_use();
    }
    SPIO_CONSTEXPR size_type size() const noexcept
    {
        return m_buffer.size();
    }

    result read(span<byte> s, bool& eof)
    {
        auto r = [&]() -> result {
            if (in_use() < s.size() && !m_eof) {
                return read_into_buffer(get_read_size(s.size()), m_eof);
            }
            return {0};
        }();
        if (m_eof && s.size() > in_use()) {
            eof = true;
        }
        s = s.first(std::min(s.size(), in_use()));
        auto bytes_read = read_from_buffer(s);
        Ensures(bytes_read == s.size());
        return {bytes_read, r.inspect_error()};
    }
    result putback(span<byte> s)
    {
#if SPIO_GCC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstrict-overflow"
#endif
        if (s.size() > free_space()) {
            return make_result(m_buffer.write_tail(s.first(free_space())),
                               out_of_memory);
        }
        return m_buffer.write_tail(s);
#if SPIO_GCC
#pragma GCC diagnostic pop
#endif
    }

private:
    SPIO_CONSTEXPR14 size_type get_read_size(size_type n) const noexcept
    {
        return std::min(detail::round_up_multiple_of_two(n, m_read_size),
                        free_space());
    }

    result read_into_buffer(size_type n, bool& eof)
    {
        Expects(n <= free_space());

        size_type has_read = 0;
        auto buffer = m_buffer.direct_write(n);
        for (auto it = buffer.begin(); it != buffer.end(); ++it) {
            auto r = base::get().read(*it, eof);
            has_read += r.value();
            if (r.has_error()) {
                return {has_read, r.inspect_error()};
            }
            if (eof) {
                if (it != buffer.end()) {
                    ++it;  // can't use a ranged for because of this
                }
                break;
            }
        }
        m_buffer.move_head(-(n - has_read));
        return has_read;
    }
    size_type read_from_buffer(span<byte> s)
    {
        return m_buffer.read(s);
    }

    buffer_type m_buffer;
    size_type m_read_size;
    bool m_eof{false};
};

SPIO_END_NAMESPACE
}  // namespace spio

#endif  // SPIO_SINK_H


text:
import {isMobile} from "UI";
import React = require('react');
/// <reference path="./typings/react/react.d.ts" />

export default class FormSection  extends React.Component<{
  id: string;
  hlevel: number;
  label: string;
}, any> {
  render() {
      return(

          {`<h${this.props.hlevel} id=${this.props.id} class="section-label form-section-label">`}
            {this.props.label}
          {`</h${this.props.hlevel}>`}

            {(this.props as any).children}

      );
  }
}


text:
@interface FFPrefPaneController (Private)

- (void)setStartsAtLogin:(BOOL)flag;

@end

@implementation FFPrefPaneController

- (void) mainViewDidLoad {
	// First load of a new version of the pref-pane
	NSString *lastVersion = (NSString *)[[FFPreferenceManager sharedInstance] valueForKey:@"version"];
	if(!lastVersion || ![lastVersion isEqualToString:[self bundleVersionNumber]]) {
		[self restartHelperApp];
		[[FFPreferenceManager sharedInstance] setValue:[self bundleVersionNumber] forKey:@"version"];
	} else {
		[self performSelector:@selector(updateHelperAppStatus) withObject:nil afterDelay:0.1];
	}

    [[FFPreferenceManager sharedInstance] addObserver:self forKeyPath:KG_LOGIN_KEYPATH options:NSKeyValueObservingOptionNew context:NULL];
    [self setStartsAtLogin:[[[FFPreferenceManager sharedInstance] valueForKey:KG_LOGIN_KEYPATH] boolValue]];
}

//- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
//}

- (IBAction)startStopHelperApp:(id)sender {
	[FFHelperAppController startStopHelperApp];
	[helperAppProgress startAnimation:self];
	[startStopHelperApp setEnabled:NO];
	// give the app a moment to start, then check if it's running.
	[self performSelector:@selector(updateHelperAppStatus) withObject:nil afterDelay:3.0];
}

- (void)restartHelperApp {
	[FFHelperAppController restartHelperApp];
	[helperAppStatus setStringValue:@"Upgrading FunctionFlip..."];
	[helperAppProgress startAnimation:self];
	[startStopHelperApp setEnabled:NO];
	// give the app a moment to start, then check if it's running.
	[self performSelector:@selector(updateHelperAppStatus) withObject:nil afterDelay:4.0];
}

- (void)updateHelperAppStatus {
	if([FFHelperAppController isHelperAppRunning]) {
		[helperAppStatus setStringValue:@"FunctionFlip is running."];
		[startStopHelperApp setTitle:@"Stop FunctionFlip"];
	} else {
		[helperAppStatus setStringValue:@"FunctionFlip is stopped."];
		[startStopHelperApp setTitle:@"Start FunctionFlip"];
	}
	[startStopHelperApp setEnabled:YES];
	[helperAppProgress stopAnimation:self];
}

- (FFPreferenceManager *)ffPreferenceManager {
	return [FFPreferenceManager sharedInstance];
}

// not cached since we want to ask DDHidKeyboard for any new keyboards every time
// could have caching with a check or notifcation of changes, but KISS
- (NSArray *)keyboards {
	NSMutableArray *keyboards = [NSMutableArray arrayWithCapacity:1];
	for(DDHidKeyboard *device in [DDHidKeyboard allKeyboards]) {
		FFKeyboard *keyboard = [FFKeyboard keyboardWithDevice:device];
		if(keyboard) [keyboards addObject:keyboard];
	}
	return keyboards;
}

- (IBAction)showAbout:(id)sender {
	[NSApp beginSheet:aboutSheet modalForWindow:[[self mainView] window] modalDelegate:self didEndSelector:@selector(aboutSheetDidEnd:returnCode:contextInfo:) contextInfo:NULL];
}

- (IBAction)hideAbout:(id)sender {
	[NSApp endSheet:aboutSheet];
}

- (void)aboutSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
	[aboutSheet orderOut:self];
}

- (IBAction)openHomePage:(id)sender {
	[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://kevingessner.com/software/functionflip/"]];
}

- (NSString *)bundleVersionNumber {
	return [[[NSBundle bundleWithIdentifier:FF_PREFPANE_BUNDLE_IDENTIFIER] infoDictionary] valueForKey:@"CFBundleVersion"];
}

- (IBAction)checkForUpdate:(id)sender {
	[NSApp beginSheet:updateSheet modalForWindow:[[self mainView] window] modalDelegate:self didEndSelector:@selector(updateSheetDidEnd:returnCode:contextInfo:) contextInfo:NULL];
	[updateSheetController beginUpdate];
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:FF_UPDATE_URL] cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:15.0];
	NSURLResponse *response; // required out-parameter for next line
	NSError *error;
	NSData *versionData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	if(!versionData) {
        NSLog(@"Couldn't get version: %@", error);
		[updateSheetController updateFailed];
	} else {
        NSString *updateVersion = [[[NSString alloc] initWithData:versionData encoding:NSASCIIStringEncoding] autorelease];
        NSLog(@"found version %@", updateVersion);
        if([updateVersion isEqualToString:[self bundleVersionNumber]]) {
			[updateSheetController updateNotAvailable];
		} else {
			[updateSheetController updateAvailable:updateVersion];
		}
	}
}

- (IBAction)hideUpdateSheet:(id)sender {
	[NSApp endSheet:updateSheet];
}

- (void)updateSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
	[updateSheet orderOut:self];
}

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:KG_LOGIN_KEYPATH]) {
		[self setStartsAtLogin:[[[FFPreferenceManager sharedInstance] valueForKey:KG_LOGIN_KEYPATH] boolValue]];
	} else {
		[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
	}
}

-(void) addAppAsLoginItem:(NSString *)appPath {
	// This will retrieve the path for the application
	// For example, /Applications/test.app
	CFURLRef url = (CFURLRef)[NSURL fileURLWithPath:appPath];

	// Create a reference to the shared file list.
    // We are adding it to the current user only.
    // If we want to add it all users, use
    // kLSSharedFileListGlobalLoginItems instead of
    //kLSSharedFileListSessionLoginItems
	LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL,
                                                            kLSSharedFileListSessionLoginItems, NULL);
	if (loginItems) {
		//Insert an item to the list.
		LSSharedFileListItemRef item = LSSharedFileListInsertItemURL(loginItems,
                                                                     kLSSharedFileListItemLast, NULL, NULL,
                                                                     url, NULL, NULL);
		if (item){
			CFRelease(item);
        }
	}
	CFRelease(loginItems);
}

-(void) deleteAppFromLoginItem:(NSString *)appPath {
	CFURLRef url;

	// Create a reference to the shared file list.
	LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);

	if (loginItems) {
		UInt32 seedValue;
		NSArray *loginItemsArray = (NSArray *)LSSharedFileListCopySnapshot(loginItems, &seedValue);
		for(id itemRef in loginItemsArray) {
            //Resolve the item with URL
			if (LSSharedFileListItemResolve((LSSharedFileListItemRef)itemRef, 0, &url, NULL) == noErr) {
				NSString * urlPath = [(NSURL*)url path];
				if ([urlPath isEqualToString:appPath]){
					LSSharedFileListItemRemove(loginItems, (LSSharedFileListItemRef)itemRef);
				}
			}
		}
		[loginItemsArray release];
	}
}

- (void)setStartsAtLogin:(BOOL)flag {
    NSString *appPath = [FFHelperAppController pathToHelperApp];
    if (flag) {
        [self addAppAsLoginItem:appPath];
    } else {
        [self deleteAppFromLoginItem:appPath];
    }
}

@end


text:
package com.qatang.core.query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * @author qatang
 * @since 2014-12-29 15:56
 */
public abstract class AbstractSearchable<T> implements Searchable<T> {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private Pageable pageable;

    private Sort sortable;

    private String sort;

    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }

    @Override
    public Pageable getPageable() {
        return pageable;
    }

    public void setPageable(Pageable pageable) {
        this.pageable = pageable;
    }

    @Override
    public Sort getSortable() {
        return sortable;
    }

    public void setSortable(Sort sortable) {
        this.sortable = sortable;
    }

    @Override
    public Specification<T> getSpecification() {
        return new Specification<T>() {
            @Override
            public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                return createPredicate(root, criteriaQuery, criteriaBuilder);
            }
        };
    }

    protected abstract Predicate createPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder);
}


text:
function [ BP_Struct ] = CTstruct2BP( CT_struct, RiboLabMap, varargin )
%UNTITLED Summary of this function goes here
%   Detailed explanation goes here

%Assume single stranded for now. Assumes consecutive for now. Assume
%bases are all numbers.

WriteToFile=false();
Path='.';
index=0;

if nargin > 2
    for ind=1:length(varargin)/2
        switch varargin{2*ind-1}
            case 'WriteToFile'
                WriteToFile=varargin{2*ind};
            case 'Path'
                Path=varargin{2*ind};
        end
    end
end

numBases=length(CT_struct.Data);

DataSetName=CT_struct.Name;
BP_Struct.Name=DataSetName;
BP_Struct.Chain='unknown';

b=[CT_struct.Data.BasePaired];
% numBasePairs=sum(b>0); %This is double, will need DeDupping.

for i=1:numBases
    if CT_struct.Data(i).BasePaired > 0
        BP_Struct.Data(index+1).Index=index+1;
        BP_Struct.Data(index+1).BP1_Name=CT_struct.Data(i).Base;
        BP_Struct.Data(index+1).BP1_Num=regexprep(RiboLabMap.ItemNames{CT_struct.Data(i).BaseNumber},'_','');
        BP_Struct.Data(index+1).BP1_Chain='';
        BP_Struct.Data(index+1).BP2_Name=CT_struct.Data(CT_struct.Data(i).BasePaired).Base;
        BP_Struct.Data(index+1).BP2_Num=regexprep(RiboLabMap.ItemNames{CT_struct.Data(i).BasePaired},'_','');
        BP_Struct.Data(index+1).BP2_Chain='';
        BP_Struct.Data(index+1).BP_Type='unkwn';
        index=index+1;
    end
end

BP_Struct=DeDupBP(BP_Struct);

if (WriteToFile)
    FR3D_Interaction_Tables=BP2Table(BP_Struct,'TableFormat','CustomData','ItemList',RiboLabMap.ItemNames,'Merge',false);
    fid=fopen(fullfile(Path,[DataSetName,'_BasePairs','.csv']),'wt');
    for i=1:size(FR3D_Interaction_Tables{1},1);
        fprintf(fid, '%s,%s,%s,%s\n',FR3D_Interaction_Tables{1}{i,:});
    end
    fclose(fid);
end

end

% Names={'BasePairs','Stacking','BaseSugar','BasePhosphate'};
% for i=1:length(Names)
%     xlswrite([DataSetName_path,'\',get(handles.DataSetName,'String'),'_',Names{i},'.xlsx'],...
%         result.FR3D_Interaction_Tables{i}(:,1:4));
% end


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/spdy/http2_priority_dependencies.h"

#include <algorithm>

#include "testing/gmock/include/gmock/gmock.h"
#include "testing/platform_test.h"

using ::testing::ContainerEq;

namespace net {

bool operator==(const Http2PriorityDependencies::DependencyUpdate& a,
                const Http2PriorityDependencies::DependencyUpdate& b) {
  return a.id == b.id && a.parent_stream_id == b.parent_stream_id &&
         a.weight == b.weight && a.exclusive == b.exclusive;
}

std::ostream& operator<<(
    std::ostream& os,
    const std::vector<Http2PriorityDependencies::DependencyUpdate>& v) {
  for (auto e : v) {
    os << "{" << e.id << "," << e.parent_stream_id << "," << e.weight << ","
       << (e.exclusive ? "true" : "false") << "}";
  }
  return os;
}

class HttpPriorityDependencyTest : public PlatformTest {
 public:
  HttpPriorityDependencyTest() : next_id_(0u) {}

  // Fixed priority values to use for testing.
  enum {
    HIGHEST = spdy::kV3HighestPriority,
    MEDIUM = HIGHEST + 1,
    LOW = MEDIUM + 1,
    LOWEST = spdy::kV3LowestPriority,
  };

  spdy::SpdyStreamId GetId() { return ++next_id_; }

  void TestStreamCreation(spdy::SpdyStreamId new_id,
                          spdy::SpdyPriority priority,
                          spdy::SpdyStreamId expected_parent_id) {
    int expected_weight = spdy::Spdy3PriorityToHttp2Weight(priority);

    spdy::SpdyStreamId parent_id = 999u;
    int weight = -1;
    bool exclusive = false;
    dependency_state_.OnStreamCreation(new_id, priority, &parent_id, &weight,
                                       &exclusive);
    if (expected_parent_id != parent_id || !exclusive ||
        expected_weight != weight) {
      ADD_FAILURE() << "OnStreamCreation(" << new_id << ", " << int(priority)
                    << ")\n"
                    << "  Got:  (" << parent_id << ", " << weight << ", "
                    << exclusive << ")\n"
                    << "  Want: (" << expected_parent_id << ", "
                    << expected_weight << ", true)\n";
    }
  }

  struct ExpectedDependencyUpdate {
    spdy::SpdyStreamId id;
    spdy::SpdyStreamId parent_id;
    int weight;
  };

  void TestStreamUpdate(spdy::SpdyStreamId id,
                        spdy::SpdyPriority new_priority,
                        std::vector<ExpectedDependencyUpdate> expected) {
    auto value = dependency_state_.OnStreamUpdate(id, new_priority);
    std::vector<Http2PriorityDependencies::DependencyUpdate> expected_value;
    for (auto e : expected) {
      expected_value.push_back(
          {e.id, e.parent_id, e.weight, true /* exclusive */});
    }
    if (value != expected_value) {
      ADD_FAILURE() << "OnStreamUpdate(" << id << ", " << int(new_priority)
                    << ")\n"
                    << "  Value:    " << value << "\n"
                    << "  Expected: " << expected_value << "\n";
    }
  }

  void OnStreamDestruction(spdy::SpdyStreamId id) {
    dependency_state_.OnStreamDestruction(id);
  }

 private:
  spdy::SpdyStreamId next_id_;
  Http2PriorityDependencies dependency_state_;
};

// Confirm dependencies correct for entries at the same priority.
TEST_F(HttpPriorityDependencyTest, SamePriority) {
  const spdy::SpdyStreamId first_id = GetId();
  const spdy::SpdyStreamId second_id = GetId();
  const spdy::SpdyStreamId third_id = GetId();

  TestStreamCreation(first_id, MEDIUM, 0u);
  TestStreamCreation(second_id, MEDIUM, first_id);
  TestStreamCreation(third_id, MEDIUM, second_id);
}

// Confirm dependencies correct for entries at different priorities, increasing.
TEST_F(HttpPriorityDependencyTest, DifferentPriorityIncreasing) {
  const spdy::SpdyStreamId first_id = GetId();
  const spdy::SpdyStreamId second_id = GetId();
  const spdy::SpdyStreamId third_id = GetId();

  TestStreamCreation(first_id, LOWEST, 0u);
  TestStreamCreation(second_id, MEDIUM, 0u);
  TestStreamCreation(third_id, HIGHEST, 0u);
}

// Confirm dependencies correct for entries at different priorities, increasing.
TEST_F(HttpPriorityDependencyTest, DifferentPriorityDecreasing) {
  const spdy::SpdyStreamId first_id = GetId();
  const spdy::SpdyStreamId second_id = GetId();
  const spdy::SpdyStreamId third_id = GetId();

  TestStreamCreation(first_id, HIGHEST, 0u);
  TestStreamCreation(second_id, MEDIUM, first_id);
  TestStreamCreation(third_id, LOWEST, second_id);
}

// Confirm dependencies correct if requests are completed between before
// next creation.
TEST_F(HttpPriorityDependencyTest, CompletionBeforeIssue) {
  const spdy::SpdyStreamId first_id = GetId();
  const spdy::SpdyStreamId second_id = GetId();
  const spdy::SpdyStreamId third_id = GetId();

  TestStreamCreation(first_id, HIGHEST, 0u);
  OnStreamDestruction(first_id);
  TestStreamCreation(second_id, MEDIUM, 0u);
  OnStreamDestruction(second_id);
  TestStreamCreation(third_id, LOWEST, 0u);
}

// Confirm dependencies correct if some requests are completed between before
// next creation.
TEST_F(HttpPriorityDependencyTest, SomeCompletions) {
  const spdy::SpdyStreamId first_id = GetId();
  const spdy::SpdyStreamId second_id = GetId();
  const spdy::SpdyStreamId third_id = GetId();

  TestStreamCreation(first_id, HIGHEST, 0u);
  TestStreamCreation(second_id, MEDIUM, first_id);
  OnStreamDestruction(second_id);
  TestStreamCreation(third_id, LOWEST, first_id);
}

// A more complex example parallel to a simple web page.
TEST_F(HttpPriorityDependencyTest, Complex) {
  const spdy::SpdyStreamId first_id = GetId();
  const spdy::SpdyStreamId second_id = GetId();
  const spdy::SpdyStreamId third_id = GetId();
  const spdy::SpdyStreamId fourth_id = GetId();
  const spdy::SpdyStreamId fifth_id = GetId();
  const spdy::SpdyStreamId sixth_id = GetId();
  const spdy::SpdyStreamId seventh_id = GetId();
  const spdy::SpdyStreamId eighth_id = GetId();
  const spdy::SpdyStreamId nineth_id = GetId();
  const spdy::SpdyStreamId tenth_id = GetId();

  TestStreamCreation(first_id, HIGHEST, 0u);
  TestStreamCreation(second_id, MEDIUM, first_id);
  TestStreamCreation(third_id, MEDIUM, second_id);
  OnStreamDestruction(first_id);
  TestStreamCreation(fourth_id, MEDIUM, third_id);
  TestStreamCreation(fifth_id, LOWEST, fourth_id);
  TestStreamCreation(sixth_id, MEDIUM, fourth_id);
  OnStreamDestruction(third_id);
  TestStreamCreation(seventh_id, MEDIUM, sixth_id);
  TestStreamCreation(eighth_id, LOW, seventh_id);
  OnStreamDestruction(second_id);
  OnStreamDestruction(fourth_id);
  OnStreamDestruction(fifth_id);
  OnStreamDestruction(sixth_id);
  OnStreamDestruction(seventh_id);
  TestStreamCreation(nineth_id, MEDIUM, 0u);
  TestStreamCreation(tenth_id, HIGHEST, 0u);
}

// Confirm dependencies correct after updates with just one stream.
// All updates are no-ops.
TEST_F(HttpPriorityDependencyTest, UpdateSingleStream) {
  const spdy::SpdyStreamId id = GetId();

  TestStreamCreation(id, HIGHEST, 0);

  std::vector<ExpectedDependencyUpdate> empty;
  TestStreamUpdate(id, HIGHEST, empty);
  TestStreamUpdate(id, MEDIUM, empty);
  TestStreamUpdate(id, LOWEST, empty);
  TestStreamUpdate(id, HIGHEST, empty);
}

// Confirm dependencies correct after updates with three streams.
TEST_F(HttpPriorityDependencyTest, UpdateThreeStreams) {
  const spdy::SpdyStreamId first_id = GetId();
  const spdy::SpdyStreamId second_id = GetId();
  const spdy::SpdyStreamId third_id = GetId();

  TestStreamCreation(first_id, HIGHEST, 0);
  TestStreamCreation(second_id, MEDIUM, first_id);
  TestStreamCreation(third_id, LOWEST, second_id);

  const int highest_weight = spdy::Spdy3PriorityToHttp2Weight(HIGHEST);
  const int medium_weight = spdy::Spdy3PriorityToHttp2Weight(MEDIUM);
  const int lowest_weight = spdy::Spdy3PriorityToHttp2Weight(LOWEST);

  std::vector<ExpectedDependencyUpdate> empty;

  // no-op: still at top.
  TestStreamUpdate(first_id, HIGHEST, empty);

  // no-op: still below first.
  TestStreamUpdate(second_id, MEDIUM, empty);

  // no-op: still below second.
  TestStreamUpdate(third_id, LOWEST, empty);

  // second moves to top, first moves below second.
  TestStreamUpdate(
      first_id, MEDIUM,
      {{second_id, 0, medium_weight}, {first_id, second_id, medium_weight}});

  // third moves to top.
  TestStreamUpdate(third_id, HIGHEST, {{third_id, 0, highest_weight}});

  // third moves to bottom.
  TestStreamUpdate(
      third_id, LOWEST,
      {{second_id, 0, medium_weight}, {third_id, first_id, lowest_weight}});

  // first moves to top.
  TestStreamUpdate(
      first_id, HIGHEST,
      {{third_id, second_id, lowest_weight}, {first_id, 0, highest_weight}});
}

// A more complex example parallel to a simple web page with pushed responses.
TEST_F(HttpPriorityDependencyTest, UpdateComplex) {
  const spdy::SpdyStreamId first_id = GetId();
  const spdy::SpdyStreamId second_id = GetId();  // pushed
  const spdy::SpdyStreamId third_id = GetId();   // pushed
  const spdy::SpdyStreamId fourth_id = GetId();
  const spdy::SpdyStreamId fifth_id = GetId();
  const spdy::SpdyStreamId sixth_id = GetId();
  const spdy::SpdyStreamId seventh_id = GetId();

  TestStreamCreation(first_id, HIGHEST, 0u);
  TestStreamCreation(second_id, LOWEST, first_id);
  TestStreamCreation(third_id, LOWEST, second_id);
  TestStreamCreation(fourth_id, HIGHEST, first_id);
  TestStreamCreation(fifth_id, MEDIUM, fourth_id);
  TestStreamCreation(sixth_id, MEDIUM, fifth_id);
  TestStreamCreation(seventh_id, LOW, sixth_id);

  const int highest_weight = spdy::Spdy3PriorityToHttp2Weight(HIGHEST);
  const int medium_weight = spdy::Spdy3PriorityToHttp2Weight(MEDIUM);
  const int lowest_weight = spdy::Spdy3PriorityToHttp2Weight(LOWEST);

  // second matches a HIGHEST priority response.
  // 3 moves under 7
  // 2 moves under 4
  TestStreamUpdate(second_id, HIGHEST,
                   {{third_id, seventh_id, lowest_weight},
                    {second_id, fourth_id, highest_weight}});

  // third matches a MEDIUM priority response.
  // 3 moves under 6
  TestStreamUpdate(third_id, MEDIUM, {{third_id, sixth_id, medium_weight}});
}

}  // namespace net


text:
TwitchModel
===========

TwitchModel is a Twitch API to [ThingModel](https://github.com/SINTEF-9012/ThingModel) adapter.


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Projects_model extends CI_Model {
	public $_file;
	public $_pic;
	function __construct()
	{
		parent::__construct();
		$this->load->library('authit');
		$this->load->helper(array('authit', 'form', 'url', 'html'));
		$this->config->load('authit');
		$this->load->database();
	}

	public function select_projects($lang = null)
	{
		switch ($lang) {
			case 'en':
				$sql = "SELECT id, pro_name, title, full_text, image_brand, created_date FROM projects";
				break;
			case 'ru':
				$sql = "SELECT id, pro_name, title, full_text, image_brand, created_date FROM ru_projects";
				break;
			case 'kg':
				$sql = "SELECT id, pro_name, title, full_text, image_brand, created_date FROM kg_projects";
				break;
			default:
				echo "

";
				break;
		}
		$query = $this->db->query($sql);
		$result = $query->result();
		return $result;
	}
	public function select_projects_for_edit()
	{
		$sql = "SELECT id, pro_name, title, full_text, image_brand, created_date FROM projects";
		$query = $this->db->query($sql);
		$result = $query->result();
		return $result;
	}
	public function select_projects_for_edit_ru()
	{
		$sql = "SELECT id, pro_name, title, full_text, image_brand, created_date FROM ru_projects";
		$query = $this->db->query($sql);
		$result = $query->result();
		return $result;
	}
	public function select_projects_for_edit_kg()
	{
		$sql = "SELECT id, pro_name, title, full_text, image_brand, created_date FROM kg_projects";
		$query = $this->db->query($sql);
		$result = $query->result();
		return $result;
	}
	public function select_projects_by_id($lang = null, $id)
	{
		switch ($lang) {
			case 'en':
				$sql = "SELECT id, pro_name, title, full_text, image_brand FROM projects WHERE id = " . $this->db->escape($id);
				break;
			case 'ru':
				$sql = "SELECT id, pro_name, title, full_text, image_brand FROM ru_projects WHERE id = " . $this->db->escape($id);
				break;
			case 'kg':
				$sql = "SELECT id, pro_name, title, full_text, image_brand FROM kg_projects WHERE id = " . $this->db->escape($id);
				break;
			default:
				echo "
Error
";
				break;
		}
		$query = $this->db->query($sql);
		$result = $query->result();
		return $result;
	}

	public function new_image()
	{
		$time = time();
		$config['upload_path'] = 'assets/img/projects/';
		$config['allowed_types'] = 'jpg|gif|png';
		$config['file_name'] = $time;
		$config['max_size'] = 1000;
		$config['max_width'] = 1200;
		$config['max_height'] = 800;

		$this->load->library('upload', $config);

		if (! $this->upload->do_upload('userfile')) {
			$error = array('error' => $this->upload->display_errors());
			foreach ($error as $key => $arr) {
				print_r($arr);
			}
			return $error;
		}
		else {
			$this->_pic = $this->upload->data();
		}
	}

	public function alter_project($id, $pro_name, $title, $full_text)
	{
		$time = time();
		if (isset($this->_pic['file_name'])) {
			$file = "SELECT id, image_brand FROM projects WHERE id = " . $this->db->escape($id);
			$query_file = $this->db->query($file);
			$result = $query_file->result();
			foreach ($result as $key => $arr):
				unlink("assets/img/projects/$arr->image_brand");
			endforeach;
			$sql = "UPDATE projects SET pro_name = ". $this->db->escape($pro_name) .", title = ". $this->db->escape($title) .", full_text = ". $this->db->escape($full_text) .", image_brand = ". $this->db->escape($this->_pic['file_name']) .", modified_date = ". $this->db->escape($time) ." ";
		}
		else {
			$sql = "UPDATE projects SET pro_name = ". $this->db->escape($pro_name) .", title = ". $this->db->escape($title) .", full_text = ". $this->db->escape($full_text) .", modified_date = ". $this->db->escape($time) ." ";
		}
		$query = $this->db->query($sql);
		return $query;
	}

	public function do_up()
	{
		$time = time();
		$config['upload_path'] = 'assets/img/projects/';
		$config['allowed_types'] = 'jpg|gif|png';
		$config['file_name'] = $time;
		$config['max_size'] = 1000;
		$config['max_width'] = 1200;
		$config['max_height'] = 800;

		$this->load->library('upload', $config);

		if (! $this->upload->do_upload('userfile')) {
			$error = array('error' => $this->upload->display_errors());
			foreach ($error as $key => $arr) {
				print_r($arr);
			}
			return $error;
		}
		else {
			$this->_file = $this->upload->data();
		}
	}

	public function addProject($name, $title, $full_text, $lang)
	{
		$date = time();
		switch ($lang) {
			case 'en':
				$sql = "INSERT INTO projects (pro_name, title, full_text, image_brand, created_date, modified_date) VALUES (". $this->db->escape($name) .", ". $this->db->escape($title) .", ". $this->db->escape($full_text) .", ". $this->db->escape($this->_file['file_name']) .", ". $this->db->escape($date) .", ". $this->db->escape($date) .")";
				break;
			case 'ru':
				$sql = "INSERT INTO ru_projects (pro_name, title, full_text, image_brand, created_date, modified_date) VALUES (". $this->db->escape($name) .", ". $this->db->escape($title) .", ". $this->db->escape($full_text) .", ". $this->db->escape($this->_file['file_name']) .", ". $this->db->escape($date) .", ". $this->db->escape($date) .")";
				break;
			case 'kg':
				$sql = "INSERT INTO kg_projects (pro_name, title, full_text, image_brand, created_date, modified_date) VALUES (". $this->db->escape($name) .", ". $this->db->escape($title) .", ". $this->db->escape($full_text) .", ". $this->db->escape($this->_file['file_name']) .", ". $this->db->escape($date) .", ". $this->db->escape($date) .")";
				break;
			default:
				echo "

";
				break;
		}
		$query = $this->db->query($sql);
		return $query;
	}

	public function drop_project($lang, $id)
	{
		$file = "SELECT id, image_brand FROM projects WHERE id = " . $this->db->escape($id);
		$query_file = $this->db->query($file);
		$result = $query_file->result();
		foreach ($result as $key => $arr):
			unlink("assets/img/projects/$arr->image_brand");
		endforeach;
		switch ($lang) {
			case 'en':
				$sql = "DELETE FROM projects WHERE id = " . $this->db->escape($id);
				break;
			case 'ru':
				$sql = "DELETE FROM ru_projects WHERE id = " . $this->db->escape($id);
				break;
			case 'kg':
				$sql = "DELETE FROM kg_projects WHERE id = " . $this->db->escape($id);
				break;
			default:
				echo "
Error
";
				break;
		}
		$query = $this->db->query($sql);
		return $query;
	}
}


text:
<?php
namespace Blog\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Doctrine\ORM\EntityManager;

class EntityUsingController extends AbstractActionController
{
    /**
    * @var EntityManager
    */
   protected $entityManager;

    /**
     * Sets the EntityManager
     *
     * @param EntityManager $em
     * @access protected
     * @return PostController
     */
    protected function setEntityManager(EntityManager $em)
    {
        $this->entityManager = $em;
        return $this;
    }

    /**
     * Returns the EntityManager
     *
     * Fetches the EntityManager from ServiceLocator if it has not been initiated
     * and then returns it
     *
     * @access protected
     * @return EntityManager
     */
    protected function getEntityManager()
    {
        if (null === $this->entityManager) {
              $this->setEntityManager($this->getServiceLocator()->get('doctrine.entitymanager.orm_default'));
        }
        return $this->entityManager;
    }
}


text:
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';

Template.itemcontainer.helpers({
  running() {
    // returns the ids of the current running items of the actual user
    return Times.find(
      {
        createdBy: Meteor.userId(),
        end: {
          $not: { $ne: null },
        },
      },
      { fields: { item: 1 } }
    )
      .fetch()
      .map(doc => doc.item);
  },
});


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;

namespace osu.Game.Beatmaps.ControlPoints
{
    public class ControlPoint : IComparable<ControlPoint>, IEquatable<ControlPoint>
    {
        /// <summary>
        /// The time at which the control point takes effect.
        /// </summary>
        public double Time;

        public int CompareTo(ControlPoint other) => Time.CompareTo(other.Time);

        /// <summary>
        /// Whether this <see cref="ControlPoint"/> provides the same parametric changes as another <see cref="ControlPoint"/>.
        /// Basically an equality check without considering the <see cref="Time"/>.
        /// </summary>
        /// <param name="other">The <see cref="ControlPoint"/> to compare to.</param>
        /// <returns>Whether this <see cref="ControlPoint"/> is equivalent to <paramref name="other"/>.</returns>
        public virtual bool EquivalentTo(ControlPoint other) => true;

        public bool Equals(ControlPoint other)
            => EquivalentTo(other) && Time.Equals(other?.Time);
    }
}


text:
@implementation APGAppDelegate

@synthesize window;

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
    return YES;
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{

}

@end


text:
import netCDF4
import time
import os
import getpass
import numpy as np
from subprocess import check_output
from kid_readout.measurement.io import data_block

from kid_readout.settings import BASE_DATA_DIR

class DataFile():
    def __init__(self, base_dir=BASE_DATA_DIR, suffix=''):
        base_dir = os.path.expanduser(base_dir)
        if not os.path.exists(base_dir):
            try:
                os.mkdir(base_dir)
            except Exception, e:
                raise Exception("Tried to make directory %s for data file but failed. Error was %s" % (base_dir,str(e)))
        fn = time.strftime('%Y-%m-%d_%H%M%S')
        if suffix:
            suffix = suffix.replace(' ','_')
            fn += ('_' + suffix)
        fn += '.nc'
        fn = os.path.join(base_dir,fn)
        self.filename = fn
        self.nc = netCDF4.Dataset(fn,mode='w')
        try:
            dname = os.path.split(__file__)[0]
            gitinfo = check_output(("cd %s; git log -1" % dname),shell=True)
        except:
            gitinfo = ''
        self.nc.gitinfo = gitinfo
        self.nc.created_by = getpass.getuser()
        self.sweeps = self.nc.createGroup('sweeps')
        self.timestreams = self.nc.createGroup('timestreams')
        self.cryo = self.nc.createGroup('cryo')
        self.hw_state = self.nc.createGroup('hw_state')
        self.hw_state.createDimension('time',None)
        self.hw_epoch = self.hw_state.createVariable('epoch',np.float64,dimensions=('time',))
        self.hw_adc_atten = self.hw_state.createVariable('adc_atten',np.float32,dimensions=('time',))
        self.hw_dac_atten = self.hw_state.createVariable('dac_atten',np.float32,dimensions=('time',))
        self.hw_ntones = self.hw_state.createVariable('ntones',np.int32,dimensions=('time',))
        self.hw_modulation_rate = self.hw_state.createVariable('modulation_rate',np.int32,dimensions=('time',))
        self.hw_modulation_output = self.hw_state.createVariable('modulation_output',np.int32,dimensions=('time',))

        self.adc_snaps = self.nc.createGroup('adc_snaps')
        self.adc_snaps.createDimension('epoch', None)
        self.adc_snaps.createDimension('adc', 2)
        self.adc_snaps.createDimension('sample', 2**12)
        self.adc_snaps_epoch = self.adc_snaps.createVariable('epoch',np.float64,dimensions=('epoch',))
        self.adc_snaps_data = self.adc_snaps.createVariable('data',np.float32,dimensions=('epoch','adc','sample'))

        self.c128 = np.dtype([('real','f8'),('imag','f8')])
        self.cdf128 = self.nc.createCompoundType(self.c128, 'complex128')
        self.c64 = np.dtype([('real','f4'),('imag','f4')])
        self.cdf64 = self.nc.createCompoundType(self.c64, 'complex64')

    def close(self):
        self.nc.close()
    def sync(self):
        self.nc.sync()
    def log_hw_state(self,ri):
        idx = len(self.hw_state.dimensions['time'])
        t0 = time.time()
        self.hw_epoch[idx] = t0
        self.hw_adc_atten[idx] = ri.adc_atten
        self.hw_dac_atten[idx] = ri.dac_atten
        self.hw_ntones[idx] = ri.tone_bins.shape[1]
        self.hw_modulation_rate[idx] = ri.modulation_rate
        self.hw_modulation_output[idx] = ri.modulation_output
        if not 'boffile' in self.nc.ncattrs():
            self.nc.boffile = ri.boffile
        if not 'heterodyne' in self.nc.ncattrs():
            self.nc.heterodyne = np.uint8(ri.heterodyne)

    def log_adc_snap(self,ri):
        t0 = time.time()
        idx = len(self.adc_snaps.dimensions['epoch'])
        x,y = ri.get_raw_adc()
        self.adc_snaps_epoch[idx] = t0
        self.adc_snaps_data[idx,0,:] = x
        self.adc_snaps_data[idx,1,:] = y

    def add_sweep(self, sweep_data):
        name = time.strftime('sweep_%Y%m%d%H%M%S')
        swg = self.sweeps.createGroup(name)
        swg.createDimension('frequency',None)
        freq = swg.createVariable('frequency',np.float64,('frequency',))
        s21 = swg.createVariable('s21',self.cdf128,('frequency',))
        index = swg.createVariable('index',np.int32,('frequency',))
        freq[:] = sweep_data.freqs
        s21[:] = sweep_data.data.astype('complex128').view(self.c128)
        index[:] = sweep_data.sweep_indexes

        dbg = swg.createGroup('datablocks')
        dbg.createDimension('epoch',None)
        dbg.createDimension('sample',sweep_data.blocks[0].data.shape[0])
        t0 = dbg.createVariable('epoch',np.float64,('epoch',))
        tone = dbg.createVariable('tone',np.int32,('epoch',))
        nsamp = dbg.createVariable('nsamp',np.int32,('epoch',))
        fftbin = dbg.createVariable('fftbin',np.int32,('epoch',))
        nfft = dbg.createVariable('nfft',np.int32,('epoch',))
        dt = dbg.createVariable('dt',np.float64,('epoch',))
        fs = dbg.createVariable('fs',np.float64,('epoch',))
        lo = dbg.createVariable('lo',np.float64,('epoch',))
        wavenorm = dbg.createVariable('wavenorm',np.float64,('epoch'))
        data = dbg.createVariable('data',self.cdf64,('epoch','sample'))
        sweep_index = dbg.createVariable('sweep_index',np.int32,('epoch'))

        blocks = sweep_data.blocks
        blen = blocks[0].data.shape[0]
        blocklist = []
        for blk in blocks:
            if blk.data.shape[0] >= blen:
                blocklist.append(blk.data[None,:blen])
            else:
                newblk = np.zeros((1,blen),dtype=blk.data.dtype)
                newblk[0,:blk.data.shape[0]] = blk.data[:]
                blocklist.append(newblk)
        data[:] = np.concatenate(blocklist,axis=0).astype('complex64').view(self.c64)
        fs[:] = np.array([x.fs for x in blocks])
        lo[:] = np.array([x.lo for x in blocks])
        t0[:] = np.array([x.t0 for x in blocks])
        tone[:] = np.array([x.tone for x in blocks])
        nfft[:] = np.array([x.nfft for x in blocks])
        wavenorm[:] = np.array([x.wavenorm for x in blocks])
        nsamp[:] = np.array([x.nsamp for x in blocks])
        dt[:] = np.array([x.dt for x in blocks])
        fftbin[:] = np.array([x.fftbin for x in blocks])
        sweep_index[:] = np.array([x.sweep_index for x in blocks])

        return name

    def add_timestream_data(self, data, ri, t0, tsg=None, mmw_source_freq=0.0, mmw_source_modulation_freq=0.0,
                            zbd_voltage=0.0, zbd_power_dbm=0.0):
        chids = ri.fpga_fft_readout_indexes+1
        tones = ri.tone_bins[ri.bank,ri.readout_selection]
        nsamp = ri.tone_nsamp
        for m in range(len(chids)):
            block = data_block.DataBlock(data = data[:,m], tone=tones[m], fftbin = chids[m],
                     nsamp = nsamp, nfft = ri.nfft, wavenorm = ri.wavenorm, t0 = t0, fs = ri.fs,
                     mmw_source_freq=mmw_source_freq, mmw_source_modulation_freq=mmw_source_modulation_freq,
                     zbd_voltage=zbd_voltage, zbd_power_dbm=zbd_power_dbm, lo=ri.lo_frequency, heterodyne=ri.heterodyne)
            tsg = self.add_block_to_timestream(block, tsg=tsg)
        return tsg

    def add_block_to_timestream(self, block, tsg = None):
        if tsg is not None and tsg.variables['data'].shape[1] != block.data.shape[0]:
            print "Warning! Timestream data cannot be added to", tsg.path, "because dimension does not agree."
            print "New timestream group will be created"
            tsg = None
        if tsg is None:
            name = time.strftime('timestream_%Y%m%d%H%M%S')
            tsg = self.timestreams.createGroup(name)
            tsg.createDimension('epoch',None)
            tsg.createDimension('sample',block.data.shape[0])
            t0 = tsg.createVariable('epoch',np.float64,('epoch',))
            tone = tsg.createVariable('tone',np.int32,('epoch',))
            nsamp = tsg.createVariable('nsamp',np.int32,('epoch',))
            fftbin = tsg.createVariable('fftbin',np.int32,('epoch',))
            nfft = tsg.createVariable('nfft',np.int32,('epoch',))
            dt = tsg.createVariable('dt',np.float64,('epoch',))
            fs = tsg.createVariable('fs',np.float64,('epoch',))
            lo = tsg.createVariable('lo',np.float64,('epoch',))
            wavenorm = tsg.createVariable('wavenorm',np.float64,('epoch'))
            mmw_source_freq = tsg.createVariable('mmw_source_freq',np.float64,('epoch'))
            mmw_source_modulation_freq = tsg.createVariable('mmw_source_modulation_freq',np.float64,('epoch'))
            zbd_voltage = tsg.createVariable('zbd_voltage',np.float64,('epoch'))
            zbd_power_dbm = tsg.createVariable('zbd_power_dbm',np.float64,('epoch'))
            sweep_index = tsg.createVariable('sweep_index',np.int32,('epoch'))
            data = tsg.createVariable('data',self.cdf64,('epoch','sample'))
        else:
            t0 = tsg.variables['epoch']
            tone = tsg.variables['tone']
            nsamp = tsg.variables['nsamp']
            fftbin = tsg.variables['fftbin']
            nfft = tsg.variables['nfft']
            dt = tsg.variables['dt']
            fs = tsg.variables['fs']
            lo = tsg.variables['lo']
            wavenorm = tsg.variables['wavenorm']
            mmw_source_freq = tsg.variables['mmw_source_freq']
            mmw_source_modulation_freq = tsg.variables['mmw_source_modulation_freq']
            zbd_voltage = tsg.variables['zbd_voltage']
            zbd_power_dbm = tsg.variables['zbd_power_dbm']
            sweep_index = tsg.variables['sweep_index']
            data = tsg.variables['data']
        idx = len(tsg.dimensions['epoch'])
        data[idx] = block.data.astype('complex64').view(self.c64)
        t0[idx] = block.t0
        fs[idx] = block.fs
        lo[idx] = block.lo
        tone[idx] = block.tone
        nsamp[idx] = block.nsamp
        fftbin[idx] = block.fftbin
        nfft[idx] = block.nfft
        wavenorm[idx] = block.wavenorm
        dt[idx] = block.dt
        mmw_source_freq[idx] = block.mmw_source_freq
        mmw_source_modulation_freq[idx] = block.mmw_source_modulation_freq
        zbd_power_dbm[idx] = block.zbd_power_dbm
        zbd_voltage[idx] = block.zbd_voltage
        sweep_index[idx] = block.sweep_index
        return tsg

    def add_cryo_data(self,cryod):
        if not self.cryo.variables:
            self.cryo.createDimension('epoch',None)
            self.cryo.createDimension('input', 4)
            for name,val in cryod.items():
                if type(val) is list:
                    self.cryo.createVariable(name,np.float64,('epoch','input'))
                else:
                    self.cryo.createVariable(name,np.float64,('epoch',))
        idx = len(self.cryo.dimensions['epoch'])
        for name,val in cryod.items():
            if type(val) is list:
                self.cryo.variables[name][idx] = val[:]
            else:
                self.cryo.variables[name][idx] = val