text:
package org.mybatis.spring;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.sql.SQLException;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.dao.support.PersistenceExceptionTranslator;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.mockrunner.mock.jdbc.MockConnection;
import com.mockrunner.mock.jdbc.MockResultSet;

/**
 *
 *
 * @version $Id$
 */
public abstract class AbstractMyBatisSpringTest {

  protected static PooledMockDataSource dataSource = new PooledMockDataSource();

  protected static SqlSessionFactory sqlSessionFactory;

  protected static ExecutorInterceptor executorInterceptor = new ExecutorInterceptor();

  protected static DataSourceTransactionManager txManager;

  protected static PersistenceExceptionTranslator exceptionTranslator;

  protected MockConnection connection;

  protected MockConnection connectionTwo;

  @BeforeClass
  public static void setupBase() throws Exception {
    // create an SqlSessionFactory that will use SpringManagedTransactions
    SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
    factoryBean.setMapperLocations(new Resource[] { new ClassPathResource("org/mybatis/spring/TestMapper.xml") });
    // note running without SqlSessionFactoryBean.configLocation set => default configuration
    factoryBean.setDataSource(dataSource);
    factoryBean.setPlugins(new Interceptor[] { executorInterceptor });

    exceptionTranslator = new MyBatisExceptionTranslator(dataSource, true);

    sqlSessionFactory = factoryBean.getObject();

    txManager = new DataSourceTransactionManager(dataSource);
  }

  protected void assertNoCommit() {
    assertNoCommitJdbc();
    assertNoCommitSession();
  }

  protected void assertNoCommitJdbc() {
    assertEquals("should not call commit on Connection", 0, connection.getNumberCommits());
    assertEquals("should not call rollback on Connection", 0, connection.getNumberRollbacks());
  }

  protected void assertNoCommitSession() {
    assertEquals("should not call commit on SqlSession", 0, executorInterceptor.getCommitCount());
    assertEquals("should not call rollback on SqlSession", 0, executorInterceptor.getRollbackCount());
  }

  protected void assertCommit() {
    assertCommitJdbc();
    assertCommitSession();
  }

  protected void assertCommitJdbc() {
    assertEquals("should call commit on Connection", 1, connection.getNumberCommits());
    assertEquals("should not call rollback on Connection", 0, connection.getNumberRollbacks());
  }

  protected void assertCommitSession() {
    assertEquals("should call commit on SqlSession", 1, executorInterceptor.getCommitCount());
    assertEquals("should not call rollback on SqlSession", 0, executorInterceptor.getRollbackCount());
  }

  protected void assertRollback() {
    assertEquals("should not call commit on Connection", 0, connection.getNumberCommits());
    assertEquals("should call rollback on Connection", 1, connection.getNumberRollbacks());
    assertEquals("should not call commit on SqlSession", 0, executorInterceptor.getCommitCount());
    assertEquals("should call rollback on SqlSession", 1, executorInterceptor.getRollbackCount());
  }

  protected void assertSingleConnection() {
    assertEquals("should only call DataSource.getConnection() once", 1, dataSource.getConnectionCount());
  }

  protected void assertExecuteCount(int count) {
    assertEquals("should have executed " + count + " SQL statements", count, connection
        .getPreparedStatementResultSetHandler().getExecutedStatements().size());
  }

  protected void assertConnectionClosed(MockConnection connection) {
    try {
      if ((connection != null) && !connection.isClosed()) {
        fail("Connection is not closed");
      }
    } catch (SQLException sqle) {
      fail("cannot call Connection.isClosed() " + sqle.getMessage());
    }
  }

  protected MockConnection createMockConnection() {
    // this query must be the same as the query in TestMapper.xml
    MockResultSet rs = new MockResultSet("SELECT 1");
    rs.addRow(new Object[] { 1 });

    MockConnection con = new MockConnection();
    con.getPreparedStatementResultSetHandler().prepareResultSet("SELECT 1", rs);

    return con;
  }

  /*
   * Setup a new Connection before each test since its closed state will need to be checked
   * afterwards and there is no Connection.open().
   */
  @Before
  public void setupConnection() throws SQLException {
    dataSource.reset();
    connection = createMockConnection();
    connectionTwo = createMockConnection();
    dataSource.addConnection(connectionTwo);
    dataSource.addConnection(connection);
  }

  @Before
  public void resetExecutorInterceptor() {
    executorInterceptor.reset();
  }

  @After
  public void validateConnectionClosed() {
    assertConnectionClosed(connection);

    connection = null;
  }

}


text:
package com.replica.replicaisland;

/**
 * CollisionParamaters defines global parameters related to dynamic (object vs object) collisions.
 */
public final class CollisionParameters {
    // HitType describes the type of hit that a victim object receives.  Victims may choose to
    // react differently to the intersection depending on the hit type.
	// TODO: Make this a bit field so that objects can support multiple hit types.
    public final class HitType {
        public final static int INVALID = 0;    // No type.
        public final static int HIT = 1;        // Standard hit type.  Life is reduced by 1.
        public final static int DEATH = 2;      // Causes instant death.
        public final static int COLLECT = 3;    // Causes collectable objects to be collected by the attacker.
        public final static int POSSESS = 4;    // Causes possessable objects to become possessed.
        public final static int DEPRESS = 5;    // A hit indicating that the attacker is pressing into the victim.
        public final static int LAUNCH = 6;     // A hit indicating that the attacker will launch the victim.
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace adapter;

use Exception;

/**
 * 音频设备实体
 */
class AudioPlayer implements MediaInterface
{
  public function play($file='', $type='')
  {
    switch ($type) {
      case 'mp3':
        echo 'playing file: ' . $file . ".mp3\n";
        break;
      case 'mp4':
        $adapter = new Adapter($type);
        $adapter->play($file);
        break;
      case 'wma':
        $adapter = new Adapter($type);
        $adapter->play($file);
        break;

      default:
        throw new Exception("$type is not supported", 400);
        break;
    }

  }
}


text:
using ApprovalTests.Persistence;
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;

namespace project.src
{
    public class Document
    {
        private Font currentFont;
        private Backgrounder Backgrounder { get; set; }

        public void Applesauce(Font newFont)
        {
            currentFont = newFont;

            var request = Api.Put($"user/{Session.Current.User.Id}/preferences/")
                .SetData($"{{\"font\":\"{newFont.Name}\"}}");

            Backgrounder.Monitor($"Document.SetFont({newFont.Name})",
                request.SendAsync(),
                LocalDb.ExecuteAsync("UPDATE Preferences SET Font = $0 WHERE UserId = $1", newFont.Name, Session.Current.User.Id)
            );
        }
    }
}


text:
<?php

namespace NetSuite\Classes;

class GetResponse {
    public $readResponse;
    static $paramtypesmap = array(
        "readResponse" => "ReadResponse",
    );
}


text:
package substitute.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public final class PropertiesUtils {

    private static Properties properties = new Properties();

    public static void load(final String fileName) throws FileNotFoundException, IOException {
        String baseDir = PropertiesUtils.class.getResource("/").getPath();
        FileInputStream inputStream = new FileInputStream(new File(baseDir.concat(fileName)));
        properties.load(inputStream);
        inputStream.close();
    }

    static {
        try {
            PropertiesUtils.load("/config.properties");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getValue(final String key) {
        return properties.getProperty(key);
    }
}


text:
use std::collections::HashMap;

#[derive(Debug, Clone)]
enum Token {
    // Arithmetic
    Plus, Minus, Star, Slash, Div,
    // Grouping
    LParen, RParen,
    // Keywords
    Begin, End, Program, Var, Integer, Real,
    // Punctuation
    Dot, Semi, Assign, Colon, Comma,
    // Literals
    IntegerLiteral(i32), RealLiteral(f64),
    // Identifiers
    Id(String),
}

#[derive(Debug)]
struct Lexer {
    source: Vec<char>,
    position: usize,
}

impl Lexer {
    fn new(source: String) -> Lexer {
        Lexer {
            source: source.chars().collect(),
            position: 0,
        }
    }

    fn done(&self) -> bool {
        self.position >= self.source.len()
    }

    fn advance(&mut self) {
        self.position += 1;
    }

    fn string(&self, start: usize, end: usize) -> String {
        (&self.source[start..end]).to_vec().into_iter().collect()
    }

    fn next_char_is<P>(&self, pred: P) -> bool where P: Fn(char) -> bool {
        if self.position + 1 < self.source.len() {
            pred(self.source[self.position + 1])
        } else {
            false
        }
    }

    fn char(&mut self) -> Option<char> {
        if !self.done() {
            Some(self.source[self.position])
        } else {
            None
        }
    }

    fn skip_whitespace(&mut self) {
        while !self.done() && self.source[self.position].is_whitespace() {
            self.advance();
        }
    }

    fn skip_comment(&mut self) {
        while !self.done() && self.source[self.position] != '}' {
            self.advance();
        }
        self.advance();
    }

    fn number(&mut self) -> Token {
        let start = self.position;
        while self.next_char_is(|c| c.is_digit(10)) {
            self.advance();
        }
        if self.next_char_is(|c| c == '.') {
            self.advance();
            while self.next_char_is(|c| c.is_digit(10)) {
                self.advance();
            }
            Token::RealLiteral(
                self.string(start, self.position + 1).parse::<f64>().unwrap())
        } else {
            Token::IntegerLiteral(
                self.string(start, self.position + 1).parse::<i32>().unwrap())
        }

    }

    fn word(&mut self) -> Token {
        use std::ascii::AsciiExt;

        let start = self.position;
        while self.next_char_is(|c| c.is_alphanumeric() && c.is_ascii()) {
            self.advance();
        }

        let word = self.string(start, self.position + 1).to_lowercase();
        match word.as_ref() {
            "begin"   => Token::Begin,
            "div"     => Token::Div,
            "end"     => Token::End,
            "integer" => Token::Integer,
            "program" => Token::Program,
            "real"    => Token::Real,
            "var"     => Token::Var,
            _         => Token::Id(word),
        }
    }

    fn get_next_token(&mut self) -> Option<Token> {
        self.skip_whitespace();

        // Skip comments
        while let Some('{') = self.char() {
            self.skip_comment();
            self.skip_whitespace();
        }

        if self.done() { return None; }

        let token = match self.char().unwrap() {
            '+' => Token::Plus,
            '-' => Token::Minus,
            '*' => Token::Star,
            '/' => Token::Slash,
            '(' => Token::LParen,
            ')' => Token::RParen,
            '.' => Token::Dot,
            ';' => Token::Semi,
            ',' => Token::Comma,

            ':' if self.next_char_is(|c| c == '=') => { self.advance(); Token::Assign }
            ':' => Token::Colon,

            '0'...'9' => self.number(),

            'a'...'z' | 'A'...'Z' | '_' => self.word(),

             c => panic!("Error: unexpected character: '{}'.", c),
        };
        self.advance();
        Some(token)
    }
}

/// program : PROGRAM variable SEMI block DOT
/// block : declarations compound_statement
/// declarations : VAR (variable_declarations SEMI)+
///              | empty
/// variable_declarations : ID (COMMA ID)* COLON type_specifier
/// type_specifier : INTEGER | REAL
/// compound_statement : BEGIN statements END
/// statements : statement (SEMI statements)*
/// statement : compound_statement
///           | assignment_statement
///           | empty
/// assignment_statement : variable ASSIGN expression
/// variable : ID
/// empty :
///
/// expression : term ((PLUS | MINUS) term)*
/// term : factor ((STAR | DIV | SLASH) factor)*
/// factor : (PLUS | MINUS) factor
///        | INTEGERLITERAL
///        | REALLITERAL
///        | LPAREN expression RPAREN
///        | variable

#[derive(Debug, Clone)]
enum AST {
    Program { name: Box<AST>, block: Box<AST> },
    Block { declarations: Vec<Box<AST>>, compound_statement: Box<AST> },
    VariableDeclaration { name: String, type_specifier: Box<AST> },
    TypeSpecifier (Token),
    CompoundStatement (Vec<Box<AST>>),
    AssignmentStatement { lhs: Box<AST>, rhs: Box<AST> },
    Variable (String),
    Empty,
    BinaryOperator { lhs: Box<AST>, op: Token, rhs: Box<AST> },
    UnaryOperator { op: Token, rhs: Box<AST> },
    Integer (i32),
    Real (f64),
}

#[derive(Debug)]
struct Parser {
    lexer: Lexer,
    current_token: Option<Token>,
}

impl Parser {
    fn new(source: String) -> Parser {
        let mut l = Lexer::new(source);
        let t = l.get_next_token();
        Parser {
            lexer: l,
            current_token: t,
        }
    }

    fn advance(&mut self) {
        self.current_token = self.lexer.get_next_token();
    }

    fn parse(&mut self) -> AST {
        let ast = self.program();
        match self.current_token {
            None => (),
            _ => panic!("Error: tokens remain after parsing."),
        }
        ast
    }

    /// program : PROGRAM variable SEMI block DOT
    fn program(&mut self) -> AST {
        match self.current_token {
            Some(Token::Program) => self.advance(),
            ref t => panic!("Error: expected a Program found a {:?}", t),
        };
        let name = self.variable();
        match self.current_token {
            Some(Token::Semi) => self.advance(),
            ref t => panic!("Error: expected a Semi found a {:?}", t),
        };
        let block = self.block();
        match self.current_token {
            Some(Token::Dot) => self.advance(),
            ref t => panic!("Error: expected a Dot found a {:?}", t),
        };
        AST::Program{name: Box::new(name), block: Box::new(block)}
    }

    /// block : declarations compound_statement
    fn block(&mut self) -> AST {
        AST::Block {
            declarations: self.declarations(),
            compound_statement: Box::new(self.compound_statement()),
        }
    }

    /// declarations : VAR (variable_declarations SEMI)+
    ///              | empty
    fn declarations(&mut self) -> Vec<Box<AST>> {
        let mut declarations: Vec<Box<AST>> = Vec::new();
        match self.current_token {
            Some(Token::Var) => {
                self.advance();
                while let Some(Token::Id(_)) = self.current_token {
                    declarations.extend(self.variable_declarations());
                    match self.current_token {
                        Some(Token::Semi) => self.advance(),
                        ref t => panic!("Error: expected a Semi found a {:?}", t),
                    }
                }
            }
            _ => (),
        };
        declarations
    }

    /// variable_declarations : ID (COMMA ID)* COLON type_specifier
    fn variable_declarations(&mut self) -> Vec<Box<AST>> {
        let mut ids: Vec<String> = Vec::new();
        match self.current_token {
            Some(Token::Id(ref s)) => ids.push(s.clone()),
            ref t => panic!("Error: expected an Id found a {:?}", t),
        }
        self.advance();
        while let Some(Token::Comma) = self.current_token {
            self.advance();
            match self.current_token {
                Some(Token::Id(ref s)) => ids.push(s.clone()),
                ref t => panic!("Error: expected an Id found a {:?}", t),
            }
            self.advance();
        }
        match self.current_token {
            Some(Token::Colon) => self.advance(),
            ref t => panic!("Error: expected a Colon found a {:?}", t),
        }
        let type_specifier = self.type_specifier();
        ids.into_iter().map(|s| Box::new(AST::VariableDeclaration{
            name: s,
            type_specifier: Box::new(type_specifier.clone()),
        })).collect()
    }

    /// type_specifier : INTEGER | REAL
    fn type_specifier(&mut self) -> AST {
        match self.current_token {
            // Some(Token::IntegerLiteral(int)) => { self.advance(); AST::Integer(int) }
            // Some(Token::RealLiteral(real)) => { self.advance(); AST::Real(rea
            Some(Token::Integer) => { self.advance(); AST::TypeSpecifier(Token::Integer) }
            Some(Token::Real)    => { self.advance(); AST::TypeSpecifier(Token::Real) }
            ref t => panic!("Error: expected a type_specifier found a {:?}", t),
        }
    }

    /// compound_statement : BEGIN statements END
    fn compound_statement(&mut self) -> AST {
        match self.current_token {
            Some(Token::Begin) => self.advance(),
            ref t => panic!("Error: expected a Begin found a {:?}", t),
        };
        let ast = AST::CompoundStatement(self.statements());
        match self.current_token {
            Some(Token::End) => self.advance(),
            ref t => panic!("Error: expected a End found a {:?}", t),
        };
        ast
    }

    /// statements : statement (SEMI statements)*
    fn statements(&mut self) -> Vec<Box<AST>> {
        let mut stmts = vec![Box::new(self.statement())];
        loop {
            match self.current_token {
                Some(Token::Semi) => {
                    self.advance();
                    stmts.push(Box::new(self.statement()))
                }
                _ => break,
            }
        }
        stmts
    }

    /// statement : compound_statement
    ///           | assignment_statement
    ///           | empty
    fn statement(&mut self) -> AST {
        match self.current_token {
            Some(Token::Begin) => self.compound_statement(),
            Some(Token::Id(_)) => self.assignment_statement(),
            _ => self.empty(),
        }
    }

    /// assignment_statement : variable ASSIGN expression
    fn assignment_statement(&mut self) -> AST {
        let lhs = self.variable();
        match self.current_token {
            Some(Token::Assign) => self.advance(),
            ref t => panic!("Error: expected an Assign found a {:?}", t),
        };
        AST::AssignmentStatement{lhs: Box::new(lhs), rhs: Box::new(self.expression())}
    }

    /// variable : ID
    fn variable(&mut self) -> AST {
        let ast = match self.current_token {
            Some(Token::Id(ref s)) => AST::Variable(s.clone()),
            ref t => panic!("Error: expected a Variable found a {:?}", t),
        };
        self.advance();
        ast
    }

    /// empty :
    fn empty(&mut self) -> AST {
        AST::Empty
    }

    /// expression : term ((PLUS | MINUS) term)*
    fn expression(&mut self) -> AST {
        let mut ast = self.term();

        loop {
            match self.current_token {
                Some(Token::Plus)  => (),
                Some(Token::Minus) => (),
                _ => break,
            }
            let token = self.current_token.clone().unwrap();
            self.advance();
            ast = AST::BinaryOperator {
                lhs: Box::new(ast), op: token, rhs: Box::new(self.term())
            };
        }
        ast
    }

    /// term : factor ((STAR | DIV | SLASH) factor)*
    fn term(&mut self) -> AST {
        let mut ast = self.factor();

        loop {
            match self.current_token {
                Some(Token::Star)  => (),
                Some(Token::Div)   => (),
                Some(Token::Slash) => (),
                _ => break,
            }
            let token = self.current_token.clone().unwrap();
            self.advance();
            ast = AST::BinaryOperator {
                lhs: Box::new(ast), op: token, rhs: Box::new(self.factor())
            };
        }
        ast
    }

    /// factor : (PLUS | MINUS) factor
    ///        | INTEGERLITERAL
    ///        | REALLITERAL
    ///        | LPAREN expression RPAREN
    ///        | variable
    fn factor(&mut self) -> AST {
        match self.current_token {
            Some(Token::Plus) | Some(Token::Minus) => {
                let token = self.current_token.clone().unwrap();
                self.advance();
                AST::UnaryOperator{op: token, rhs: Box::new(self.factor())}
            }

            Some(Token::IntegerLiteral(i)) => {
                self.advance();
                AST::Integer(i)
            }

            Some(Token::RealLiteral(r)) => {
                self.advance();
                AST::Real(r)
            }

            Some(Token::LParen) => {
                self.advance();
                let paren_ast = self.expression();
                match self.current_token {
                    Some(Token::RParen) => { self.advance(); paren_ast }
                    ref t => panic!("Error: expected an RParen found a {:?}", t),
                }
            }

            Some(Token::Id(_)) => self.variable(),

            ref t => panic!("Error: expected an integer and found a '{:?}'.", t),
        }
    }
}

#[derive(Debug)]
struct Interpreter {
    parser: Parser,
    global_scope: HashMap<String, i32>,
}

impl Interpreter {
    fn new(source: String) -> Interpreter {
        Interpreter {
            parser: Parser::new(source),
            global_scope: HashMap::new(),
        }
    }

    // Program { name: Box<AST>, block: Box<AST> },
    // Block { declarations: Vec<Box<AST>>, compound_statement: Box<AST> },
    // VariableDeclaration { name: String, type_specifier: Box<AST> },
    // TypeSpecifier (Token),
    // CompoundStatement (Vec<Box<AST>>),
    // AssignmentStatement { lhs: Box<AST>, rhs: Box<AST> },
    // Empty,
    fn visit(&mut self, ast: AST) {
        match ast {
            AST::Program{name, block} => self.visit(*block),
            AST::Block{declarations, compound_statement} => {
                for vardec in declarations {
                    self.visit(*vardec)
                }
                self.visit(*compound_statement);
            }
            AST::VariableDeclaration{name, type_specifier} => (),
            AST::CompoundStatement(children) => {
                for child in children {
                    self.visit(*child);
                }
            }
            AST::AssignmentStatement{lhs, rhs} => match *lhs {
                AST::Variable(s) => {
                    let val = self.evaluate(*rhs);
                    self.global_scope.insert(s, val);
                }
                ref t => panic!("Error: expected variable and found {:?}", t),
            },
            AST::Empty => (),

            ref t => panic!("Error: expected statement and found {:?}", t),
        }
    }

    // BinaryOperator { lhs: Box<AST>, op: Token, rhs: Box<AST> },
    // UnaryOperator { op: Token, rhs: Box<AST> },
    // Variable (String),
    // Integer (i32),
    // Real (f64),
    fn evaluate(&self, ast: AST) -> i32 {
        match ast {
            AST::BinaryOperator{lhs, op, rhs} => match op {
                Token::Plus  => self.evaluate(*lhs) + self.evaluate(*rhs),
                Token::Minus => self.evaluate(*lhs) - self.evaluate(*rhs),
                Token::Star  => self.evaluate(*lhs) * self.evaluate(*rhs),
                Token::Div   => self.evaluate(*lhs) / self.evaluate(*rhs),
                Token::Slash => self.evaluate(*lhs) / self.evaluate(*rhs),
                _ => panic!("Error: expected arithmetic operator and found '{:?}'.", op),
            },
            AST::UnaryOperator{op, rhs} => match op {
                Token::Plus  => self.evaluate(*rhs),
                Token::Minus => -self.evaluate(*rhs),
                _ => panic!("Error: expected a '+' or '-' and found '{:?}'.", op),
            },
            AST::Variable(name) => match self.global_scope.get(&name) {
                Some(val) => *val,
                None => panic!("Error: the variable {} is undefined", name),
            },
            AST::Integer(i) => i,
            AST::Real(r) => r as i32,
            ref t => panic!("Error: expected an evaluatable expression found {:?}", t),
        }
    }

    fn interpret(&mut self) {
        let ast = self.parser.parse();
        self.visit(ast);
        println!("{:#?}", self.global_scope);
    }
}

fn main() {
    use std::env;

    let args: Vec<String> = env::args().collect();
    match args.len() {
        1 => run_prompt(),
        2 => run_file(&args[1]),
        _ => println!("Usage: rs_interpreter [script]")
    }
}

fn run_file(path: &String) {
    use std::fs::File;
    use std::io::Read;

    let mut file = File::open(path).expect("Could not open file");
    let mut file_string = String::new();
    file.read_to_string(&mut file_string).expect("Could not read from file");
    run(file_string);
}

macro_rules! prompt(
    ($($arg:tt)*) => { {
        print!($($arg)*);
        stdout().flush().expect("Could not flush stdout");
    } }
);

fn run_prompt() {
    use std::io::{BufRead, stdin, stdout, Write};

    prompt!("calc> ");
    let stdin = stdin();
    for line in stdin.lock().lines() {
        let mut interpreter = Interpreter::new(line.unwrap());
        interpreter.interpret();
        prompt!("calc> ");
    }
}

fn run(source: String) {
    let mut interpreter = Interpreter::new(source);
    interpreter.interpret();
}


text:
using Esiur.Data;
using Esiur.Core;
using Esiur.Proxy;
using Esiur.Resource.Template;
using Esiur.Security.Permissions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Esiur.Net.IIP;
using System.Text.RegularExpressions;
using Esiur.Misc;
using System.Collections.Concurrent;
using System.Collections;
using System.Data;

namespace Esiur.Resource;

// Centeral Resource Issuer
public static class Warehouse
{
    //static byte prefixCounter;

    //static AutoList<IStore, Instance> stores = new AutoList<IStore, Instance>(null);
    static ConcurrentDictionary<uint, WeakReference<IResource>> resources = new ConcurrentDictionary<uint, WeakReference<IResource>>();
    static ConcurrentDictionary<IStore, List<WeakReference<IResource>>> stores = new ConcurrentDictionary<IStore, List<WeakReference<IResource>>>();

    static uint resourceCounter = 0;

    static KeyList<TemplateType, KeyList<Guid, TypeTemplate>> templates
        = new KeyList<TemplateType, KeyList<Guid, TypeTemplate>>()
        {
            //[TemplateType.Unspecified] = new KeyList<Guid, TypeTemplate>(),
            [TemplateType.Resource] = new KeyList<Guid, TypeTemplate>(),
            [TemplateType.Record] = new KeyList<Guid, TypeTemplate>(),
            //[TemplateType.Wrapper] = new KeyList<Guid, TypeTemplate>(),
            [TemplateType.Enum] = new KeyList<Guid, TypeTemplate>(),
        };

    static bool warehouseIsOpen = false;

    public delegate void StoreEvent(IStore store);//, string name);
                                                  // public delegate void StoreDisconnectedEvent(IStore store);

    public static event StoreEvent StoreConnected;
    //public static event StoreEvent StoreOpen;
    public static event StoreEvent StoreDisconnected;

    public delegate AsyncReply<IStore> ProtocolInstance(string name, object properties);

    public static KeyList<string, ProtocolInstance> Protocols { get; } = GetSupportedProtocols();

    private static Regex urlRegex = new Regex(@"^(?:([\S]*)://([^/]*)/?)");

    //private static object resourcesLock = new object();

    static KeyList<string, ProtocolInstance> GetSupportedProtocols()
    {
        var rt = new KeyList<string, ProtocolInstance>();
        rt.Add("iip", async (name, attributes) => await Warehouse.New<DistributedConnection>(name, null, null, null, attributes));
        return rt;
    }

    /// <summary>
    /// Get a store by its name.
    /// </summary>
    /// <param name="name">Store instance name</param>
    /// <returns></returns>
    public static IStore GetStore(string name)
    {
        foreach (var s in stores)
            if (s.Key.Instance.Name == name)
                return s.Key;
        return null;
    }

    public static WeakReference<IResource>[] Resources => resources.Values.ToArray();

    /// <summary>
    /// Get a resource by instance Id.
    /// </summary>
    /// <param name="id">Instance Id</param>
    /// <returns></returns>
    public static AsyncReply<IResource> GetById(uint id)
    {
        if (resources.ContainsKey(id))
        {
            IResource r;
            if (resources[id].TryGetTarget(out r))
                return new AsyncReply<IResource>(r);
            else
                return new AsyncReply<IResource>(null);
        }
        else
            return new AsyncReply<IResource>(null);
    }

    static void LoadGenerated()
    {
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            var generatedType = assembly.GetType("Esiur.Generated");
            if (generatedType != null)
            {
                var resourceTypes = (Type[])generatedType.GetProperty("Resources").GetValue(null);
                foreach (var t in resourceTypes)
                {
                    PutTemplate(new TypeTemplate(t));
                }

                var recordTypes = (Type[])generatedType.GetProperty("Records").GetValue(null);
                foreach (var t in recordTypes)
                {
                    PutTemplate(new TypeTemplate(t));
                }

                var enumsTypes = (Type[])generatedType.GetProperty("Enums").GetValue(null);
                foreach (var t in recordTypes)
                {
                    PutTemplate(new TypeTemplate(t));
                }
            }
        }
    }

    /// <summary>
    /// Open the warehouse.
    /// This function issues the initialize trigger to all stores and resources.
    /// </summary>
    /// <returns>True, if no problem occurred.</returns>
    public static async AsyncReply<bool> Open()
    {
        if (warehouseIsOpen)
            return false;

        // Load generated models
        LoadGenerated();

        warehouseIsOpen = true;

        var resSnap = resources.Select(x =>
        {
            IResource r;
            if (x.Value.TryGetTarget(out r))
                return r;
            else
                return null;
        }).Where(r => r != null).ToArray();

        foreach (var r in resSnap)
        {
            //IResource r;
            //if (rk.Value.TryGetTarget(out r))
            //{
            var rt = await r.Trigger(ResourceTrigger.Initialize);
            //if (!rt)
            //  return false;

            if (!rt)
            {
                Console.WriteLine($"Resource failed at Initialize {r.Instance.Name} [{r.Instance.Template.ClassName}]");
            }
            //}
        }

        foreach (var r in resSnap)
        {
            //IResource r;
            //if (rk.Value.TryGetTarget(out r))
            //{
            var rt = await r.Trigger(ResourceTrigger.SystemInitialized);
            if (!rt)
            {
                Console.WriteLine($"Resource failed at SystemInitialized {r.Instance.Name} [{r.Instance.Template.ClassName}]");
            }
            //return false;
            //}
        }

        return true;

        /*
        var bag = new AsyncBag<bool>();

        //foreach (var store in stores)
        //    bag.Add(store.Trigger(ResourceTrigger.Initialize));

        bag.Seal();

        var rt = new AsyncReply<bool>();
        bag.Then((x) =>
        {
            foreach (var b in x)
                if (!b)
                {
                    rt.Trigger(false);
                    return;
                }

            var rBag = new AsyncBag<bool>();
            foreach (var rk in resources)
            {
                IResource r;
                if (rk.Value.TryGetTarget(out r))
                    rBag.Add(r.Trigger(ResourceTrigger.Initialize));
            }

            rBag.Seal();

            rBag.Then(y =>
            {
                foreach (var b in y)
                    if (!b)
                    {
                        rt.Trigger(false);
                        return;
                    }

                rt.Trigger(true);
                warehouseIsOpen = true;
            });

        });

        return rt;
        */
    }

    /// <summary>
    /// Close the warehouse.
    /// This function issues terminate trigger to all resources and stores.
    /// </summary>
    /// <returns>True, if no problem occurred.</returns>
    public static AsyncReply<bool> Close()
    {

        var bag = new AsyncBag<bool>();

        foreach (var resource in resources.Values)
        {
            IResource r;
            if (resource.TryGetTarget(out r))
            {
                if (!(r is IStore))
                    bag.Add(r.Trigger(ResourceTrigger.Terminate));

            }
        }

        foreach (var store in stores)
            bag.Add(store.Key.Trigger(ResourceTrigger.Terminate));

        foreach (var resource in resources.Values)
        {
            IResource r;
            if (resource.TryGetTarget(out r))
            {
                if (!(r is IStore))
                    bag.Add(r.Trigger(ResourceTrigger.SystemTerminated));
            }
        }

        foreach (var store in stores)
            bag.Add(store.Key.Trigger(ResourceTrigger.SystemTerminated));

        bag.Seal();

        var rt = new AsyncReply<bool>();
        bag.Then((x) =>
        {
            foreach (var b in x)
                if (!b)
                {
                    rt.Trigger(false);
                    return;
                }

            rt.Trigger(true);
        });

        return rt;
    }

    /*
    private static IResource[] QureyIn(string[] path, int index, IEnumerable<IResource> resources)// AutoList<IResource, Instance> resources)
    {
        var rt = new List<IResource>();

        if (index == path.Length - 1)
        {
            if (path[index] == "")
                foreach (IResource child in resources)
                  rt.Add(child);
             else
                foreach (IResource child in resources)
                    if (child.Instance.Name == path[index])
                        rt.Add(child);
        }
        else
            foreach (IResource child in resources)
                if (child.Instance.Name == path[index])
                    rt.AddRange(QureyIn(path, index+1, child.Instance.Children<IResource>()));

        return rt.ToArray();
    }

    public static AsyncReply<IResource[]> Query(string path)
    {
        if (path == null || path == "")
        {
            var roots = stores.Where(s => s.Instance.Parents<IResource>().Count() == 0).ToArray();
            return new AsyncReply<IResource[]>(roots);
        }
        else
        {
            var rt = new AsyncReply<IResource[]>();
            Get(path).Then(x =>
            {
                var p = path.Split('/');

                if (x == null)
                {
                    rt.Trigger(QureyIn(p, 0, stores));
                }
                else
                {
                    var ar = QureyIn(p, 0, stores).Where(r => r != x).ToList();
                    ar.Insert(0, x);
                    rt.Trigger(ar.ToArray());
                }
            });

            return rt;

        }

    }
    */

    public static async AsyncReply<IResource[]> Query(string path)
    {
        var rt = new AsyncReply<IResource[]>();

        var p = path.Trim().Split('/');
        IResource resource;

        foreach (var store in stores.Keys)
            if (p[0] == store.Instance.Name)
            {

                if (p.Length == 1)
                    return new IResource[] { store };

                var res = await store.Get(String.Join("/", p.Skip(1).ToArray()));
                if (res != null)
                    return new IResource[] { res };

                resource = store;
                for (var i = 1; i < p.Length; i++)
                {
                    var children = await resource.Instance.Children<IResource>(p[i]);
                    if (children.Length > 0)
                    {
                        if (i == p.Length - 1)
                            return children;
                        else
                            resource = children[0];
                    }
                    else
                        break;
                }

                return null;
            }

        return null;
    }

    /// <summary>
    /// Get a resource by its path.
    /// Resource path is sperated by '/' character, e.g. "system/http".
    /// </summary>
    /// <param name="path"></param>
    /// <returns>Resource instance.</returns>
    public static async AsyncReply<T> Get<T>(string path, object attributes = null, IResource parent = null, IPermissionsManager manager = null)
        where T : IResource
    {
        //var rt = new AsyncReply<IResource>();

        // Should we create a new store ?

        if (urlRegex.IsMatch(path))
        {

            var url = urlRegex.Split(path);

            if (Protocols.ContainsKey(url[1]))
            {
                if (!warehouseIsOpen)
                    await Open();

                var handler = Protocols[url[1]];
                var store = await handler(url[2], attributes);

                try
                {
                    //await Put(store, url[2], null, parent, null, 0, manager, attributes);

                    if (url[3].Length > 0 && url[3] != "")
                        return (T)await store.Get(url[3]);
                    else
                        return (T)store;

                }
                catch (Exception ex)
                {
                    Warehouse.Remove(store);
                    throw ex;
                }

            }

            //    store.Get(url[3]).Then(r =>
            //        {
            //            rt.Trigger(r);
            //        }).Error(e =>
            //        {
            //            Warehouse.Remove(store);
            //            rt.TriggerError(e);
            //        });
            //    else
            //        rt.Trigger(store);

            //    store.Trigger(ResourceTrigger.Open).Then(x =>
            //    {

            //        warehouseIsOpen = true;
            //        await Put(store, url[2], null, parent, null, 0, manager, attributes);

            //        if (url[3].Length > 0 && url[3] != "")
            //            store.Get(url[3]).Then(r =>
            //            {
            //                rt.Trigger(r);
            //            }).Error(e =>
            //            {
            //                Warehouse.Remove(store);
            //                rt.TriggerError(e);
            //            });
            //        else
            //            rt.Trigger(store);
            //    }).Error(e =>
            //    {
            //        rt.TriggerError(e);
            //        //Warehouse.Remove(store);
            //    });

            //    return rt;
            //}
        }

        //await Query(path).Then(rs =>
        //{
        //    //                rt.TriggerError(new Exception());
        //    if (rs != null && rs.Length > 0)
        //        rt.Trigger(rs.First());
        //    else
        //        rt.Trigger(null);
        //});

        //return rt;

        var res = await Query(path);

        if (res.Length == 0)
            return default(T);
        else
            return (T)res.First();

    }

    //public static async AsyncReply<T> Push<T>(string path, T resource) where T : IResource
    //{
    //    await Put(path, resource);
    //    return resource;
    //}

    /// <summary>
    /// Put a resource in the warehouse.
    /// </summary>
    /// <param name="name">Resource name.</param>
    /// <param name="resource">Resource instance.</param>
    /// <param name="store">IStore that manages the resource. Can be null if the resource is a store.</param>
    /// <param name="parent">Parent resource. if not presented the store becomes the parent for the resource.</param>
    public static async AsyncReply<T> Put<T>(string name, T resource, IStore store = null, IResource parent = null, TypeTemplate customTemplate = null, ulong age = 0, IPermissionsManager manager = null, object attributes = null) where T : IResource
    {
        if (resource.Instance != null)
            throw new Exception("Resource has a store.");

        var path = name.TrimStart('/').Split('/');

        if (path.Length > 1)
        {
            if (parent != null)
                throw new Exception("Parent can't be set when using path in instance name");

            parent = await Warehouse.Get<IResource>(string.Join("/", path.Take(path.Length - 1)));

            if (parent == null)
                throw new Exception("Can't find parent");

            store = store ?? parent.Instance.Store;
        }

        var instanceName = path.Last();

        var resourceReference = new WeakReference<IResource>(resource);

        if (store == null)
        {
            // assign parent's store as a store
            if (parent != null)
            {
                // assign parent as a store
                if (parent is IStore)
                {
                    store = (IStore)parent;
                    List<WeakReference<IResource>> list;
                    if (stores.TryGetValue(store, out list))
                        lock (((ICollection)list).SyncRoot)
                            list.Add(resourceReference);
                    //stores[store].Add(resourceReference);
                }
                else
                {
                    store = parent.Instance.Store;

                    List<WeakReference<IResource>> list;
                    if (stores.TryGetValue(store, out list))
                        lock (((ICollection)list).SyncRoot)
                            list.Add(resourceReference);
                }
            }
            // assign self as a store (root store)
            else if (resource is IStore)
            {
                store = (IStore)resource;
            }
            else
                throw new Exception("Can't find a store for the resource.");
        }

        resource.Instance = new Instance(resourceCounter++, instanceName, resource, store, customTemplate, age);

        if (attributes != null)
            resource.Instance.SetAttributes(Map<string, object>.FromObject(attributes));

        if (manager != null)
            resource.Instance.Managers.Add(manager);

        if (store == parent)
            parent = null;

        try
        {
            if (resource is IStore)
                stores.TryAdd(resource as IStore, new List<WeakReference<IResource>>());

            if (!await store.Put(resource))
                throw new Exception("Store failed to put the resource");
            //return default(T);

            if (parent != null)
            {
                await parent.Instance.Store.AddChild(parent, resource);
                await store.AddParent(resource, parent);
            }

            var t = resource.GetType();
            Global.Counters["T-" + t.Namespace + "." + t.Name]++;

            resources.TryAdd(resource.Instance.Id, resourceReference);

            if (warehouseIsOpen)
            {
                await resource.Trigger(ResourceTrigger.Initialize);
                if (resource is IStore)
                    await resource.Trigger(ResourceTrigger.Open);
            }

            if (resource is IStore)
                StoreConnected?.Invoke(resource as IStore);
        }
        catch (Exception ex)
        {
            Warehouse.Remove(resource);
            throw ex;
        }

        return resource;

    }

    public static async AsyncReply<IResource> New(Type type, string name = null, IStore store = null, IResource parent = null, IPermissionsManager manager = null, object attributes = null, object properties = null)
    {

        type = ResourceProxy.GetProxy(type);

        /*
        if (arguments != null)
        {
            var constructors = type.GetConstructors(System.Reflection.BindingFlags.Public);

            foreach(var constructor in constructors)
            {
                var pi = constructor.GetParameters();
                if (pi.Length == constructor.le)
            }

            // cast arguments
            ParameterInfo[] pi = fi.GetParameters();

            object[] args = new object[pi.Length];

            for (var i = 0; i < pi.Length; i++)
            {
                if (pi[i].ParameterType == typeof(DistributedConnection))
                {
                    args[i] = this;
                }
                else if (namedArgs.ContainsKey(pi[i].Name))
                {
                    args[i] = DC.CastConvert(namedArgs[pi[i].Name], pi[i].ParameterType);
                }
            }

            constructors[0].
        }
        */
        var res = Activator.CreateInstance(type) as IResource;

        if (properties != null)
        {
            var ps = Map<string, object>.FromObject(properties);

            foreach (var p in ps)
            {

                var pi = type.GetProperty(p.Key, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                if (pi != null)
                {
                    if (pi.CanWrite)
                    {
                        try
                        {
                            pi.SetValue(res, p.Value);
                        }
                        catch (Exception ex)
                        {
                            Global.Log(ex);
                        }
                    }
                }
                else
                {
                    var fi = type.GetField(p.Key, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
                    if (fi != null)
                    {
                        try
                        {
                            fi.SetValue(res, p.Value);
                        }
                        catch (Exception ex)
                        {
                            Global.Log(ex);
                        }
                    }
                }
            }
        }

        if (store != null || parent != null || res is IStore)
        {
            //if (!await Put(name, res, store, parent, null, 0, manager, attributes))
            //    return null;

            await Put(name, res, store, parent, null, 0, manager, attributes);
        }

        return res;

    }

    public static async AsyncReply<T> New<T>(string name, IStore store = null, IResource parent = null, IPermissionsManager manager = null, object attributes = null, object properties = null)
        where T : IResource
    {
        return (T)(await New(typeof(T), name, store, parent, manager, attributes, properties));
    }

    /// <summary>
    /// Put a resource template in the templates warehouse.
    /// </summary>
    /// <param name="template">Resource template.</param>
    public static void PutTemplate(TypeTemplate template)
    {
        if (templates[template.Type].ContainsKey(template.ClassId))
            throw new Exception($"Template with same class Id already exists. {templates[template.Type][template.ClassId].ClassName} -> {template.ClassName}");

        templates[template.Type][template.ClassId] = template;
    }

    /// <summary>
    /// Get a template by type from the templates warehouse. If not in the warehouse, a new ResourceTemplate is created and added to the warehouse.
    /// </summary>
    /// <param name="type">.Net type.</param>
    /// <returns>Resource template.</returns>
    public static TypeTemplate GetTemplateByType(Type type)
    {
        var baseType = ResourceProxy.GetBaseType(type);

        if (baseType == typeof(IResource)
            || baseType == typeof(IRecord))
            return null;

        TemplateType templateType;
        if (Codec.ImplementsInterface(type, typeof(IResource)))
            templateType = TemplateType.Resource;
        else if (Codec.ImplementsInterface(type, typeof(IRecord)))
            templateType = TemplateType.Record;
        else if (type.IsEnum)
            templateType = TemplateType.Enum;
        else
            return null;

        var template = templates[templateType].Values.FirstOrDefault(x => x.DefinedType == baseType);
        if (template != null)
            return template;

        // create new template for type
        template = new TypeTemplate(baseType, true);
        TypeTemplate.GetDependencies(template);

        return template;
    }

    /// <summary>
    /// Get a template by class Id from the templates warehouse. If not in the warehouse, a new ResourceTemplate is created and added to the warehouse.
    /// </summary>
    /// <param name="classId">Class Id.</param>
    /// <returns>Resource template.</returns>
    public static TypeTemplate GetTemplateByClassId(Guid classId, TemplateType? templateType = null)
    {
        if (templateType == null)
        {
            // look into resources
            var template = templates[TemplateType.Resource][classId];
            if (template != null)
                return template;

            // look into records
            template = templates[TemplateType.Record][classId];
            if (template != null)
                return template;

            // look into enums
            template = templates[TemplateType.Enum][classId];
            return template;
            //if (template != null)

            //// look in wrappers
            //template = templates[TemplateType.Wrapper][classId];
            //return template;
        }
        else
            return templates[templateType.Value][classId];

    }

    /// <summary>
    /// Get a template by class name from the templates warehouse. If not in the warehouse, a new ResourceTemplate is created and added to the warehouse.
    /// </summary>
    /// <param name="className">Class name.</param>
    /// <returns>Resource template.</returns>
    public static TypeTemplate GetTemplateByClassName(string className, TemplateType? templateType = null)
    {
        if (templateType == null)
        {
            // look into resources
            var template = templates[TemplateType.Resource].Values.FirstOrDefault(x => x.ClassName == className);
            if (template != null)
                return template;

            // look into records
            template = templates[TemplateType.Record].Values.FirstOrDefault(x => x.ClassName == className);
            if (template != null)
                return template;

            // look into enums
            template = templates[TemplateType.Enum].Values.FirstOrDefault(x => x.ClassName == className);
            //if (template != null)
            return template;

            //// look in wrappers
            //template = templates[TemplateType.Wrapper].Values.FirstOrDefault(x => x.ClassName == className);
            //return template;
        }
        else
        {
            return templates[templateType.Value].Values.FirstOrDefault(x => x.ClassName == className);
        }
    }

    public static bool Remove(IResource resource)
    {

        if (resource.Instance == null)
            return false;

        //lock (resourcesLock)
        //{

        WeakReference<IResource> resourceReference;

        if (resources.ContainsKey(resource.Instance.Id))
            resources.TryRemove(resource.Instance.Id, out resourceReference);
        else
            return false;

        if (resource != resource.Instance.Store)
        {
            List<WeakReference<IResource>> list;
            if (stores.TryGetValue(resource.Instance.Store, out list))
            {

                lock (((ICollection)list).SyncRoot)
                    list.Remove(resourceReference);

            }
        }
        if (resource is IStore)
        {
            var store = resource as IStore;

            List<WeakReference<IResource>> toBeRemoved;

            stores.TryRemove(store, out toBeRemoved);

            foreach (var o in toBeRemoved)
            {
                IResource r;
                if (o.TryGetTarget(out r))
                    Remove(r);
            }

            StoreDisconnected?.Invoke(resource as IStore);
        }

        if (resource.Instance.Store != null)
            resource.Instance.Store.Remove(resource);

        resource.Destroy();

        return true;
    }
}


text:
package org.redisson.api;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * Redis based implementation of {@link java.util.concurrent.ScheduledExecutorService}
 *
 * @author Nikita Koksharov
 *
 */
public interface RScheduledExecutorServiceAsync extends RExecutorServiceAsync {

    /**
     * Creates in async mode and executes a one-shot action that becomes enabled
     * after the given delay.
     *
     * @param task the task to execute
     * @param delay the time from now to delay execution
     * @param unit the time unit of the delay parameter
     * @return RScheduledFuture with listeners support
     */
    RScheduledFuture<?> scheduleAsync(Runnable task, long delay, TimeUnit unit);

    /**
     * Creates in async mode and executes a ScheduledFuture that becomes enabled after the
     * given delay.
     *
     * @param task the function to execute
     * @param delay the time from now to delay execution
     * @param unit the time unit of the delay parameter
     * @param <V> the type of the callable's result
     * @return RScheduledFuture with listeners support
     */
    <V> RScheduledFuture<V> scheduleAsync(Callable<V> task, long delay, TimeUnit unit);

    /**
     * Creates in async mode and executes a periodic action that becomes enabled first
     * after the given initial delay, and subsequently with the given
     * period.
     * If any execution of the task
     * encounters an exception, subsequent executions are suppressed.
     * Otherwise, the task will only terminate via cancellation or
     * termination of the executor.  If any execution of this task
     * takes longer than its period, then subsequent executions
     * may start late, but will not concurrently execute.
     *
     * @param task the task to execute
     * @param initialDelay the time to delay first execution
     * @param period the period between successive executions
     * @param unit the time unit of the initialDelay and period parameters
     * @return RScheduledFuture with listeners support
     */
    RScheduledFuture<?> scheduleAtFixedRateAsync(Runnable task, long initialDelay, long period, TimeUnit unit);

    /**
     * Creates in async mode and executes a periodic action that becomes enabled first
     * after the given initial delay, and subsequently with the
     * given delay between the termination of one execution and the
     * commencement of the next.  If any execution of the task
     * encounters an exception, subsequent executions are suppressed.
     * Otherwise, the task will only terminate via cancellation or
     * termination of the executor.
     *
     * @param task the task to execute
     * @param initialDelay the time to delay first execution
     * @param delay the delay between the termination of one
     * execution and the commencement of the next
     * @param unit the time unit of the initialDelay and delay parameters
     * @return RScheduledFuture with listeners support
     */
    RScheduledFuture<?> scheduleWithFixedDelayAsync(Runnable task, long initialDelay, long delay, TimeUnit unit);

    /**
     * Creates in async mode and executes a periodic action with cron schedule object.
     * If any execution of the task
     * encounters an exception, subsequent executions are suppressed.
     * Otherwise, the task will only terminate via cancellation or
     * termination of the executor.  If any execution of this task
     * takes longer than its period, then subsequent executions
     * may start late, but will not concurrently execute.
     *
     * @param task the task to execute
     * @param cronSchedule cron schedule object
     * @return RScheduledFuture with listeners support
     */
    RScheduledFuture<?> scheduleAsync(Runnable task, CronSchedule cronSchedule);
}


text:
<?

class Login_Action implements IContentAdictedAction
{
	public function execute($c, $rd)
	{
		$c->set('core.layout', false);

		if(isset($rd['submit']))
		{
			$c->setAttribute('user', $rd['user']);

			if($c->getUser()->login($rd['user'], $rd['pass']))
			{
				$c->set('core.layout', true);
				$c->forward('start');
			}
			sleep(3);
			$c->getUser()->setMessage('Benutzername oder Passwort ist falsch.', 'error');
		}
		$c->setAttribute('user', '');
	}

	public function isSecure()
	{
		return false;
	}
}

?>


text:
package nl.tno.stormcv.example.util;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import backtype.storm.task.TopologyContext;
import nl.tno.stormcv.model.CVParticle;
import nl.tno.stormcv.model.Feature;
import nl.tno.stormcv.model.Frame;
import nl.tno.stormcv.model.serializer.CVParticleSerializer;
import nl.tno.stormcv.model.serializer.FrameSerializer;
import nl.tno.stormcv.operation.ISingleInputOperation;

public class OpticalFlowVisualizeOp implements ISingleInputOperation<Frame>{

	private static final long serialVersionUID = 1183401329954092073L;
	private String featureName;

	public OpticalFlowVisualizeOp(String featureName) {
		this.featureName = featureName;
	}

	@Override
	public void deactivate() {	}

	@Override
	public CVParticleSerializer<Frame> getSerializer() {
		return new FrameSerializer();
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void prepare(Map arg0, TopologyContext arg1) throws Exception {	}

	@Override
	public List<Frame> execute(CVParticle particle) throws Exception {
		List<Frame> result = new ArrayList<Frame>();
		if(!(particle instanceof Feature) ) return result;
		Feature of = (Feature)particle;
		if(!of.getName().equals(featureName)) return result;

		float[][][] dense = of.getDenseDescriptors();
		BufferedImage image = new BufferedImage(dense.length, dense[0].length, BufferedImage.TYPE_INT_RGB);

		for(int x=0; x<dense.length; x++){
			for(int y=0; y<dense[x].length; y++){
				float v = (float) Math.sqrt(Math.pow(dense[x][y][0],2) + Math.pow(dense[x][y][1], 2));
				v = Math.min(v, 1);
				image.setRGB(x, y, new Color(v, v, v).getRGB());
			}
		}
		result.add(new Frame(of.getStreamId(), of.getSequenceNr(), Frame.JPG_IMAGE, image, 0, new Rectangle(0,0,image.getWidth(), image.getHeight())));
		return result;
	}

}


text:
'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var path = require('path');
var cp = require('child_process');
var assert = require('assert');

var SDKBase = require('sdk-base');

var _require = require('lodash'),
    merge = _require.merge;

var ROLE = require('./constant/role');
var util = require('./util');

var LibraryWorker = function (_SDKBase) {
  _inherits(LibraryWorker, _SDKBase);

  function LibraryWorker() {
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
        libraryPath = _ref.libraryPath,
        logger = _ref.logger,
        sockPath = _ref.sockPath;

    _classCallCheck(this, LibraryWorker);

    var _this = _possibleConstructorReturn(this, (LibraryWorker.__proto__ || Object.getPrototypeOf(LibraryWorker)).call(this));

    _this.libraryPath = libraryPath;
    _this.logger = logger;
    _this.sockPath = sockPath;

    assert(util.exists(_this.libraryPath), `libraryPath ${_this.libraryPath} 不存在或不是一个文件`);

    _this.worker = null;
    return _this;
  }

  _createClass(LibraryWorker, [{
    key: 'init',
    value: function init() {
      this.fork();
    }
  }, {
    key: 'fork',
    value: function fork() {
      var _this2 = this;

      var libraryPath = this.libraryPath,
          logger = this.logger,
          sockPath = this.sockPath;

      var env = merge(process.env, {
        ROLE: ROLE.LIBRARY,
        LIBRARY_PATH: libraryPath,
        SOCK_PATH: sockPath
      });
      var worker = cp.fork(path.join(__dirname, './client/fork_library.js'), { env });

      worker.on('message', function (message) {
        if (message && message.ready) {
          _this2.ready(true);
        }
      });

      logger.info(`library worker fork pid = ${worker.pid}`);

      worker.on('error', logger.error);
      worker.once('exit', function (code, signal) {
        logger.error(`library worker exit code = ${code}, signal = ${signal}`);

        worker.removeAllListeners();
        if (process.env.NODE_ENV === 'production') {
          _this2.fork();
        }
      });

      this.worker = worker;
    }
  }]);

  return LibraryWorker;
}(SDKBase);

module.exports = LibraryWorker;


text:
@interface ClickableTextField : NSTextField

@property (nonatomic, strong) NSString *urlToOpen;

@end


text:
<?php

namespace GameBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * PlayerRoomRepository
*/
class PlayerRoomRepository extends EntityRepository
{
}


text:
import Syncable from "./syncable";

// this is a root type - basically adding fields from a config file to the repo record

export default class RootObject extends Syncable {
    key = "rootobject";
    dbCollection = "Repos";
    sortBy = "slug";
    configFileBodyField = "description";
    configFileSkippedKeys = ["id", "user", "repo", "contentHash", "temp"];
    configFileKeyOrder = ["title", "summary"];

    // return true if this node will be handled as this entity type
    // do we need to pass any other parameters?
    isClaimedNode(node, parentEntity, foundEntities) {
        if (node.path == "" && !parentEntity) return true;
        return false;
    }

    // assuming claimedNode returned true, process the node
    // assumes no need for access to other nodes in parent folder
    // if that is needed, override process directly.
    readEntityFromNode(n, parentEntity, foundEntities, handleFoundEntity, done) {
        let e = {
            // include all the standard repo properties so merge doesn't think they are being deleted
            ...this.dataHandler.repo.options,
            contentHash: n.hash,
            treeNode: n,
            title: this.dataHandler.repo.options.title || this.dataHandler.repo.options.remoteUrl
        };
        delete e.userSettings;

        handleFoundEntity("rootobject", e);

        this.dataHandler.processTreeNode(n, e, this.dataHandler.allEntityKeys, foundEntities, handleFoundEntity, function(err) {

            done(err);
        });
    }

    // load full version of an entity from git. callback result
    // should correspond directly to the objects in the database.
    populateFromGit(allEntities, entity, callback) {
        return callback(null, entity);
    }

    loadFromDb(handleFoundEntity, done) {
        let { dataHandler, dbCollection, key } = this;
        dataHandler.db[dbCollection].find({
            id: dataHandler.repo.options.id,
            user: dataHandler.repo.options.user
        }).each(function(err, item) {
            if (err || !item) return done(err, item);
            handleFoundEntity(key, item);
        });
    }

    matchMergedEntityDefinite(entity, possibleMatches, idMapping) {
        // there is always exactly one root entity in a repo, so it must match
        for (let mk in possibleMatches) {
            let e2 = possibleMatches[mk];
            return e2;
        }
    }

    getTreeNodesForEntity(allEntities, entity, index, callback) {
        let { dataHandler } = this;

        dataHandler.getTreeNodesForEntities(allEntities, entity, function(err, treeNodes) {
            if (err) return callback(err);
            callback(null, treeNodes);
        });

    }
}


text:
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(450, 300)
        Dialog.setMinimumSize(QtCore.QSize(450, 300))
        Dialog.setMaximumSize(QtCore.QSize(500, 400))
        self.gridLayout = QtGui.QGridLayout(Dialog)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.textBrowser = QtGui.QTextBrowser(Dialog)
        self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
        self.gridLayout.addWidget(self.textBrowser, 0, 0, 1, 1)

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "关于", None, QtGui.QApplication.UnicodeUTF8))
        self.textBrowser.setHtml(QtGui.QApplication.translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<meta name=\"qrichtext\" content=\"1\" />\n"
"
欢迎使用"多文件夹助手"!
\n"
"
简介:
\n"
"
本软件为免费绿色软件。主要用于进行文件夹批量建立。
\n"
"
主要功能:
\n"
"
1.根据blumind文件批量建立文件夹
\n"
"
2.根据现有文件夹生成blumind图形化文件
\n"
"
3.文件夹结构拷贝
\n"
"

\n"
"
需要源码联系 winxos@hotmail.com
\n"
"
winxos©2011
", None, QtGui.QApplication.UnicodeUTF8))

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/EC2CreateKeyPairRequestMarshaller.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/EC2CreateKeyPairRequestMarshaller</TokenIdentifier>
			<Abstract type="html">Create Key Pair Request Marshaller</Abstract>
			<DeclaredIn>EC2CreateKeyPairRequestMarshaller.h</DeclaredIn>

			<NodeRef refid="411"/>
		</Token>

	</File>
</Tokens>


text:
.mce-content-body *[contentEditable=true], .mce-content-body *[data-mce-contenteditable=true] {
	background: #adffad;
	border: 1px solid #999;
}

.mce-content-body *[contentEditable=false], .mce-content-body *[data-mce-contenteditable=false] {
	background: #ffadad;
	border: 1px solid #999;
	margin: 0 1px 0 2px;
}

.mce-content-body div[contentEditable=false], .mce-content-body p[contentEditable=false] {
	margin: 2px 0 2px 0;
}

.mce-content-body  *[contentEditable]:focus {
	outline: 2px dotted blue;
}

/* Debug overrides */

.mce-visual-caret {
	outline: 2px solid red;
}

.mce-visual-caret-before {
	outline: 2px solid green;
}

.mce-content-body *[data-mce-selected] {
	outline: 2px solid blue;
}

.mce-content-body .mce-offscreen-selection {
	left: auto;
	right: 0;
}

*[data-mce-caret] {
	outline: 1px solid green;
	position: absolute;
	left: auto;
	right: 0;
	top: 0;
	margin: 0;
	padding: 0;
}


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('frontend', '0072_remove_unused_models'),
    ]

    operations = [
        migrations.RunSQL('DROP MATERIALIZED VIEW IF EXISTS vw__medians_for_tariff'),
    ]


text:
/*-------------------------------------------------------------*/
/*---------------------------- F L A T ------------------------*/
/*-------------------------------------------------------------*/
CREATE TABLE flat (
	fid integer NOT NULL,
	address varchar(255),
	CONSTRAINT flat_pkey PRIMARY KEY (fid)
);

/*-------------------------------------------------------------*/
/*--------------------------- C A C H E -----------------------*/
/*-------------------------------------------------------------*/

CREATE TABLE calendarCache (
	cid integer NOT NULL,
	date datetime NOT NULL,
	fid integer NOT NULL,
	state integer NOT NULL DEFAULT '0',
	background integer NOT NULL DEFAULT '0',
	prepay integer NOT NULL DEFAULT '0',
	debt integer NOT NULL DEFAULT '0',
	casus integer NOT NULL DEFAULT '0',
	CONSTRAINT calendar_cache_pkey PRIMARY KEY (cid) autoincrement,
	CONSTRAINT calendar_cache_fkey FOREIGN KEY (fid)
	REFERENCES flat(fid)  MATCH FULL
	ON UPDATE CASCADE ON DELETE CASCADE,
	CONSTRAINT uc_dateFid UNIQUE (date,fid)
);

CREATE TABLE calendarCacheExt (
	cid integer NOT NULL,
	book_am integer NOT NULL DEFAULT '0',
	book_pm integer NOT NULL DEFAULT '0',
	rent_am integer NOT NULL DEFAULT '0',
	rent_pm integer NOT NULL DEFAULT '0',
	book_settlement integer NOT NULL DEFAULT '0',
	book_eviction integer NOT NULL DEFAULT '0',
	rent_settlement integer NOT NULL DEFAULT '0',
	rent_eviction integer NOT NULL DEFAULT '0',
	CONSTRAINT calendar_cache_ext_fkey FOREIGN KEY (cid)
	REFERENCES calendarCache(cid)  MATCH FULL
	ON UPDATE CASCADE ON DELETE CASCADE
);

CREATE TABLE state (
	sid integer NOT NULL,
	am integer NOT NULL,
	pm integer NOT NULL,
	settlement integer NOT NULL,
	eviction integer NOT NULL,
	CONSTRAINT state_pkey PRIMARY KEY (sid) autoincrement
);
/*-------------------------------------------------------------*/
/*------------------------ I N T E R V A L --------------------*/
/*-------------------------------------------------------------*/

CREATE TABLE interval (
	iid integer NOT NULL,
	date_from datetime NOT NULL,
	date_to datetime NOT NULL,
	CONSTRAINT interval_pkey PRIMARY KEY (iid)
);

CREATE TABLE intervalAnketa (
	iid integer NOT NULL,
	type integer NOT NULL,
	telephone_left varchar(255) NOT NULL DEFAULT '',
	telephone_right varchar(255) NOT NULL DEFAULT '',
	name_left varchar(255) NOT NULL DEFAULT '',
	name_right varchar(255) NOT NULL DEFAULT '',
	anketa text NOT NULL DEFAULT '',
	settlement varchar(255) NOT NULL DEFAULT '',
	eviction varchar(255) NOT NULL DEFAULT '',
	else_info text NOT NULL DEFAULT '',
	CONSTRAINT interval_anketa_fkey FOREIGN KEY (iid)
	REFERENCES interval(iid) MATCH FULL
	ON UPDATE CASCADE ON DELETE CASCADE
);

CREATE TABLE intervalFlat (
	fid integer NOT NULL,
	iid integer NOT NULL,
	CONSTRAINT interval_flat_fid_fkey FOREIGN KEY (fid)
	REFERENCES flat(fid) MATCH FULL ON DELETE CASCADE,
	CONSTRAINT interval_flat_iid_fkey FOREIGN KEY (iid)
	REFERENCES interval(iid) MATCH FULL ON DELETE CASCADE
);
/*-------------------------------------------------------------*/
/*--------------------------- M O N E Y -----------------------*/
/*-------------------------------------------------------------*/

CREATE TABLE money (
	mid integer NOT NULL,
	amount integer,
	CONSTRAINT money_pkey PRIMARY KEY (mid),
	CONSTRAINT money_check CHECK (amount >= '0' OR amount IS NULL)
);

CREATE TABLE payment (
	mid integer NOT NULL UNIQUE,
	price integer,
	CONSTRAINT payment_fkey FOREIGN KEY (mid)
	REFERENCES money(mid) MATCH FULL ON DELETE CASCADE,
	CONSTRAINT payment_check CHECK ((price >= '0' OR price IS NULL))
);

CREATE TABLE debt (
	mid integer NOT NULL UNIQUE,
	CONSTRAINT debt_fkey FOREIGN KEY (mid)
	REFERENCES money(mid) MATCH FULL ON DELETE CASCADE
);

CREATE TABLE prepay (
	mid integer NOT NULL UNIQUE,
	CONSTRAINT prepay_fkey FOREIGN KEY (mid)
	REFERENCES money(mid) MATCH FULL ON DELETE CASCADE
);

CREATE TABLE intervalMoney (
	iid integer NOT NULL,
	mid integer NOT NULL UNIQUE,
	CONSTRAINT interval_money_iid_fkey FOREIGN KEY (iid)
	REFERENCES interval(iid) MATCH FULL ON DELETE CASCADE,
	CONSTRAINT interval_money_mid_fkey FOREIGN KEY (mid)
	REFERENCES money(mid) MATCH FULL ON DELETE CASCADE
);
/*-------------------------------------------------------------*/
/*------------------------- E M P L O Y E E -------------------*/
/*-------------------------------------------------------------*/
CREATE TABLE employee (
	eid integer NOT NULL,
	name varchar(255) NOT NULL,
	CONSTRAINT employee_pkey PRIMARY KEY (eid)
);

CREATE TABLE director (
	eid INTEGER PRIMARY KEY,
	FOREIGN KEY (eid) REFERENCES employee(eid) ON DELETE CASCADE
);

CREATE TABLE manager (
	eid INTEGER PRIMARY KEY,
	FOREIGN KEY (eid) REFERENCES employee(eid) ON DELETE CASCADE
);

CREATE TABLE programmer (
	eid INTEGER PRIMARY KEY,
	FOREIGN KEY (eid) REFERENCES employee(eid) ON DELETE CASCADE
);

CREATE TABLE maiden (
	eid INTEGER PRIMARY KEY,
	mon integer NOT NULL DEFAULT '0',
	tue integer NOT NULL DEFAULT '0',
	wen integer NOT NULL DEFAULT '0',
	thu integer NOT NULL DEFAULT '0',
	fri integer NOT NULL DEFAULT '0',
	sat integer NOT NULL DEFAULT '0',
	sun integer NOT NULL DEFAULT '0',
	FOREIGN KEY (eid) REFERENCES employee(eid) ON DELETE CASCADE
);
/*-------------------------------------------------------------*/
/*--------------------------- M A I D E N ---------------------*/
/*-------------------------------------------------------------*/
CREATE TABLE cleanings (
	iid integer NOT NULL,
	eid integer NOT NULL,
	date datetime NOT NULL,
	CONSTRAINT interval_fkey FOREIGN KEY (iid)
	REFERENCES interval(iid) MATCH FULL ON DELETE CASCADE,
	CONSTRAINT employee_fkey FOREIGN KEY (eid)
	REFERENCES employee(eid) MATCH FULL ON DELETE CASCADE
);


text:
using Joyride.Extensions;
using Joyride.Platforms;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;

namespace Tests.Android.Native.SampleApp.ApiDemo.Screens.App
{
    public class AlertDialogsScreen : ApiDemoScreen
    {
        [FindsBy(How = How.Id, Using = "io.appium.android.apis:id/two_buttons")]
        private IWebElement OkCancelDialog;

        [FindsBy(How = How.Id, Using = "io.appium.android.apis:id/two_buttons2")]
        private IWebElement OkCancelDialogWithLongMessage ;

        public override bool IsOnScreen(int timeOutSecs)
        {
            var xpath = @"//android.widget.TextView[@text='App/Alert Dialogs']";
            var header = Driver.FindElement(By.XPath(xpath), timeOutSecs);
            return header != null;
        }

        public override string Name
        {
            get { return "Alert Dialogs"; }
        }

        public override Screen GoBack()
        {
            Driver.Navigate().Back();
            return ScreenFactory.CreateScreen<AppScreen>();
        }
    }
}


text:
<?php

/**
 * Adminhtml paypal settlement reports grid block
 *
 * @category    Mage
 * @package     Mage_Paypal
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Paypal_Block_Adminhtml_Settlement_Report_Grid extends Mage_Adminhtml_Block_Widget_Grid
{
    /**
     * Retain filter parameters in session
     *
     * @var bool
     */
    protected $_saveParametersInSession = true;

    /**
     * Constructor
     * Set main configuration of grid
     */
    public function __construct()
    {
        parent::__construct();
        $this->setId('settlementGrid');
        $this->setUseAjax(true);
    }

    /**
     * Prepare collection for grid
     * @return Mage_Paypal_Block_Adminhtml_Settlement_Grid
     */
    protected function _prepareCollection()
    {
        $collection = Mage::getResourceModel('paypal/report_settlement_row_collection');
        $this->setCollection($collection);
        if (!$this->getParam($this->getVarNameSort())) {
            $collection->setOrder('row_id', 'desc');
        }
        return parent::_prepareCollection();
    }

    /**
     * Prepare grid columns
     * @return Mage_Paypal_Block_Adminhtml_Settlement_Grid
     */
    protected function _prepareColumns()
    {
        $settlement = Mage::getSingleton('paypal/report_settlement');
        $this->addColumn('report_date', array(
            'header'    => $settlement->getFieldLabel('report_date'),
            'index'     => 'report_date',
            'type'     => 'date'
        ));
        $this->addColumn('account_id', array(
            'header'    => $settlement->getFieldLabel('account_id'),
            'index'     => 'account_id'
        ));
        $this->addColumn('transaction_id', array(
            'header'    => $settlement->getFieldLabel('transaction_id'),
            'index'     => 'transaction_id'
        ));
        $this->addColumn('invoice_id', array(
            'header'    => $settlement->getFieldLabel('invoice_id'),
            'index'     => 'invoice_id'
        ));
        $this->addColumn('paypal_reference_id', array(
            'header'    => $settlement->getFieldLabel('paypal_reference_id'),
            'index'     => 'paypal_reference_id'
        ));
        $this->addColumn('transaction_event_code', array(
            'header'    => $settlement->getFieldLabel('transaction_event'),
            'index'     => 'transaction_event_code',
            'type'      => 'options',
            'options'   => Mage::getModel('paypal/report_settlement_row')->getTransactionEvents()
        ));
        $this->addColumn('transaction_initiation_date', array(
            'header'    => $settlement->getFieldLabel('transaction_initiation_date'),
            'index'     => 'transaction_initiation_date',
            'type'      => 'datetime'
        ));
        $this->addColumn('transaction_completion_date', array(
            'header'    => $settlement->getFieldLabel('transaction_completion_date'),
            'index'     => 'transaction_completion_date',
            'type'      => 'datetime'
        ));
        $this->addColumn('gross_transaction_amount', array(
            'header'    => $settlement->getFieldLabel('gross_transaction_amount'),
            'index'     => 'gross_transaction_amount',
            'type'      => 'currency',
            'currency'  => 'gross_transaction_currency',
        ));
        $this->addColumn('fee_amount', array(
            'header'    => $settlement->getFieldLabel('fee_amount'),
            'index'     => 'fee_amount',
            'type'      => 'currency',
            'currency'  => 'gross_transaction_currency',
        ));
        return parent::_prepareColumns();
    }

    /**
     * Return grid URL
     * @return string
     */
    public function getGridUrl()
    {
         return $this->getUrl('*/*/grid');
    }

    /**
     * Return item view URL
     * @return string
     */
    public function getRowUrl($item)
    {
        return $this->getUrl('*/*/details', array('id' => $item->getId()));
    }
}


text:
package org.opensmartgridplatform.domain.core.valueobjects.smartmetering;

import java.util.EnumSet;
import java.util.Set;

public enum ClockStatusBit {

    INVALID_VALUE("invalid value"),
    DOUBTFUL_VALUE("doubtful value"),
    DIFFERENT_CLOCK_BASE("different clock base"),
    INVALID_CLOCK_STATUS("invalid clock status"),
    RESERVED_1("reserved"),
    RESERVED_2("reserved"),
    RESERVED_3("reserved"),
    DAYLIGHT_SAVING_ACTIVE("daylight saving active");

    private final String description;

    ClockStatusBit(final String description) {
        this.description = description;
    }

    public String getDescription() {
        return this.description;
    }

    public boolean isSet(final int clockStatus) {
        final int mask = 1 << this.ordinal();
        return mask == (mask & clockStatus);
    }

    @Override
    public String toString() {
        return this.description;
    }

    public static Set<ClockStatusBit> forClockStatus(final byte clockStatus) {
        return forClockStatus(clockStatus & 0xFF);
    }

    public static Set<ClockStatusBit> forClockStatus(final int clockStatus) {
        if (ClockStatus.STATUS_NOT_SPECIFIED == clockStatus) {
            return null;
        }
        if (clockStatus < 0 || clockStatus > 0xFF) {
            throw new IllegalArgumentException("clockStatus not in [0..255]");
        }
        final Set<ClockStatusBit> statusBits = EnumSet.noneOf(ClockStatusBit.class);
        for (final ClockStatusBit statusBit : values()) {
            if (statusBit.isSet(clockStatus)) {
                statusBits.add(statusBit);
            }
        }
        return statusBits;
    }

    public static int getStatus(final Set<ClockStatusBit> statusBits) {
        if (statusBits == null) {
            return ClockStatus.STATUS_NOT_SPECIFIED;
        }
        int status = 0;
        for (final ClockStatusBit statusBit : statusBits) {
            status |= (1 << statusBit.ordinal());
        }
        return status;
    }

}


text:
namespace AntMe.Basics.MapTiles
{
    /// <summary>
    /// Map Tile Info for the Cliff Walls.
    /// </summary>
    public class WallCliffMapTileInfo : CliffMapTileInfo
    {
        /// <summary>
        /// Default Constructor for the Type Mapper.
        /// </summary>
        /// <param name="tile">Reference to the Tile</param>
        /// <param name="observer">Observing Item</param>
        public WallCliffMapTileInfo(WallCliffMapTile tile, Item observer) : base(tile, observer)
        {
        }
    }
}


text:
module Jhc.ForeignPtr(
    ForeignPtr(),
    newPlainForeignPtr_,
    newForeignPtr_,
    mallocPlainForeignPtrAlignBytes,
    mallocForeignPtrAlignBytes,
    unsafeForeignPtrToPtr,
    castForeignPtr,
    touchForeignPtr
    ) where

import Jhc.Addr
import Jhc.IO
import Jhc.Prim.Rts
import Jhc.Basics

type FinalizerPtr  a = FunPtr (Ptr a -> IO ())

-- not Addr_ because we need to make sure it is allocated in a real heap
-- location. The actual ForeignPtr heap location may contain more than the
-- single BitsPtr_ argument.
data ForeignPtr a = FP BitsPtr_

-- | This function creates a plain ForeignPtr from a Ptr, a plain foreignptr
-- may not have finalizers associated with it, hence this function may be pure.
newPlainForeignPtr_ :: Ptr a -> ForeignPtr a
newPlainForeignPtr_  (Ptr (Addr_ addr)) = FP addr

newForeignPtr_ :: Ptr a -> IO (ForeignPtr a)
newForeignPtr_ ptr = fromUIO $ \w ->
    case gc_new_foreignptr ptr w of
        (# w', bp #) -> (# w', fromBang_ bp #)

-- | This function is similar to 'mallocForeignPtrAlignBytes', except that the
-- internally an optimised ForeignPtr representation with no finalizer is used.
-- Attempts to add a finalizer will cause the program to abort.
mallocPlainForeignPtrAlignBytes
    :: Int -- ^ alignment in bytes, must be power of 2. May be zero.
    -> Int -- ^ size to allocate in bytes.
    -> IO (ForeignPtr a)
mallocPlainForeignPtrAlignBytes align size = fromUIO $ \w ->
    case gc_malloc_foreignptr (int2word align) (int2word size) False w of
        (# w', bp #) -> (# w', fromBang_ bp #)

-- | Allocate memory of the given size and alignment that will automatically be
-- reclaimed. Any Finalizers that are attached to this will run before the
-- memory is freed.
mallocForeignPtrAlignBytes
    :: Int -- ^ alignment in bytes, must be power of 2. May be zero.
    -> Int -- ^ size to allocate in bytes.
    -> IO (ForeignPtr a)
mallocForeignPtrAlignBytes align size = fromUIO $ \w ->
    case gc_malloc_foreignptr (int2word align) (int2word size) True w of
        (# w', bp #) -> (# w', fromBang_ bp #)

foreign import safe ccall gc_malloc_foreignptr
    :: Word     -- alignment in words
    -> Word     -- size in words
    -> Bool     -- false for plain foreignptrs, true for ones with finalizers.
    -> UIO (Bang_ (ForeignPtr a))

foreign import safe ccall gc_new_foreignptr ::
    Ptr a -> UIO (Bang_ (ForeignPtr a))

foreign import unsafe ccall gc_add_foreignptr_finalizer
    :: Bang_ (ForeignPtr a)
    -> FinalizerPtr a
    -> IO ()

unsafeForeignPtrToPtr :: ForeignPtr a -> Ptr a
unsafeForeignPtrToPtr (FP x) = Ptr (Addr_ x)

touchForeignPtr :: ForeignPtr a -> IO ()
touchForeignPtr x = fromUIO_ (touch_ x)

castForeignPtr :: ForeignPtr a -> ForeignPtr b
castForeignPtr x = unsafeCoerce x

foreign import primitive touch_ :: ForeignPtr a -> UIO_
foreign import primitive "B2B" int2word :: Int -> Word
foreign import primitive unsafeCoerce :: a -> b


text:
package org.elasticsearch.search.aggregations.bucket.sampler;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.InternalAggregation.Type;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.aggregations.support.ValuesSource;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorBuilder;
import org.elasticsearch.search.aggregations.support.ValuesSourceAggregatorFactory;
import org.elasticsearch.search.aggregations.support.ValuesSourceConfig;
import org.elasticsearch.search.aggregations.support.ValuesSourceType;

import java.io.IOException;
import java.util.Objects;

public class DiversifiedAggregatorBuilder extends ValuesSourceAggregatorBuilder<ValuesSource, DiversifiedAggregatorBuilder> {
    public static final String NAME = "diversified_sampler";
    public static final ParseField AGGREGATION_NAME_FIELD = new ParseField(NAME);
    public static final Type TYPE = new Type(NAME);

    public static final int MAX_DOCS_PER_VALUE_DEFAULT = 1;

    private int shardSize = SamplerAggregatorBuilder.DEFAULT_SHARD_SAMPLE_SIZE;
    private int maxDocsPerValue = MAX_DOCS_PER_VALUE_DEFAULT;
    private String executionHint = null;

    public DiversifiedAggregatorBuilder(String name) {
        super(name, TYPE, ValuesSourceType.ANY, null);
    }

    /**
     * Read from a stream.
     */
    public DiversifiedAggregatorBuilder(StreamInput in) throws IOException {
        super(in, TYPE, ValuesSourceType.ANY, null);
        shardSize = in.readVInt();
        maxDocsPerValue = in.readVInt();
        executionHint = in.readOptionalString();
    }

    @Override
    protected void innerWriteTo(StreamOutput out) throws IOException {
        out.writeVInt(shardSize);
        out.writeVInt(maxDocsPerValue);
        out.writeOptionalString(executionHint);
    }

    /**
     * Set the max num docs to be returned from each shard.
     */
    public DiversifiedAggregatorBuilder shardSize(int shardSize) {
        if (shardSize < 0) {
            throw new IllegalArgumentException(
                    "[shardSize] must be greater than or equal to 0. Found [" + shardSize + "] in [" + name + "]");
        }
        this.shardSize = shardSize;
        return this;
    }

    /**
     * Get the max num docs to be returned from each shard.
     */
    public int shardSize() {
        return shardSize;
    }

    /**
     * Set the max num docs to be returned per value.
     */
    public DiversifiedAggregatorBuilder maxDocsPerValue(int maxDocsPerValue) {
        if (maxDocsPerValue < 0) {
            throw new IllegalArgumentException(
                    "[maxDocsPerValue] must be greater than or equal to 0. Found [" + maxDocsPerValue + "] in [" + name + "]");
        }
        this.maxDocsPerValue = maxDocsPerValue;
        return this;
    }

    /**
     * Get the max num docs to be returned per value.
     */
    public int maxDocsPerValue() {
        return maxDocsPerValue;
    }

    /**
     * Set the execution hint.
     */
    public DiversifiedAggregatorBuilder executionHint(String executionHint) {
        this.executionHint = executionHint;
        return this;
    }

    /**
     * Get the execution hint.
     */
    public String executionHint() {
        return executionHint;
    }

    @Override
    protected ValuesSourceAggregatorFactory<ValuesSource, ?> innerBuild(AggregationContext context,
            ValuesSourceConfig<ValuesSource> config, AggregatorFactory<?> parent, Builder subFactoriesBuilder) throws IOException {
        return new DiversifiedAggregatorFactory(name, TYPE, config, shardSize, maxDocsPerValue, executionHint, context, parent,
                subFactoriesBuilder, metaData);
    }

    @Override
    protected XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException {
        builder.field(SamplerAggregator.SHARD_SIZE_FIELD.getPreferredName(), shardSize);
        builder.field(SamplerAggregator.MAX_DOCS_PER_VALUE_FIELD.getPreferredName(), maxDocsPerValue);
        if (executionHint != null) {
            builder.field(SamplerAggregator.EXECUTION_HINT_FIELD.getPreferredName(), executionHint);
        }
        return builder;
    }

    @Override
    protected int innerHashCode() {
        return Objects.hash(shardSize, maxDocsPerValue, executionHint);
    }

    @Override
    protected boolean innerEquals(Object obj) {
        DiversifiedAggregatorBuilder other = (DiversifiedAggregatorBuilder) obj;
        return Objects.equals(shardSize, other.shardSize)
                && Objects.equals(maxDocsPerValue, other.maxDocsPerValue)
                && Objects.equals(executionHint, other.executionHint);
    }

    @Override
    public String getWriteableName() {
        return NAME;
    }
}


text:
var reactiveDict;

/*------------------------------------------------------------------------------------------------------------------------------*/
Template.tagsEdit.helpers({
    typeaheadTags: function(){
        return reactiveDict.get('typeaheadTags');
    }
});
/*------------------------------------------------------------------------------------------------------------------------------*/
Template.tagsEdit.created = function() {
    reactiveDict = new ReactiveDict();
    reactiveDict.set('typeaheadTags', null);
};
/*------------------------------------------------------------------------------------------------------------------------------*/
Template.tagsEdit.destroyed = function() {
};
/*------------------------------------------------------------------------------------------------------------------------------*/
Template.tagsEdit.events({
    'click .tagged': function(e, template){
        // CANNOT USE "THIS" HERE
        var self = template.data;
        e.preventDefault();
        var diagram_id = self.options.diagram_id;

        var tag = $(e.currentTarget).attr('data-tag');
        if (!self.options.removeTag){
            console.log('Missing removeTag function');
            return false;
        }
        self.options.removeTag(diagram_id, tag);
    },
    'click #addTagID': function(e) {
        e.preventDefault();
        var $inputTagID = $('#inputTagID');
        $inputTagID.val('');
        $inputTagID.focus();
    },
    'keyup #inputTagID': function(e, template) {
        e.preventDefault();
        var self = template.data;

        if (e.which == 13) {//ENTER
            var tag = validateTag( $(e.currentTarget).val() );
            if (!tag) return false;
            if (!self.options.addTag){
                console.log('Missing addTag function');
                return false;
            }
            var diagram_id = self.options.diagram_id;
            self.options.addTag(diagram_id, tag);
            $(e.currentTarget).val('');
            reactiveDict.set('typeaheadTags', null);
        } else if (e.which == 27) {//ESC
            $(e.currentTarget).val('');
            reactiveDict.set('typeaheadTags', null);
        } else {
            var searchText = $('#inputTagID').val();
            if (!searchText) {
                reactiveDict.set('typeaheadTags', null);
                return;
            }
            // user settings for regex - RegExp.escape, startsWith
            searchText = RegExp.escape(searchText);
            var showableTags = _.difference(self.options.allTags, self.tags);
            if (showableTags) {
                var items = [];
                _.each(showableTags, function (tag) {
                    var myRe = new RegExp(".*" + searchText + ".*");//, "g");
                    var myArray = myRe.exec(tag);
                    if (myArray && myArray.length != 0) {
                        items.push(tag);
                    }
                });
                reactiveDict.set('typeaheadTags', items);
            }
        }
    },
    'blur #inputTagID': function(e) {
        $(e.currentTarget).val('');
    },
    'click ul>a.typeahead': function(e, template){
        // CANNOT USE "THIS" HERE
        var self = template.data;
        e.preventDefault();
        var tag = $(e.currentTarget).attr('data-tag');
        if (!self.options.addTag){
            console.log('Missing addTag function');
            return false;
        }
        var diagram_id = self.options.diagram_id;
        self.options.addTag(diagram_id, tag);
        reactiveDict.set('typeaheadTags', null);
        $('#inputTagID').focus();
    }
});
/*------------------------------------------------------------------------------------------------------------------------------*/
Template.tagsEdit.rendered = function() {
};
/*------------------------------------------------------------------------------------------------------------------------------*/